file_search_tool.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. import asyncio
  9. class FileSearchToolInput(BaseModel):
  10. indexes: List[int] = Field(
  11. ..., description="file index list to look up in retrieval"
  12. )
  13. query: str = Field(..., description="query to look up in retrieval")
  14. class FileSearchTool(BaseTool):
  15. name: str = "file_search"
  16. description: str = (
  17. "Can be used to look up information that was uploaded to this assistant."
  18. "If the user is referencing particular files, that is often a good hint that information may be here."
  19. )
  20. args_schema: Type[BaseModel] = FileSearchToolInput
  21. def __init__(self) -> None:
  22. super().__init__()
  23. self.__filenames = []
  24. self.__keys = []
  25. def configure(self, session: Session, run: Run, **kwargs):
  26. """
  27. 置当前 Retrieval 涉及文件信息
  28. """
  29. ## 获取文件信息
  30. files = FileService.get_file_list_by_ids(session=session, file_ids=run.file_ids)
  31. # files = FileService.list_in_files(ids=run.file_ids, offset=0, limit=100)
  32. loop = asyncio.get_event_loop() # 获取当前事件循环
  33. db_asst = AssistantService.get_assistant_sync(
  34. session=session, assistant_id=run.assistant_id
  35. )
  36. if db_asst.tool_resources and "file_search" in db_asst.tool_resources:
  37. ##{"file_search": {"vector_store_ids": [{"file_ids": []}]}}
  38. asst_folder_ids = (
  39. db_asst.tool_resources.get("file_search")
  40. .get("vector_stores")[0]
  41. .get("folder_ids")
  42. )
  43. print(asst_folder_ids)
  44. folder_fileinfo = []
  45. if asst_folder_ids:
  46. for fid in asst_folder_ids:
  47. folder_fileinfo += FileService.list_documents(
  48. id=fid, offset=0, limit=100
  49. )
  50. print(folder_fileinfo)
  51. for file in folder_fileinfo:
  52. self.__filenames.append(file.get("title"))
  53. self.__keys.append(file.get("metadata").get("file_key"))
  54. # pre-cache data to prevent thread conflicts that may occur later on.
  55. print(
  56. "---------ssssssssssss-----------------sssssssssssss---------------ssssssssssssss-------------sssssssssssss-------------ss-------"
  57. )
  58. print(files)
  59. for file in files:
  60. self.__filenames.append(file.filename)
  61. self.__keys.append(file.key)
  62. print(self.__keys)
  63. def run(self, indexes: List[int], query: str) -> dict:
  64. file_keys = []
  65. print(self.__keys)
  66. for index in indexes:
  67. file_key = self.__keys[index]
  68. file_keys.append(file_key)
  69. files = FileService.search_in_files(query=query, file_keys=file_keys)
  70. return files
  71. def instruction_supplement(self) -> str:
  72. """
  73. 为 Retrieval 提供文件选择信息,用于 llm 调用抉择
  74. """
  75. if len(self.__filenames) == 0:
  76. return ""
  77. else:
  78. filenames_info = [
  79. f"({index}){filename}"
  80. for index, filename in enumerate(self.__filenames)
  81. ]
  82. return (
  83. 'You can use the "retrieval" tool to retrieve relevant context from the following attached files. '
  84. + 'Each line represents a file in the format "(index)filename":\n'
  85. + "\n".join(filenames_info)
  86. + "\nMake sure to be extremely concise when using attached files. "
  87. )