disable_annotation_reply_task.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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(App.id == app_id, App.tenant_id == tenant_id, App.status == "normal").first()
  20. annotations_count = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app_id).count()
  21. if not app:
  22. raise NotFound("App not found")
  23. app_annotation_setting = (
  24. db.session.query(AppAnnotationSetting).filter(AppAnnotationSetting.app_id == app_id).first()
  25. )
  26. if not app_annotation_setting:
  27. raise NotFound("App annotation setting not found")
  28. disable_app_annotation_key = "disable_app_annotation_{}".format(str(app_id))
  29. disable_app_annotation_job_key = "disable_app_annotation_job_{}".format(str(job_id))
  30. try:
  31. dataset = Dataset(
  32. id=app_id,
  33. tenant_id=tenant_id,
  34. indexing_technique="high_quality",
  35. collection_binding_id=app_annotation_setting.collection_binding_id,
  36. )
  37. try:
  38. if annotations_count > 0:
  39. vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"])
  40. vector.delete_by_metadata_field("app_id", app_id)
  41. except Exception:
  42. logging.exception("Delete annotation index failed when annotation deleted.")
  43. redis_client.setex(disable_app_annotation_job_key, 600, "completed")
  44. # delete annotation setting
  45. db.session.delete(app_annotation_setting)
  46. db.session.commit()
  47. end_at = time.perf_counter()
  48. logging.info(
  49. click.style("App annotations index deleted : {} latency: {}".format(app_id, end_at - start_at), fg="green")
  50. )
  51. except Exception as e:
  52. logging.exception("Annotation batch deleted index failed:{}".format(str(e)))
  53. redis_client.setex(disable_app_annotation_job_key, 600, "error")
  54. disable_app_annotation_error_key = "disable_app_annotation_error_{}".format(str(job_id))
  55. redis_client.setex(disable_app_annotation_error_key, 600, str(e))
  56. finally:
  57. redis_client.delete(disable_app_annotation_key)