file_search_tool.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. description="The exact content or keywords to search for in the files/knowledge base.",
  18. )
  19. class FileSearchTool(BaseTool):
  20. name: str = "file_search"
  21. description: str = (
  22. "Retrieve specific content from uploaded files or the knowledge base. Use this when the user explicitly requests information from a file (e.g., PDF, Excel) or references uploaded data. Strictly invoke ONCE per API call."
  23. )
  24. args_schema: Type[BaseModel] = FileSearchToolInput
  25. def __init__(self) -> None:
  26. super().__init__()
  27. self.__filenames = []
  28. self.__keys = []
  29. self.__dirkeys = []
  30. self.loop = None
  31. self.index = 0
  32. def configure(self, session: Session, run: Run, **kwargs):
  33. # 获取当前事件循环
  34. # document_id = []
  35. file_key = []
  36. # filesinfo = []
  37. # 后语要从知识库里选择文件,所以在openassistant的数据库里可能不存在
  38. for key in run.file_ids:
  39. if len(key) == 36:
  40. self.__keys.append(key) # 添加文件id 作为检索
  41. else:
  42. file_key.append(
  43. key
  44. ) ## assiatant的id数据,在r2r里没办法检索需要提取filekey字段
  45. print(
  46. "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"
  47. )
  48. # print(document_id)
  49. print(file_key)
  50. files = []
  51. # 这种情况是uuid.ex 这种格式的在最早的时候存在的,后续要去掉
  52. if len(file_key) > 0:
  53. ## 获取文件信息
  54. files = FileService.get_file_list_by_ids(session=session, file_ids=file_key)
  55. for file in files:
  56. self.__keys.append(file.key)
  57. print(files)
  58. # 读取assistant的数据,获取文件夹的id
  59. db_asst = AssistantService.get_assistant_sync(
  60. session=session, assistant_id=run.assistant_id
  61. )
  62. if db_asst.tool_resources and "file_search" in db_asst.tool_resources:
  63. ##{"file_search": {"vector_store_ids": [{"file_ids": []}]}}
  64. asst_folder_ids = (
  65. db_asst.tool_resources.get("file_search")
  66. .get("vector_stores")[0]
  67. .get("folder_ids")
  68. )
  69. print(asst_folder_ids)
  70. # folder_fileinfo = []
  71. if asst_folder_ids:
  72. self.__dirkeys = asst_folder_ids
  73. # pre-cache data to prevent thread conflicts that may occur later on.
  74. print(
  75. "---------ssssssssssss-----------------sssssssssssss---------------ssssssssssssss-------------sssssssssssss-------------ss-------"
  76. )
  77. print(self.__dirkeys)
  78. print(self.__keys)
  79. # indexes: List[int],
  80. def run(self, query: str) -> dict:
  81. print(
  82. "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"
  83. )
  84. print(self.__keys)
  85. print(self.__dirkeys)
  86. files = []
  87. if self.index == 0:
  88. files = FileService.search_in_files(
  89. query=query, file_keys=self.__keys, folder_keys=self.__dirkeys
  90. )
  91. self.index = 1
  92. print(files)
  93. return files
  94. def instruction_supplement(self) -> str:
  95. """
  96. 为 Retrieval 提供文件选择信息,用于 llm 调用抉择
  97. """
  98. if (self.__keys and len(self.__keys) > 0) or (
  99. self.__dirkeys and len(self.__dirkeys) > 0
  100. ):
  101. return ""
  102. else:
  103. return ""