file_search_tool.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. from typing import Type, List
  2. from pydantic import BaseModel, Field
  3. from sqlalchemy.orm import Session
  4. from app.core.tools.base_tool import BaseTool
  5. from app.models.run import Run
  6. from app.services.file.file import FileService
  7. from app.services.assistant.assistant import AssistantService
  8. # return '## important:You can use the "retrieval" tool to search for relevant information.\n If you are asking about the content of the files, please specify any keywords, topics, or context you are looking for to help retrieve the most relevant content.'
  9. # query: str = Field(
  10. # ...,
  11. # description="query to look up in retrieval",
  12. # )
  13. # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  14. # query: str = Field(..., description="query to look up in retrieval")
  15. class FileSearchToolInput(BaseModel):
  16. query: str = Field(
  17. ...,
  18. description="query to look up in retrieval",
  19. )
  20. class FileSearchTool(BaseTool):
  21. name: str = "file_search"
  22. description: str = (
  23. "Can be used to search through content of files uploaded by the user."
  24. + "If the user references specific file content (e.g., 'in my uploaded document...'), this function should be triggered."
  25. + "If the user has uploaded files in multiple batches, and their request is ambiguous (e.g. 'summarize the documents'), default to summarizing only the most recent batch of uploaded files. If the user's intent is to include older files, they should specify this explicitly."
  26. + "Singleton operation: Strictly 1 invocation per API call"
  27. )
  28. args_schema: Type[BaseModel] = FileSearchToolInput
  29. def __init__(self) -> None:
  30. super().__init__()
  31. self.__filenames = []
  32. self.__keys = []
  33. self.__dirkeys = []
  34. self.loop = None
  35. self.index = 0
  36. def configure(self, session: Session, run: Run, **kwargs):
  37. # 获取当前事件循环
  38. # document_id = []
  39. file_key = []
  40. # filesinfo = []
  41. # 后语要从知识库里选择文件,所以在openassistant的数据库里可能不存在
  42. for key in run.file_ids:
  43. if len(key) == 36:
  44. self.__keys.append(key) # 添加文件id 作为检索
  45. else:
  46. file_key.append(
  47. key
  48. ) ## assiatant的id数据,在r2r里没办法检索需要提取filekey字段
  49. print(
  50. "document_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_iddocument_id"
  51. )
  52. # print(document_id)
  53. print(file_key)
  54. files = []
  55. # 这种情况是uuid.ex 这种格式的在最早的时候存在的,后续要去掉
  56. if len(file_key) > 0:
  57. ## 获取文件信息
  58. files = FileService.get_file_list_by_ids(session=session, file_ids=file_key)
  59. for file in files:
  60. self.__keys.append(file.key)
  61. print(files)
  62. """
  63. # 读取assistant的数据,获取文件夹的id
  64. db_asst = AssistantService.get_assistant_sync(
  65. session=session, assistant_id=run.assistant_id
  66. )
  67. if db_asst.tool_resources and "file_search" in db_asst.tool_resources:
  68. ##{"file_search": {"vector_store_ids": [{"file_ids": []}]}}
  69. asst_folder_ids = (
  70. db_asst.tool_resources.get("file_search")
  71. .get("vector_stores")[0]
  72. .get("folder_ids")
  73. )
  74. print(asst_folder_ids)
  75. # folder_fileinfo = []
  76. if asst_folder_ids:
  77. self.__dirkeys = asst_folder_ids
  78. """
  79. # pre-cache data to prevent thread conflicts that may occur later on.
  80. print(
  81. "---------ssssssssssss-----------------sssssssssssss---------------ssssssssssssss-------------sssssssssssss-------------ss-------"
  82. )
  83. print(self.__dirkeys)
  84. print(self.__keys)
  85. # indexes: List[int],
  86. def run(self, query: str) -> dict:
  87. print(
  88. "file_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keysfile_keys"
  89. )
  90. print(self.__keys)
  91. print(self.__dirkeys)
  92. files = []
  93. ## 必须有总结的内容query和才能触发
  94. if self.index == 0 and query:
  95. try:
  96. files = FileService.search_in_files(
  97. query=query, file_keys=self.__keys, folder_keys=self.__dirkeys
  98. )
  99. self.index = 1
  100. except Exception as e:
  101. print(e)
  102. # print(files)
  103. return files
  104. def instruction_supplement(self) -> str:
  105. """
  106. 为 Retrieval 提供文件选择信息,用于 llm 调用抉择
  107. """
  108. if (self.__keys and len(self.__keys) > 0) or (
  109. self.__dirkeys and len(self.__dirkeys) > 0
  110. ):
  111. return ""
  112. else:
  113. return "如果您不确定用户发的文件内容或者代码库结构,请使用文件搜索工具读取内容并收集相关信息,不要瞎猜或者编造答案。"