您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

enable_annotation_reply_task.py 5.3KB

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