You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

enable_annotation_reply_task.py 5.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import logging
  2. import time
  3. import click
  4. from celery import shared_task # type: ignore
  5. from core.rag.datasource.vdb.vector_factory import Vector
  6. from core.rag.models.document import Document
  7. from extensions.ext_database import db
  8. from extensions.ext_redis import redis_client
  9. from libs.datetime_utils import naive_utc_now
  10. from models.dataset import Dataset
  11. from models.model import App, AppAnnotationSetting, MessageAnnotation
  12. from services.dataset_service import DatasetCollectionBindingService
  13. @shared_task(queue="dataset")
  14. def enable_annotation_reply_task(
  15. job_id: str,
  16. app_id: str,
  17. user_id: str,
  18. tenant_id: str,
  19. score_threshold: float,
  20. embedding_provider_name: str,
  21. embedding_model_name: str,
  22. ):
  23. """
  24. Async enable annotation reply task
  25. """
  26. logging.info(click.style(f"Start add app annotation to index: {app_id}", fg="green"))
  27. start_at = time.perf_counter()
  28. # get app info
  29. app = db.session.query(App).where(App.id == app_id, App.tenant_id == tenant_id, App.status == "normal").first()
  30. if not app:
  31. logging.info(click.style(f"App not found: {app_id}", fg="red"))
  32. db.session.close()
  33. return
  34. annotations = db.session.query(MessageAnnotation).where(MessageAnnotation.app_id == app_id).all()
  35. enable_app_annotation_key = f"enable_app_annotation_{str(app_id)}"
  36. enable_app_annotation_job_key = f"enable_app_annotation_job_{str(job_id)}"
  37. try:
  38. documents = []
  39. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  40. embedding_provider_name, embedding_model_name, "annotation"
  41. )
  42. annotation_setting = db.session.query(AppAnnotationSetting).where(AppAnnotationSetting.app_id == app_id).first()
  43. if annotation_setting:
  44. if dataset_collection_binding.id != annotation_setting.collection_binding_id:
  45. old_dataset_collection_binding = (
  46. DatasetCollectionBindingService.get_dataset_collection_binding_by_id_and_type(
  47. annotation_setting.collection_binding_id, "annotation"
  48. )
  49. )
  50. if old_dataset_collection_binding and annotations:
  51. old_dataset = Dataset(
  52. id=app_id,
  53. tenant_id=tenant_id,
  54. indexing_technique="high_quality",
  55. embedding_model_provider=old_dataset_collection_binding.provider_name,
  56. embedding_model=old_dataset_collection_binding.model_name,
  57. collection_binding_id=old_dataset_collection_binding.id,
  58. )
  59. old_vector = Vector(old_dataset, attributes=["doc_id", "annotation_id", "app_id"])
  60. try:
  61. old_vector.delete()
  62. except Exception as e:
  63. logging.info(click.style(f"Delete annotation index error: {str(e)}", fg="red"))
  64. annotation_setting.score_threshold = score_threshold
  65. annotation_setting.collection_binding_id = dataset_collection_binding.id
  66. annotation_setting.updated_user_id = user_id
  67. annotation_setting.updated_at = naive_utc_now()
  68. db.session.add(annotation_setting)
  69. else:
  70. new_app_annotation_setting = AppAnnotationSetting(
  71. app_id=app_id,
  72. score_threshold=score_threshold,
  73. collection_binding_id=dataset_collection_binding.id,
  74. created_user_id=user_id,
  75. updated_user_id=user_id,
  76. )
  77. db.session.add(new_app_annotation_setting)
  78. dataset = Dataset(
  79. id=app_id,
  80. tenant_id=tenant_id,
  81. indexing_technique="high_quality",
  82. embedding_model_provider=embedding_provider_name,
  83. embedding_model=embedding_model_name,
  84. collection_binding_id=dataset_collection_binding.id,
  85. )
  86. if annotations:
  87. for annotation in annotations:
  88. document = Document(
  89. page_content=annotation.question,
  90. metadata={"annotation_id": annotation.id, "app_id": app_id, "doc_id": annotation.id},
  91. )
  92. documents.append(document)
  93. vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"])
  94. try:
  95. vector.delete_by_metadata_field("app_id", app_id)
  96. except Exception as e:
  97. logging.info(click.style(f"Delete annotation index error: {str(e)}", fg="red"))
  98. vector.create(documents)
  99. db.session.commit()
  100. redis_client.setex(enable_app_annotation_job_key, 600, "completed")
  101. end_at = time.perf_counter()
  102. logging.info(click.style(f"App annotations added to index: {app_id} latency: {end_at - start_at}", fg="green"))
  103. except Exception as e:
  104. logging.exception("Annotation batch created index failed")
  105. redis_client.setex(enable_app_annotation_job_key, 600, "error")
  106. enable_app_annotation_error_key = f"enable_app_annotation_error_{str(job_id)}"
  107. redis_client.setex(enable_app_annotation_error_key, 600, str(e))
  108. db.session.rollback()
  109. finally:
  110. redis_client.delete(enable_app_annotation_key)
  111. db.session.close()