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 53KB

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