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.

dataset_retrieval.py 52KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. import json
  2. import math
  3. import re
  4. import threading
  5. from collections import Counter, defaultdict
  6. from collections.abc import Generator, Mapping
  7. from typing import Any, Optional, Union, cast
  8. from flask import Flask, current_app
  9. from sqlalchemy import Integer, and_, or_, text
  10. from sqlalchemy import cast as sqlalchemy_cast
  11. from core.app.app_config.entities import (
  12. DatasetEntity,
  13. DatasetRetrieveConfigEntity,
  14. MetadataFilteringCondition,
  15. ModelConfig,
  16. )
  17. from core.app.entities.app_invoke_entities import InvokeFrom, ModelConfigWithCredentialsEntity
  18. from core.callback_handler.index_tool_callback_handler import DatasetIndexToolCallbackHandler
  19. from core.entities.agent_entities import PlanningStrategy
  20. from core.entities.model_entities import ModelStatus
  21. from core.memory.token_buffer_memory import TokenBufferMemory
  22. from core.model_manager import ModelInstance, ModelManager
  23. from core.model_runtime.entities.llm_entities import LLMResult, LLMUsage
  24. from core.model_runtime.entities.message_entities import PromptMessage, PromptMessageRole, PromptMessageTool
  25. from core.model_runtime.entities.model_entities import ModelFeature, ModelType
  26. from core.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
  27. from core.ops.entities.trace_entity import TraceTaskName
  28. from core.ops.ops_trace_manager import TraceQueueManager, TraceTask
  29. from core.ops.utils import measure_time
  30. from core.prompt.advanced_prompt_transform import AdvancedPromptTransform
  31. from core.prompt.entities.advanced_prompt_entities import ChatModelMessage, CompletionModelPromptTemplate
  32. from core.prompt.simple_prompt_transform import ModelMode
  33. from core.rag.data_post_processor.data_post_processor import DataPostProcessor
  34. from core.rag.datasource.keyword.jieba.jieba_keyword_table_handler import JiebaKeywordTableHandler
  35. from core.rag.datasource.retrieval_service import RetrievalService
  36. from core.rag.entities.context_entities import DocumentContext
  37. from core.rag.entities.metadata_entities import Condition, MetadataCondition
  38. from core.rag.index_processor.constant.index_type import IndexType
  39. from core.rag.models.document import Document
  40. from core.rag.rerank.rerank_type import RerankMode
  41. from core.rag.retrieval.retrieval_methods import RetrievalMethod
  42. from core.rag.retrieval.router.multi_dataset_function_call_router import FunctionCallMultiDatasetRouter
  43. from core.rag.retrieval.router.multi_dataset_react_route import ReactMultiDatasetRouter
  44. from core.rag.retrieval.template_prompts import (
  45. METADATA_FILTER_ASSISTANT_PROMPT_1,
  46. METADATA_FILTER_ASSISTANT_PROMPT_2,
  47. METADATA_FILTER_COMPLETION_PROMPT,
  48. METADATA_FILTER_SYSTEM_PROMPT,
  49. METADATA_FILTER_USER_PROMPT_1,
  50. METADATA_FILTER_USER_PROMPT_2,
  51. METADATA_FILTER_USER_PROMPT_3,
  52. )
  53. from core.tools.entities.common_entities import I18nObject
  54. from core.tools.utils.dataset_retriever.dataset_retriever_base_tool import DatasetRetrieverBaseTool
  55. from extensions.ext_database import db
  56. from libs.json_in_md_parser import parse_and_check_json_markdown
  57. from models.dataset import ChildChunk, Dataset, DatasetMetadata, DatasetQuery, DocumentSegment
  58. from models.dataset import Document as DatasetDocument
  59. from services.external_knowledge_service import ExternalDatasetService
  60. default_retrieval_model: dict[str, Any] = {
  61. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  62. "reranking_enable": False,
  63. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  64. "top_k": 2,
  65. "score_threshold_enabled": False,
  66. }
  67. class DatasetRetrieval:
  68. def __init__(self, application_generate_entity=None):
  69. self.application_generate_entity = application_generate_entity
  70. def retrieve(
  71. self,
  72. app_id: str,
  73. user_id: str,
  74. tenant_id: str,
  75. model_config: ModelConfigWithCredentialsEntity,
  76. config: DatasetEntity,
  77. query: str,
  78. invoke_from: InvokeFrom,
  79. show_retrieve_source: bool,
  80. hit_callback: DatasetIndexToolCallbackHandler,
  81. message_id: str,
  82. memory: Optional[TokenBufferMemory] = None,
  83. inputs: Optional[Mapping[str, Any]] = None,
  84. ) -> Optional[str]:
  85. """
  86. Retrieve dataset.
  87. :param app_id: app_id
  88. :param user_id: user_id
  89. :param tenant_id: tenant id
  90. :param model_config: model config
  91. :param config: dataset config
  92. :param query: query
  93. :param invoke_from: invoke from
  94. :param show_retrieve_source: show retrieve source
  95. :param hit_callback: hit callback
  96. :param message_id: message id
  97. :param memory: memory
  98. :param inputs: inputs
  99. :return:
  100. """
  101. dataset_ids = config.dataset_ids
  102. if len(dataset_ids) == 0:
  103. return None
  104. retrieve_config = config.retrieve_config
  105. # check model is support tool calling
  106. model_type_instance = model_config.provider_model_bundle.model_type_instance
  107. model_type_instance = cast(LargeLanguageModel, model_type_instance)
  108. model_manager = ModelManager()
  109. model_instance = model_manager.get_model_instance(
  110. tenant_id=tenant_id, model_type=ModelType.LLM, provider=model_config.provider, model=model_config.model
  111. )
  112. # get model schema
  113. model_schema = model_type_instance.get_model_schema(
  114. model=model_config.model, credentials=model_config.credentials
  115. )
  116. if not model_schema:
  117. return None
  118. planning_strategy = PlanningStrategy.REACT_ROUTER
  119. features = model_schema.features
  120. if features:
  121. if ModelFeature.TOOL_CALL in features or ModelFeature.MULTI_TOOL_CALL in features:
  122. planning_strategy = PlanningStrategy.ROUTER
  123. available_datasets = []
  124. for dataset_id in dataset_ids:
  125. # get dataset from dataset id
  126. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  127. # pass if dataset is not available
  128. if not dataset:
  129. continue
  130. # pass if dataset is not available
  131. if dataset and dataset.available_document_count == 0 and dataset.provider != "external":
  132. continue
  133. available_datasets.append(dataset)
  134. if inputs:
  135. inputs = {key: str(value) for key, value in inputs.items()}
  136. else:
  137. inputs = {}
  138. available_datasets_ids = [dataset.id for dataset in available_datasets]
  139. metadata_filter_document_ids, metadata_condition = self._get_metadata_filter_condition(
  140. available_datasets_ids,
  141. query,
  142. tenant_id,
  143. user_id,
  144. retrieve_config.metadata_filtering_mode, # type: ignore
  145. retrieve_config.metadata_model_config, # type: ignore
  146. retrieve_config.metadata_filtering_conditions,
  147. inputs,
  148. )
  149. all_documents = []
  150. user_from = "account" if invoke_from in {InvokeFrom.EXPLORE, InvokeFrom.DEBUGGER} else "end_user"
  151. if retrieve_config.retrieve_strategy == DatasetRetrieveConfigEntity.RetrieveStrategy.SINGLE:
  152. all_documents = self.single_retrieve(
  153. app_id,
  154. tenant_id,
  155. user_id,
  156. user_from,
  157. available_datasets,
  158. query,
  159. model_instance,
  160. model_config,
  161. planning_strategy,
  162. message_id,
  163. metadata_filter_document_ids,
  164. metadata_condition,
  165. )
  166. elif retrieve_config.retrieve_strategy == DatasetRetrieveConfigEntity.RetrieveStrategy.MULTIPLE:
  167. all_documents = self.multiple_retrieve(
  168. app_id,
  169. tenant_id,
  170. user_id,
  171. user_from,
  172. available_datasets,
  173. query,
  174. retrieve_config.top_k or 0,
  175. retrieve_config.score_threshold or 0,
  176. retrieve_config.rerank_mode or "reranking_model",
  177. retrieve_config.reranking_model,
  178. retrieve_config.weights,
  179. retrieve_config.reranking_enabled or True,
  180. message_id,
  181. metadata_filter_document_ids,
  182. metadata_condition,
  183. )
  184. dify_documents = [item for item in all_documents if item.provider == "dify"]
  185. external_documents = [item for item in all_documents if item.provider == "external"]
  186. document_context_list = []
  187. retrieval_resource_list = []
  188. # deal with external documents
  189. for item in external_documents:
  190. document_context_list.append(DocumentContext(content=item.page_content, score=item.metadata.get("score")))
  191. source = {
  192. "dataset_id": item.metadata.get("dataset_id"),
  193. "dataset_name": item.metadata.get("dataset_name"),
  194. "document_name": item.metadata.get("title"),
  195. "data_source_type": "external",
  196. "retriever_from": invoke_from.to_source(),
  197. "score": item.metadata.get("score"),
  198. "content": item.page_content,
  199. }
  200. retrieval_resource_list.append(source)
  201. # deal with dify documents
  202. if dify_documents:
  203. records = RetrievalService.format_retrieval_documents(dify_documents)
  204. if records:
  205. for record in records:
  206. segment = record.segment
  207. if segment.answer:
  208. document_context_list.append(
  209. DocumentContext(
  210. content=f"question:{segment.get_sign_content()} answer:{segment.answer}",
  211. score=record.score,
  212. )
  213. )
  214. else:
  215. document_context_list.append(
  216. DocumentContext(
  217. content=segment.get_sign_content(),
  218. score=record.score,
  219. )
  220. )
  221. if show_retrieve_source:
  222. for record in records:
  223. segment = record.segment
  224. dataset = Dataset.query.filter_by(id=segment.dataset_id).first()
  225. document = DatasetDocument.query.filter(
  226. DatasetDocument.id == segment.document_id,
  227. DatasetDocument.enabled == True,
  228. DatasetDocument.archived == False,
  229. ).first()
  230. if dataset and document:
  231. source = {
  232. "dataset_id": dataset.id,
  233. "dataset_name": dataset.name,
  234. "document_id": document.id,
  235. "document_name": document.name,
  236. "data_source_type": document.data_source_type,
  237. "segment_id": segment.id,
  238. "retriever_from": invoke_from.to_source(),
  239. "score": record.score or 0.0,
  240. "doc_metadata": document.doc_metadata,
  241. }
  242. if invoke_from.to_source() == "dev":
  243. source["hit_count"] = segment.hit_count
  244. source["word_count"] = segment.word_count
  245. source["segment_position"] = segment.position
  246. source["index_node_hash"] = segment.index_node_hash
  247. if segment.answer:
  248. source["content"] = f"question:{segment.content} \nanswer:{segment.answer}"
  249. else:
  250. source["content"] = segment.content
  251. retrieval_resource_list.append(source)
  252. if hit_callback and retrieval_resource_list:
  253. retrieval_resource_list = sorted(retrieval_resource_list, key=lambda x: x.get("score") or 0.0, reverse=True)
  254. for position, item in enumerate(retrieval_resource_list, start=1):
  255. item["position"] = position
  256. hit_callback.return_retriever_resource_info(retrieval_resource_list)
  257. if document_context_list:
  258. document_context_list = sorted(document_context_list, key=lambda x: x.score or 0.0, reverse=True)
  259. return str("\n".join([document_context.content for document_context in document_context_list]))
  260. return ""
  261. def single_retrieve(
  262. self,
  263. app_id: str,
  264. tenant_id: str,
  265. user_id: str,
  266. user_from: str,
  267. available_datasets: list,
  268. query: str,
  269. model_instance: ModelInstance,
  270. model_config: ModelConfigWithCredentialsEntity,
  271. planning_strategy: PlanningStrategy,
  272. message_id: Optional[str] = None,
  273. metadata_filter_document_ids: Optional[dict[str, list[str]]] = None,
  274. metadata_condition: Optional[MetadataCondition] = None,
  275. ):
  276. tools = []
  277. for dataset in available_datasets:
  278. description = dataset.description
  279. if not description:
  280. description = I18nObject(
  281. en_US="useful for when you want to answer queries about the " + dataset.name,
  282. zh_Hans="用于回答关于 " + dataset.name + " 的查询",
  283. )
  284. description = description.replace("\n", "").replace("\r", "")
  285. message_tool = PromptMessageTool(
  286. name=dataset.id,
  287. description=description,
  288. parameters={
  289. "type": "object",
  290. "properties": {},
  291. "required": [],
  292. },
  293. )
  294. tools.append(message_tool)
  295. dataset_id = None
  296. if planning_strategy == PlanningStrategy.REACT_ROUTER:
  297. react_multi_dataset_router = ReactMultiDatasetRouter()
  298. dataset_id = react_multi_dataset_router.invoke(
  299. query, tools, model_config, model_instance, user_id, tenant_id
  300. )
  301. elif planning_strategy == PlanningStrategy.ROUTER:
  302. function_call_router = FunctionCallMultiDatasetRouter()
  303. dataset_id = function_call_router.invoke(query, tools, model_config, model_instance)
  304. if dataset_id:
  305. # get retrieval model config
  306. dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
  307. if dataset:
  308. results = []
  309. if dataset.provider == "external":
  310. external_documents = ExternalDatasetService.fetch_external_knowledge_retrieval(
  311. tenant_id=dataset.tenant_id,
  312. dataset_id=dataset_id,
  313. query=query,
  314. external_retrieval_parameters=dataset.retrieval_model,
  315. metadata_condition=metadata_condition,
  316. )
  317. for external_document in external_documents:
  318. document = Document(
  319. page_content=external_document.get("content"),
  320. metadata=external_document.get("metadata"),
  321. provider="external",
  322. )
  323. if document.metadata is not None:
  324. document.metadata["score"] = external_document.get("score")
  325. document.metadata["title"] = external_document.get("title")
  326. document.metadata["dataset_id"] = dataset_id
  327. document.metadata["dataset_name"] = dataset.name
  328. results.append(document)
  329. else:
  330. if metadata_condition and not metadata_filter_document_ids:
  331. return []
  332. document_ids_filter = None
  333. if metadata_filter_document_ids:
  334. document_ids = metadata_filter_document_ids.get(dataset.id, [])
  335. if document_ids:
  336. document_ids_filter = document_ids
  337. else:
  338. return []
  339. retrieval_model_config = dataset.retrieval_model or default_retrieval_model
  340. # get top k
  341. top_k = retrieval_model_config["top_k"]
  342. # get retrieval method
  343. if dataset.indexing_technique == "economy":
  344. retrieval_method = "keyword_search"
  345. else:
  346. retrieval_method = retrieval_model_config["search_method"]
  347. # get reranking model
  348. reranking_model = (
  349. retrieval_model_config["reranking_model"]
  350. if retrieval_model_config["reranking_enable"]
  351. else None
  352. )
  353. # get score threshold
  354. score_threshold = 0.0
  355. score_threshold_enabled = retrieval_model_config.get("score_threshold_enabled")
  356. if score_threshold_enabled:
  357. score_threshold = retrieval_model_config.get("score_threshold", 0.0)
  358. with measure_time() as timer:
  359. results = RetrievalService.retrieve(
  360. retrieval_method=retrieval_method,
  361. dataset_id=dataset.id,
  362. query=query,
  363. top_k=top_k,
  364. score_threshold=score_threshold,
  365. reranking_model=reranking_model,
  366. reranking_mode=retrieval_model_config.get("reranking_mode", "reranking_model"),
  367. weights=retrieval_model_config.get("weights", None),
  368. document_ids_filter=document_ids_filter,
  369. )
  370. self._on_query(query, [dataset_id], app_id, user_from, user_id)
  371. if results:
  372. self._on_retrieval_end(results, message_id, timer)
  373. return results
  374. return []
  375. def multiple_retrieve(
  376. self,
  377. app_id: str,
  378. tenant_id: str,
  379. user_id: str,
  380. user_from: str,
  381. available_datasets: list,
  382. query: str,
  383. top_k: int,
  384. score_threshold: float,
  385. reranking_mode: str,
  386. reranking_model: Optional[dict] = None,
  387. weights: Optional[dict[str, Any]] = None,
  388. reranking_enable: bool = True,
  389. message_id: Optional[str] = None,
  390. metadata_filter_document_ids: Optional[dict[str, list[str]]] = None,
  391. metadata_condition: Optional[MetadataCondition] = None,
  392. ):
  393. if not available_datasets:
  394. return []
  395. threads = []
  396. all_documents: list[Document] = []
  397. dataset_ids = [dataset.id for dataset in available_datasets]
  398. index_type_check = all(
  399. item.indexing_technique == available_datasets[0].indexing_technique for item in available_datasets
  400. )
  401. if not index_type_check and (not reranking_enable or reranking_mode != RerankMode.RERANKING_MODEL):
  402. raise ValueError(
  403. "The configured knowledge base list have different indexing technique, please set reranking model."
  404. )
  405. index_type = available_datasets[0].indexing_technique
  406. if index_type == "high_quality":
  407. embedding_model_check = all(
  408. item.embedding_model == available_datasets[0].embedding_model for item in available_datasets
  409. )
  410. embedding_model_provider_check = all(
  411. item.embedding_model_provider == available_datasets[0].embedding_model_provider
  412. for item in available_datasets
  413. )
  414. if (
  415. reranking_enable
  416. and reranking_mode == "weighted_score"
  417. and (not embedding_model_check or not embedding_model_provider_check)
  418. ):
  419. raise ValueError(
  420. "The configured knowledge base list have different embedding model, please set reranking model."
  421. )
  422. if reranking_enable and reranking_mode == RerankMode.WEIGHTED_SCORE:
  423. if weights is not None:
  424. weights["vector_setting"]["embedding_provider_name"] = available_datasets[
  425. 0
  426. ].embedding_model_provider
  427. weights["vector_setting"]["embedding_model_name"] = available_datasets[0].embedding_model
  428. for dataset in available_datasets:
  429. index_type = dataset.indexing_technique
  430. document_ids_filter = None
  431. if dataset.provider != "external":
  432. if metadata_condition and not metadata_filter_document_ids:
  433. continue
  434. if metadata_filter_document_ids:
  435. document_ids = metadata_filter_document_ids.get(dataset.id, [])
  436. if document_ids:
  437. document_ids_filter = document_ids
  438. else:
  439. continue
  440. retrieval_thread = threading.Thread(
  441. target=self._retriever,
  442. kwargs={
  443. "flask_app": current_app._get_current_object(), # type: ignore
  444. "dataset_id": dataset.id,
  445. "query": query,
  446. "top_k": top_k,
  447. "all_documents": all_documents,
  448. "document_ids_filter": document_ids_filter,
  449. "metadata_condition": metadata_condition,
  450. },
  451. )
  452. threads.append(retrieval_thread)
  453. retrieval_thread.start()
  454. for thread in threads:
  455. thread.join()
  456. with measure_time() as timer:
  457. if reranking_enable:
  458. # do rerank for searched documents
  459. data_post_processor = DataPostProcessor(tenant_id, reranking_mode, reranking_model, weights, False)
  460. all_documents = data_post_processor.invoke(
  461. query=query, documents=all_documents, score_threshold=score_threshold, top_n=top_k
  462. )
  463. else:
  464. if index_type == "economy":
  465. all_documents = self.calculate_keyword_score(query, all_documents, top_k)
  466. elif index_type == "high_quality":
  467. all_documents = self.calculate_vector_score(all_documents, top_k, score_threshold)
  468. self._on_query(query, dataset_ids, app_id, user_from, user_id)
  469. if all_documents:
  470. self._on_retrieval_end(all_documents, message_id, timer)
  471. return all_documents
  472. def _on_retrieval_end(
  473. self, documents: list[Document], message_id: Optional[str] = None, timer: Optional[dict] = None
  474. ) -> None:
  475. """Handle retrieval end."""
  476. dify_documents = [document for document in documents if document.provider == "dify"]
  477. for document in dify_documents:
  478. if document.metadata is not None:
  479. dataset_document = DatasetDocument.query.filter(
  480. DatasetDocument.id == document.metadata["document_id"]
  481. ).first()
  482. if dataset_document:
  483. if dataset_document.doc_form == IndexType.PARENT_CHILD_INDEX:
  484. child_chunk = ChildChunk.query.filter(
  485. ChildChunk.index_node_id == document.metadata["doc_id"],
  486. ChildChunk.dataset_id == dataset_document.dataset_id,
  487. ChildChunk.document_id == dataset_document.id,
  488. ).first()
  489. if child_chunk:
  490. segment = DocumentSegment.query.filter(DocumentSegment.id == child_chunk.segment_id).update(
  491. {DocumentSegment.hit_count: DocumentSegment.hit_count + 1}, synchronize_session=False
  492. )
  493. db.session.commit()
  494. else:
  495. query = db.session.query(DocumentSegment).filter(
  496. DocumentSegment.index_node_id == document.metadata["doc_id"]
  497. )
  498. # if 'dataset_id' in document.metadata:
  499. if "dataset_id" in document.metadata:
  500. query = query.filter(DocumentSegment.dataset_id == document.metadata["dataset_id"])
  501. # add hit count to document segment
  502. query.update(
  503. {DocumentSegment.hit_count: DocumentSegment.hit_count + 1}, synchronize_session=False
  504. )
  505. db.session.commit()
  506. # get tracing instance
  507. trace_manager: TraceQueueManager | None = (
  508. self.application_generate_entity.trace_manager if self.application_generate_entity else None
  509. )
  510. if trace_manager:
  511. trace_manager.add_trace_task(
  512. TraceTask(
  513. TraceTaskName.DATASET_RETRIEVAL_TRACE, message_id=message_id, documents=documents, timer=timer
  514. )
  515. )
  516. def _on_query(self, query: str, dataset_ids: list[str], app_id: str, user_from: str, user_id: str) -> None:
  517. """
  518. Handle query.
  519. """
  520. if not query:
  521. return
  522. dataset_queries = []
  523. for dataset_id in dataset_ids:
  524. dataset_query = DatasetQuery(
  525. dataset_id=dataset_id,
  526. content=query,
  527. source="app",
  528. source_app_id=app_id,
  529. created_by_role=user_from,
  530. created_by=user_id,
  531. )
  532. dataset_queries.append(dataset_query)
  533. if dataset_queries:
  534. db.session.add_all(dataset_queries)
  535. db.session.commit()
  536. def _retriever(
  537. self,
  538. flask_app: Flask,
  539. dataset_id: str,
  540. query: str,
  541. top_k: int,
  542. all_documents: list,
  543. document_ids_filter: Optional[list[str]] = None,
  544. metadata_condition: Optional[MetadataCondition] = None,
  545. ):
  546. with flask_app.app_context():
  547. dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
  548. if not dataset:
  549. return []
  550. if dataset.provider == "external":
  551. external_documents = ExternalDatasetService.fetch_external_knowledge_retrieval(
  552. tenant_id=dataset.tenant_id,
  553. dataset_id=dataset_id,
  554. query=query,
  555. external_retrieval_parameters=dataset.retrieval_model,
  556. metadata_condition=metadata_condition,
  557. )
  558. for external_document in external_documents:
  559. document = Document(
  560. page_content=external_document.get("content"),
  561. metadata=external_document.get("metadata"),
  562. provider="external",
  563. )
  564. if document.metadata is not None:
  565. document.metadata["score"] = external_document.get("score")
  566. document.metadata["title"] = external_document.get("title")
  567. document.metadata["dataset_id"] = dataset_id
  568. document.metadata["dataset_name"] = dataset.name
  569. all_documents.append(document)
  570. else:
  571. # get retrieval model , if the model is not setting , using default
  572. retrieval_model = dataset.retrieval_model or default_retrieval_model
  573. if dataset.indexing_technique == "economy":
  574. # use keyword table query
  575. documents = RetrievalService.retrieve(
  576. retrieval_method="keyword_search",
  577. dataset_id=dataset.id,
  578. query=query,
  579. top_k=top_k,
  580. document_ids_filter=document_ids_filter,
  581. )
  582. if documents:
  583. all_documents.extend(documents)
  584. else:
  585. if top_k > 0:
  586. # retrieval source
  587. documents = RetrievalService.retrieve(
  588. retrieval_method=retrieval_model["search_method"],
  589. dataset_id=dataset.id,
  590. query=query,
  591. top_k=retrieval_model.get("top_k") or 2,
  592. score_threshold=retrieval_model.get("score_threshold", 0.0)
  593. if retrieval_model["score_threshold_enabled"]
  594. else 0.0,
  595. reranking_model=retrieval_model.get("reranking_model", None)
  596. if retrieval_model["reranking_enable"]
  597. else None,
  598. reranking_mode=retrieval_model.get("reranking_mode") or "reranking_model",
  599. weights=retrieval_model.get("weights", None),
  600. document_ids_filter=document_ids_filter,
  601. )
  602. all_documents.extend(documents)
  603. def to_dataset_retriever_tool(
  604. self,
  605. tenant_id: str,
  606. dataset_ids: list[str],
  607. retrieve_config: DatasetRetrieveConfigEntity,
  608. return_resource: bool,
  609. invoke_from: InvokeFrom,
  610. hit_callback: DatasetIndexToolCallbackHandler,
  611. ) -> Optional[list[DatasetRetrieverBaseTool]]:
  612. """
  613. A dataset tool is a tool that can be used to retrieve information from a dataset
  614. :param tenant_id: tenant id
  615. :param dataset_ids: dataset ids
  616. :param retrieve_config: retrieve config
  617. :param return_resource: return resource
  618. :param invoke_from: invoke from
  619. :param hit_callback: hit callback
  620. """
  621. tools = []
  622. available_datasets = []
  623. for dataset_id in dataset_ids:
  624. # get dataset from dataset id
  625. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  626. # pass if dataset is not available
  627. if not dataset:
  628. continue
  629. # pass if dataset is not available
  630. if dataset and dataset.provider != "external" and dataset.available_document_count == 0:
  631. continue
  632. available_datasets.append(dataset)
  633. if retrieve_config.retrieve_strategy == DatasetRetrieveConfigEntity.RetrieveStrategy.SINGLE:
  634. # get retrieval model config
  635. default_retrieval_model = {
  636. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  637. "reranking_enable": False,
  638. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  639. "top_k": 2,
  640. "score_threshold_enabled": False,
  641. }
  642. for dataset in available_datasets:
  643. retrieval_model_config = dataset.retrieval_model or default_retrieval_model
  644. # get top k
  645. top_k = retrieval_model_config["top_k"]
  646. # get score threshold
  647. score_threshold = None
  648. score_threshold_enabled = retrieval_model_config.get("score_threshold_enabled")
  649. if score_threshold_enabled:
  650. score_threshold = retrieval_model_config.get("score_threshold")
  651. from core.tools.utils.dataset_retriever.dataset_retriever_tool import DatasetRetrieverTool
  652. tool = DatasetRetrieverTool.from_dataset(
  653. dataset=dataset,
  654. top_k=top_k,
  655. score_threshold=score_threshold,
  656. hit_callbacks=[hit_callback],
  657. return_resource=return_resource,
  658. retriever_from=invoke_from.to_source(),
  659. )
  660. tools.append(tool)
  661. elif retrieve_config.retrieve_strategy == DatasetRetrieveConfigEntity.RetrieveStrategy.MULTIPLE:
  662. from core.tools.utils.dataset_retriever.dataset_multi_retriever_tool import DatasetMultiRetrieverTool
  663. if retrieve_config.reranking_model is None:
  664. raise ValueError("Reranking model is required for multiple retrieval")
  665. tool = DatasetMultiRetrieverTool.from_dataset(
  666. dataset_ids=[dataset.id for dataset in available_datasets],
  667. tenant_id=tenant_id,
  668. top_k=retrieve_config.top_k or 2,
  669. score_threshold=retrieve_config.score_threshold,
  670. hit_callbacks=[hit_callback],
  671. return_resource=return_resource,
  672. retriever_from=invoke_from.to_source(),
  673. reranking_provider_name=retrieve_config.reranking_model.get("reranking_provider_name"),
  674. reranking_model_name=retrieve_config.reranking_model.get("reranking_model_name"),
  675. )
  676. tools.append(tool)
  677. return tools
  678. def calculate_keyword_score(self, query: str, documents: list[Document], top_k: int) -> list[Document]:
  679. """
  680. Calculate keywords scores
  681. :param query: search query
  682. :param documents: documents for reranking
  683. :param top_k: top k
  684. :return:
  685. """
  686. keyword_table_handler = JiebaKeywordTableHandler()
  687. query_keywords = keyword_table_handler.extract_keywords(query, None)
  688. documents_keywords = []
  689. for document in documents:
  690. if document.metadata is not None:
  691. # get the document keywords
  692. document_keywords = keyword_table_handler.extract_keywords(document.page_content, None)
  693. document.metadata["keywords"] = document_keywords
  694. documents_keywords.append(document_keywords)
  695. # Counter query keywords(TF)
  696. query_keyword_counts = Counter(query_keywords)
  697. # total documents
  698. total_documents = len(documents)
  699. # calculate all documents' keywords IDF
  700. all_keywords = set()
  701. for document_keywords in documents_keywords:
  702. all_keywords.update(document_keywords)
  703. keyword_idf = {}
  704. for keyword in all_keywords:
  705. # calculate include query keywords' documents
  706. doc_count_containing_keyword = sum(1 for doc_keywords in documents_keywords if keyword in doc_keywords)
  707. # IDF
  708. keyword_idf[keyword] = math.log((1 + total_documents) / (1 + doc_count_containing_keyword)) + 1
  709. query_tfidf = {}
  710. for keyword, count in query_keyword_counts.items():
  711. tf = count
  712. idf = keyword_idf.get(keyword, 0)
  713. query_tfidf[keyword] = tf * idf
  714. # calculate all documents' TF-IDF
  715. documents_tfidf = []
  716. for document_keywords in documents_keywords:
  717. document_keyword_counts = Counter(document_keywords)
  718. document_tfidf = {}
  719. for keyword, count in document_keyword_counts.items():
  720. tf = count
  721. idf = keyword_idf.get(keyword, 0)
  722. document_tfidf[keyword] = tf * idf
  723. documents_tfidf.append(document_tfidf)
  724. def cosine_similarity(vec1, vec2):
  725. intersection = set(vec1.keys()) & set(vec2.keys())
  726. numerator = sum(vec1[x] * vec2[x] for x in intersection)
  727. sum1 = sum(vec1[x] ** 2 for x in vec1)
  728. sum2 = sum(vec2[x] ** 2 for x in vec2)
  729. denominator = math.sqrt(sum1) * math.sqrt(sum2)
  730. if not denominator:
  731. return 0.0
  732. else:
  733. return float(numerator) / denominator
  734. similarities = []
  735. for document_tfidf in documents_tfidf:
  736. similarity = cosine_similarity(query_tfidf, document_tfidf)
  737. similarities.append(similarity)
  738. for document, score in zip(documents, similarities):
  739. # format document
  740. if document.metadata is not None:
  741. document.metadata["score"] = score
  742. documents = sorted(documents, key=lambda x: x.metadata.get("score", 0) if x.metadata else 0, reverse=True)
  743. return documents[:top_k] if top_k else documents
  744. def calculate_vector_score(
  745. self, all_documents: list[Document], top_k: int, score_threshold: float
  746. ) -> list[Document]:
  747. filter_documents = []
  748. for document in all_documents:
  749. if score_threshold is None or (document.metadata and document.metadata.get("score", 0) >= score_threshold):
  750. filter_documents.append(document)
  751. if not filter_documents:
  752. return []
  753. filter_documents = sorted(
  754. filter_documents, key=lambda x: x.metadata.get("score", 0) if x.metadata else 0, reverse=True
  755. )
  756. return filter_documents[:top_k] if top_k else filter_documents
  757. def _get_metadata_filter_condition(
  758. self,
  759. dataset_ids: list,
  760. query: str,
  761. tenant_id: str,
  762. user_id: str,
  763. metadata_filtering_mode: str,
  764. metadata_model_config: ModelConfig,
  765. metadata_filtering_conditions: Optional[MetadataFilteringCondition],
  766. inputs: dict,
  767. ) -> tuple[Optional[dict[str, list[str]]], Optional[MetadataCondition]]:
  768. document_query = db.session.query(DatasetDocument).filter(
  769. DatasetDocument.dataset_id.in_(dataset_ids),
  770. DatasetDocument.indexing_status == "completed",
  771. DatasetDocument.enabled == True,
  772. DatasetDocument.archived == False,
  773. )
  774. filters = [] # type: ignore
  775. metadata_condition = None
  776. if metadata_filtering_mode == "disabled":
  777. return None, None
  778. elif metadata_filtering_mode == "automatic":
  779. automatic_metadata_filters = self._automatic_metadata_filter_func(
  780. dataset_ids, query, tenant_id, user_id, metadata_model_config
  781. )
  782. if automatic_metadata_filters:
  783. conditions = []
  784. for sequence, filter in enumerate(automatic_metadata_filters):
  785. self._process_metadata_filter_func(
  786. sequence,
  787. filter.get("condition"), # type: ignore
  788. filter.get("metadata_name"), # type: ignore
  789. filter.get("value"),
  790. filters, # type: ignore
  791. )
  792. conditions.append(
  793. Condition(
  794. name=filter.get("metadata_name"), # type: ignore
  795. comparison_operator=filter.get("condition"), # type: ignore
  796. value=filter.get("value"),
  797. )
  798. )
  799. metadata_condition = MetadataCondition(
  800. logical_operator=metadata_filtering_conditions.logical_operator, # type: ignore
  801. conditions=conditions,
  802. )
  803. elif metadata_filtering_mode == "manual":
  804. if metadata_filtering_conditions:
  805. metadata_condition = MetadataCondition(**metadata_filtering_conditions.model_dump())
  806. for sequence, condition in enumerate(metadata_filtering_conditions.conditions): # type: ignore
  807. metadata_name = condition.name
  808. expected_value = condition.value
  809. if expected_value is not None or condition.comparison_operator in ("empty", "not empty"):
  810. if isinstance(expected_value, str):
  811. expected_value = self._replace_metadata_filter_value(expected_value, inputs)
  812. filters = self._process_metadata_filter_func(
  813. sequence,
  814. condition.comparison_operator,
  815. metadata_name,
  816. expected_value,
  817. filters,
  818. )
  819. else:
  820. raise ValueError("Invalid metadata filtering mode")
  821. if filters:
  822. if metadata_filtering_conditions.logical_operator == "or": # type: ignore
  823. document_query = document_query.filter(or_(*filters))
  824. else:
  825. document_query = document_query.filter(and_(*filters))
  826. documents = document_query.all()
  827. # group by dataset_id
  828. metadata_filter_document_ids = defaultdict(list) if documents else None # type: ignore
  829. for document in documents:
  830. metadata_filter_document_ids[document.dataset_id].append(document.id) # type: ignore
  831. return metadata_filter_document_ids, metadata_condition
  832. def _replace_metadata_filter_value(self, text: str, inputs: dict) -> str:
  833. def replacer(match):
  834. key = match.group(1)
  835. return str(inputs.get(key, f"{{{{{key}}}}}"))
  836. pattern = re.compile(r"\{\{(\w+)\}\}")
  837. output = pattern.sub(replacer, text)
  838. if isinstance(output, str):
  839. output = re.sub(r"[\r\n\t]+", " ", output).strip()
  840. return output
  841. def _automatic_metadata_filter_func(
  842. self, dataset_ids: list, query: str, tenant_id: str, user_id: str, metadata_model_config: ModelConfig
  843. ) -> Optional[list[dict[str, Any]]]:
  844. # get all metadata field
  845. metadata_fields = db.session.query(DatasetMetadata).filter(DatasetMetadata.dataset_id.in_(dataset_ids)).all()
  846. all_metadata_fields = [metadata_field.name for metadata_field in metadata_fields]
  847. # get metadata model config
  848. if metadata_model_config is None:
  849. raise ValueError("metadata_model_config is required")
  850. # get metadata model instance
  851. # fetch model config
  852. model_instance, model_config = self._fetch_model_config(tenant_id, metadata_model_config)
  853. # fetch prompt messages
  854. prompt_messages, stop = self._get_prompt_template(
  855. model_config=model_config,
  856. mode=metadata_model_config.mode,
  857. metadata_fields=all_metadata_fields,
  858. query=query or "",
  859. )
  860. result_text = ""
  861. try:
  862. # handle invoke result
  863. invoke_result = cast(
  864. Generator[LLMResult, None, None],
  865. model_instance.invoke_llm(
  866. prompt_messages=prompt_messages,
  867. model_parameters=model_config.parameters,
  868. stop=stop,
  869. stream=True,
  870. user=user_id,
  871. ),
  872. )
  873. # handle invoke result
  874. result_text, usage = self._handle_invoke_result(invoke_result=invoke_result)
  875. result_text_json = parse_and_check_json_markdown(result_text, [])
  876. automatic_metadata_filters = []
  877. if "metadata_map" in result_text_json:
  878. metadata_map = result_text_json["metadata_map"]
  879. for item in metadata_map:
  880. if item.get("metadata_field_name") in all_metadata_fields:
  881. automatic_metadata_filters.append(
  882. {
  883. "metadata_name": item.get("metadata_field_name"),
  884. "value": item.get("metadata_field_value"),
  885. "condition": item.get("comparison_operator"),
  886. }
  887. )
  888. except Exception as e:
  889. return None
  890. return automatic_metadata_filters
  891. def _process_metadata_filter_func(
  892. self, sequence: int, condition: str, metadata_name: str, value: Optional[Any], filters: list
  893. ):
  894. key = f"{metadata_name}_{sequence}"
  895. key_value = f"{metadata_name}_{sequence}_value"
  896. match condition:
  897. case "contains":
  898. filters.append(
  899. (text(f"documents.doc_metadata ->> :{key} LIKE :{key_value}")).params(
  900. **{key: metadata_name, key_value: f"%{value}%"}
  901. )
  902. )
  903. case "not contains":
  904. filters.append(
  905. (text(f"documents.doc_metadata ->> :{key} NOT LIKE :{key_value}")).params(
  906. **{key: metadata_name, key_value: f"%{value}%"}
  907. )
  908. )
  909. case "start with":
  910. filters.append(
  911. (text(f"documents.doc_metadata ->> :{key} LIKE :{key_value}")).params(
  912. **{key: metadata_name, key_value: f"{value}%"}
  913. )
  914. )
  915. case "end with":
  916. filters.append(
  917. (text(f"documents.doc_metadata ->> :{key} LIKE :{key_value}")).params(
  918. **{key: metadata_name, key_value: f"%{value}"}
  919. )
  920. )
  921. case "is" | "=":
  922. if isinstance(value, str):
  923. filters.append(DatasetDocument.doc_metadata[metadata_name] == f'"{value}"')
  924. else:
  925. filters.append(
  926. sqlalchemy_cast(DatasetDocument.doc_metadata[metadata_name].astext, Integer) == value
  927. )
  928. case "is not" | "≠":
  929. if isinstance(value, str):
  930. filters.append(DatasetDocument.doc_metadata[metadata_name] != f'"{value}"')
  931. else:
  932. filters.append(
  933. sqlalchemy_cast(DatasetDocument.doc_metadata[metadata_name].astext, Integer) != value
  934. )
  935. case "empty":
  936. filters.append(DatasetDocument.doc_metadata[metadata_name].is_(None))
  937. case "not empty":
  938. filters.append(DatasetDocument.doc_metadata[metadata_name].isnot(None))
  939. case "before" | "<":
  940. filters.append(sqlalchemy_cast(DatasetDocument.doc_metadata[metadata_name].astext, Integer) < value)
  941. case "after" | ">":
  942. filters.append(sqlalchemy_cast(DatasetDocument.doc_metadata[metadata_name].astext, Integer) > value)
  943. case "≤" | "<=":
  944. filters.append(sqlalchemy_cast(DatasetDocument.doc_metadata[metadata_name].astext, Integer) <= value)
  945. case "≥" | ">=":
  946. filters.append(sqlalchemy_cast(DatasetDocument.doc_metadata[metadata_name].astext, Integer) >= value)
  947. case _:
  948. pass
  949. return filters
  950. def _fetch_model_config(
  951. self, tenant_id: str, model: ModelConfig
  952. ) -> tuple[ModelInstance, ModelConfigWithCredentialsEntity]:
  953. """
  954. Fetch model config
  955. """
  956. if model is None:
  957. raise ValueError("single_retrieval_config is required")
  958. model_name = model.name
  959. provider_name = model.provider
  960. model_manager = ModelManager()
  961. model_instance = model_manager.get_model_instance(
  962. tenant_id=tenant_id, model_type=ModelType.LLM, provider=provider_name, model=model_name
  963. )
  964. provider_model_bundle = model_instance.provider_model_bundle
  965. model_type_instance = model_instance.model_type_instance
  966. model_type_instance = cast(LargeLanguageModel, model_type_instance)
  967. model_credentials = model_instance.credentials
  968. # check model
  969. provider_model = provider_model_bundle.configuration.get_provider_model(
  970. model=model_name, model_type=ModelType.LLM
  971. )
  972. if provider_model is None:
  973. raise ValueError(f"Model {model_name} not exist.")
  974. if provider_model.status == ModelStatus.NO_CONFIGURE:
  975. raise ValueError(f"Model {model_name} credentials is not initialized.")
  976. elif provider_model.status == ModelStatus.NO_PERMISSION:
  977. raise ValueError(f"Dify Hosted OpenAI {model_name} currently not support.")
  978. elif provider_model.status == ModelStatus.QUOTA_EXCEEDED:
  979. raise ValueError(f"Model provider {provider_name} quota exceeded.")
  980. # model config
  981. completion_params = model.completion_params
  982. stop = []
  983. if "stop" in completion_params:
  984. stop = completion_params["stop"]
  985. del completion_params["stop"]
  986. # get model mode
  987. model_mode = model.mode
  988. if not model_mode:
  989. raise ValueError("LLM mode is required.")
  990. model_schema = model_type_instance.get_model_schema(model_name, model_credentials)
  991. if not model_schema:
  992. raise ValueError(f"Model {model_name} not exist.")
  993. return model_instance, ModelConfigWithCredentialsEntity(
  994. provider=provider_name,
  995. model=model_name,
  996. model_schema=model_schema,
  997. mode=model_mode,
  998. provider_model_bundle=provider_model_bundle,
  999. credentials=model_credentials,
  1000. parameters=completion_params,
  1001. stop=stop,
  1002. )
  1003. def _get_prompt_template(
  1004. self, model_config: ModelConfigWithCredentialsEntity, mode: str, metadata_fields: list, query: str
  1005. ):
  1006. model_mode = ModelMode.value_of(mode)
  1007. input_text = query
  1008. prompt_template: Union[CompletionModelPromptTemplate, list[ChatModelMessage]]
  1009. if model_mode == ModelMode.CHAT:
  1010. prompt_template = []
  1011. system_prompt_messages = ChatModelMessage(role=PromptMessageRole.SYSTEM, text=METADATA_FILTER_SYSTEM_PROMPT)
  1012. prompt_template.append(system_prompt_messages)
  1013. user_prompt_message_1 = ChatModelMessage(role=PromptMessageRole.USER, text=METADATA_FILTER_USER_PROMPT_1)
  1014. prompt_template.append(user_prompt_message_1)
  1015. assistant_prompt_message_1 = ChatModelMessage(
  1016. role=PromptMessageRole.ASSISTANT, text=METADATA_FILTER_ASSISTANT_PROMPT_1
  1017. )
  1018. prompt_template.append(assistant_prompt_message_1)
  1019. user_prompt_message_2 = ChatModelMessage(role=PromptMessageRole.USER, text=METADATA_FILTER_USER_PROMPT_2)
  1020. prompt_template.append(user_prompt_message_2)
  1021. assistant_prompt_message_2 = ChatModelMessage(
  1022. role=PromptMessageRole.ASSISTANT, text=METADATA_FILTER_ASSISTANT_PROMPT_2
  1023. )
  1024. prompt_template.append(assistant_prompt_message_2)
  1025. user_prompt_message_3 = ChatModelMessage(
  1026. role=PromptMessageRole.USER,
  1027. text=METADATA_FILTER_USER_PROMPT_3.format(
  1028. input_text=input_text,
  1029. metadata_fields=json.dumps(metadata_fields, ensure_ascii=False),
  1030. ),
  1031. )
  1032. prompt_template.append(user_prompt_message_3)
  1033. elif model_mode == ModelMode.COMPLETION:
  1034. prompt_template = CompletionModelPromptTemplate(
  1035. text=METADATA_FILTER_COMPLETION_PROMPT.format(
  1036. input_text=input_text,
  1037. metadata_fields=json.dumps(metadata_fields, ensure_ascii=False),
  1038. )
  1039. )
  1040. else:
  1041. raise ValueError(f"Model mode {model_mode} not support.")
  1042. prompt_transform = AdvancedPromptTransform()
  1043. prompt_messages = prompt_transform.get_prompt(
  1044. prompt_template=prompt_template,
  1045. inputs={},
  1046. query=query or "",
  1047. files=[],
  1048. context=None,
  1049. memory_config=None,
  1050. memory=None,
  1051. model_config=model_config,
  1052. )
  1053. stop = model_config.stop
  1054. return prompt_messages, stop
  1055. def _handle_invoke_result(self, invoke_result: Generator) -> tuple[str, LLMUsage]:
  1056. """
  1057. Handle invoke result
  1058. :param invoke_result: invoke result
  1059. :return:
  1060. """
  1061. model = None
  1062. prompt_messages: list[PromptMessage] = []
  1063. full_text = ""
  1064. usage = None
  1065. for result in invoke_result:
  1066. text = result.delta.message.content
  1067. full_text += text
  1068. if not model:
  1069. model = result.model
  1070. if not prompt_messages:
  1071. prompt_messages = result.prompt_messages
  1072. if not usage and result.delta.usage:
  1073. usage = result.delta.usage
  1074. if not usage:
  1075. usage = LLMUsage.empty_usage()
  1076. return full_text, usage