-
Notifications
You must be signed in to change notification settings - Fork 34
/
base_search_tool.py
56 lines (43 loc) · 1.82 KB
/
base_search_tool.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from dataclasses import dataclass
from abc import ABC, abstractmethod
from ..base_tool import BaseTool
@dataclass
class BaseSearchResult:
"""
A single search result.
"""
content: str
source: str
class BaseSearchTool(BaseTool):
"""A search tool that can run a query and return a formatted string of search results."""
@abstractmethod
def raw_search(self, query: str, n_search_results_to_use: int):
"""
Runs a query using the searcher, then returns the raw search results without formatting.
:param query: The query to run.
:param n_search_results_to_use: The number of results to return.
"""
def use_tool(self, query: str, n_search_results_to_use: int):
raw_search_results = self.raw_search(query, n_search_results_to_use)
displayable_search_results = BaseSearchTool._format_results_full(raw_search_results)
return displayable_search_results
@staticmethod
def _format_results(raw_search_results:list[BaseSearchResult]):
"""
Joins and formats the extracted search results as a string.
:param extracted: The extracted search results to format.
"""
result = "\n".join(
[
f'<item index="{i+1}">\n<source>{r.source}</source>\n<page_content>\n{r.content}\n</page_content>\n</item>'
for i, r in enumerate(raw_search_results)
]
)
return result
@staticmethod
def _format_results_full(extracted: list[list[str]]):
"""
Formats the extracted search results as a string, including the <search_results> tags.
:param extracted: The extracted search results to format.
"""
return f"\n<search_results>\n{BaseSearchTool._format_results(extracted)}\n</search_results>"