file_search_tool.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. class FileSearchToolInput(BaseModel):
  8. indexes: List[int] = Field(..., description="file index list to look up in retrieval")
  9. query: str = Field(..., description="query to look up in retrieval")
  10. class FileSearchTool(BaseTool):
  11. name: str = "file_search"
  12. description: str = (
  13. "Can be used to look up information that was uploaded to this assistant."
  14. "If the user is referencing particular files, that is often a good hint that information may be here."
  15. )
  16. args_schema: Type[BaseModel] = FileSearchToolInput
  17. def __init__(self) -> None:
  18. super().__init__()
  19. self.__filenames = []
  20. self.__keys = []
  21. def configure(self, session: Session, run: Run, **kwargs):
  22. """
  23. 置当前 Retrieval 涉及文件信息
  24. """
  25. files = FileService.get_file_list_by_ids(session=session, file_ids=run.file_ids)
  26. # pre-cache data to prevent thread conflicts that may occur later on.
  27. print("---------ssssssssssss-----------------sssssssssssss---------------ssssssssssssss-------------sssssssssssss-------------ss-------")
  28. print(files)
  29. for file in files:
  30. self.__filenames.append(file.filename)
  31. self.__keys.append(file.key)
  32. print(self.__keys)
  33. def run(self, indexes: List[int], query: str) -> dict:
  34. file_keys = []
  35. print(self.__keys)
  36. for index in indexes:
  37. file_key = self.__keys[index]
  38. file_keys.append(file_key)
  39. files = FileService.search_in_files(query=query, file_keys=file_keys)
  40. return files
  41. def instruction_supplement(self) -> str:
  42. """
  43. 为 Retrieval 提供文件选择信息,用于 llm 调用抉择
  44. """
  45. if len(self.__filenames) == 0:
  46. return ""
  47. else:
  48. filenames_info = [f"({index}){filename}" for index, filename in enumerate(self.__filenames)]
  49. return (
  50. 'You can use the "retrieval" tool to retrieve relevant context from the following attached files. '
  51. + 'Each line represents a file in the format "(index)filename":\n'
  52. + "\n".join(filenames_info)
  53. + "\nMake sure to be extremely concise when using attached files. "
  54. )