disable_annotation_reply_task.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import logging
  2. import time
  3. import click
  4. from celery import shared_task
  5. from werkzeug.exceptions import NotFound
  6. from core.rag.datasource.vdb.vector_factory import Vector
  7. from extensions.ext_database import db
  8. from extensions.ext_redis import redis_client
  9. from models.dataset import Dataset
  10. from models.model import App, AppAnnotationSetting, MessageAnnotation
  11. @shared_task(queue='dataset')
  12. def disable_annotation_reply_task(job_id: str, app_id: str, tenant_id: str):
  13. """
  14. Async enable annotation reply task
  15. """
  16. logging.info(click.style('Start delete app annotations index: {}'.format(app_id), fg='green'))
  17. start_at = time.perf_counter()
  18. # get app info
  19. app = db.session.query(App).filter(
  20. App.id == app_id,
  21. App.tenant_id == tenant_id,
  22. App.status == 'normal'
  23. ).first()
  24. annotations_count = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app_id).count()
  25. if not app:
  26. raise NotFound("App not found")
  27. app_annotation_setting = db.session.query(AppAnnotationSetting).filter(
  28. AppAnnotationSetting.app_id == app_id
  29. ).first()
  30. if not app_annotation_setting:
  31. raise NotFound("App annotation setting not found")
  32. disable_app_annotation_key = 'disable_app_annotation_{}'.format(str(app_id))
  33. disable_app_annotation_job_key = 'disable_app_annotation_job_{}'.format(str(job_id))
  34. try:
  35. dataset = Dataset(
  36. id=app_id,
  37. tenant_id=tenant_id,
  38. indexing_technique='high_quality',
  39. collection_binding_id=app_annotation_setting.collection_binding_id
  40. )
  41. try:
  42. if annotations_count > 0:
  43. vector = Vector(dataset, attributes=['doc_id', 'annotation_id', 'app_id'])
  44. vector.delete_by_metadata_field('app_id', app_id)
  45. except Exception:
  46. logging.exception("Delete annotation index failed when annotation deleted.")
  47. redis_client.setex(disable_app_annotation_job_key, 600, 'completed')
  48. # delete annotation setting
  49. db.session.delete(app_annotation_setting)
  50. db.session.commit()
  51. end_at = time.perf_counter()
  52. logging.info(
  53. click.style('App annotations index deleted : {} latency: {}'.format(app_id, end_at - start_at),
  54. fg='green'))
  55. except Exception as e:
  56. logging.exception("Annotation batch deleted index failed:{}".format(str(e)))
  57. redis_client.setex(disable_app_annotation_job_key, 600, 'error')
  58. disable_app_annotation_error_key = 'disable_app_annotation_error_{}'.format(str(job_id))
  59. redis_client.setex(disable_app_annotation_error_key, 600, str(e))
  60. finally:
  61. redis_client.delete(disable_app_annotation_key)