Skip to content

armgit / storm

Public Imported from GitHub
0

An LLM-powered knowledge curation system that researches a topic and generates a full-length report with citations.

Merge remote-tracking branch 'origin/main' into feature/add-support-for-searxng

Hanly De Los Santosfa45507b4f4a
diff --cc knowledge_storm/rm.py
index b9a29ae,0951ef3..6d0d2d1
--- a/knowledge_storm/rm.py
+++ b/knowledge_storm/rm.py
@@@ -405,69 -405,137 +405,204 @@@ class VectorRM(dspy.Retrieve)
return collected_results
+ class SerperRM(dspy.Retrieve):
+ """Retrieve information from custom queries using Serper.dev."""
-
++
+ def __init__(self, serper_search_api_key=None, query_params=None):
+ """Args:
+ serper_search_api_key str: API key to run serper, can be found by creating an account on https://serper.dev/
+ query_params (dict or list of dict): parameters in dictionary or list of dictionaries that has a max size of 100 that will be used to query.
+ Commonly used fields are as follows (see more information in https://serper.dev/playground):
+ q str: query that will be used with google search
+ type str: type that will be used for browsing google. Types are search, images, video, maps, places, etc.
+ gl str: Country that will be focused on for the search
+ location str: Country where the search will originate from. All locates can be found here: https://api.serper.dev/locations.
+ autocorrect bool: Enable autocorrect on the queries while searching, if query is misspelled, will be updated.
+ results int: Max number of results per page.
+ page int: Max number of pages per call.
+ tbs str: date time range, automatically set to any time by default.
+ qdr:h str: Date time range for the past hour.
+ qdr:d str: Date time range for the past 24 hours.
+ qdr:w str: Date time range for past week.
+ qdr:m str: Date time range for past month.
+ qdr:y str: Date time range for past year.
+ """
+ super().__init__()
+ self.usage = 0
+ self.query_params = query_params
+ self.serper_search_api_key = serper_search_api_key
+ if not self.serper_search_api_key and not os.environ.get('SERPER_API_KEY'):
+ raise RuntimeError(
+ 'You must supply a serper_search_api_key param or set environment variable SERPER_API_KEY'
+ )
+
+ elif self.serper_search_api_key:
+ self.serper_search_api_key = serper_search_api_key
+
+ else:
+ self.serper_search_api_key = os.environ['SERPER_API_KEY']
+
+ self.base_url = 'https://google.serper.dev'
+
+ def serper_runner(self, query_params):
+ self.search_url = f'{self.base_url}/search'
+
+ headers = {
+ 'X-API-KEY': self.serper_search_api_key,
+ 'Content-Type': 'application/json',
+ }
+
+ response = requests.request(
+ 'POST', self.search_url, headers=headers, json=query_params
+ )
+
+ if response == None:
+ raise RuntimeError(
+ f'Error had occured while running the search process.\n Error is {response.reason}, had failed with status code {response.status_code}'
+ )
+
+ return response.json()
+
+ def get_usage_and_reset(self):
+ usage = self.usage
+ self.usage = 0
+ return {'SerperRM': usage}
+
+ def forward(self, query_or_queries: Union[str, List[str]], exclude_urls: List[str]):
+ """
+ Calls the API and searches for the query passed in.
-
-
++
++
+ Args:
+ query_or_queries (Union[str, List[str]]): The query or queries to search for.
+ exclude_urls (List[str]): Dummy parameter to match the interface. Does not have any effect.
+
+ Returns:
+ a list of dictionaries, each dictionary has keys of 'description', 'snippets' (list of strings), 'title', 'url'
+ """
+ queries = (
+ [query_or_queries]
+ if isinstance(query_or_queries, str)
+ else query_or_queries
+ )
+
+ self.usage += len(queries)
+ self.results = []
+ collected_results = []
+ for query in queries:
+ if query == 'Queries:':
+ continue
+ query_params = self.query_params
-
++
+ # All available parameters can be found in the playground: https://serper.dev/playground
+ # Sets the json value for query to be the query that is being parsed.
+ query_params['q'] = query
+
+ # Sets the type to be search, can be images, video, places, maps etc that Google provides.
+ query_params['type'] = 'search'
+
+ self.result = self.serper_runner(query_params)
+ self.results.append(self.result)
+
+ # Array of dictionaries that will be used by Storm to create the jsons
+ collected_results = []
+
+ for result in self.results:
+ try:
+ # An array of dictionaries that contains the snippets, title of the document and url that will be used.
+ organic_results = result.get('organic')
+
+ knowledge_graph = result.get('knowledgeGraph')
+ for organic in organic_results:
+ snippets = []
+ snippets.append(organic.get('snippet'))
+ if knowledge_graph != None:
+ collected_results.append(
+ {
+ 'snippets': snippets,
+ 'title': organic.get('title'),
+ 'url': organic.get('link'),
+ 'description': knowledge_graph.get('description'),
+ }
+ )
+ else:
+ # Common for knowledge graph to be None, set description to empty string
+ collected_results.append(
+ {
+ 'snippets': snippets,
+ 'title': result.get('title'),
+ 'url': result.get('link'),
+ 'description': '',
+ }
+ )
+ except:
+ continue
+
+ return collected_results
++
+
+class SearXNG(dspy.Retrieve):
+ def __init__(self, searxng_api_url, searxng_api_key=None, k=3, is_valid_source: Callable = None):
+ """
+ Initialize the SearXNG search retriever.
+
+ Args:
+ searxng_api_url (str): The URL of the SearXNG API.
+ searxng_api_key (str, optional): The API key for the SearXNG API. Defaults to None.
+ k (int, optional): The number of top passages to retrieve. Defaults to 3.
+ is_valid_source (Callable, optional): A function that takes a URL and returns a boolean indicating if the source is valid. Defaults to None.
+ """
+ super().__init__(k=k)
+ if not searxng_api_url:
+ raise RuntimeError("You must supply searxng_api_url")
+ self.searxng_api_url = searxng_api_url
+ self.searxng_api_key = searxng_api_key
+ self.usage = 0
+
+ if is_valid_source:
+ self.is_valid_source = is_valid_source
+ else:
+ self.is_valid_source = lambda x: True
+
+ def get_usage_and_reset(self):
+ usage = self.usage
+ self.usage = 0
+ return {'SearXNG': usage}
+
+ def forward(self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = []):
+ """Search with SearxNG for self.k top passages for query or queries
+
+ Args:
+ query_or_queries (Union[str, List[str]]): The query or queries to search for.
+ exclude_urls (List[str]): A list of urls to exclude from the search results.
+
+ Returns:
+ a list of Dicts, each dict has keys of 'description', 'snippets' (list of strings), 'title', 'url'
+ """
+ queries = (
+ [query_or_queries]
+ if isinstance(query_or_queries, str)
+ else query_or_queries
+ )
+ self.usage += len(queries)
+ collected_results = []
+ headers = {"Authorization": f"Bearer {self.searxng_api_key}"} if self.searxng_api_key else {}
+
+ for query in queries:
+ try:
+ params = {"q": query, "format": "json"}
+ response = requests.get(self.searxng_api_url, headers=headers, params=params)
+ results = response.json()
+
+ for r in results['results']:
+ if self.is_valid_source(r['url']) and r['url'] not in exclude_urls:
+ collected_results.append({
+ 'description': r.get('content', ''),
+ 'snippets': [r.get('content', '')],
+ 'title': r.get('title', ''),
+ 'url': r['url']
+ })
+ except Exception as e:
+ logging.error(f'Error occurs when searching query {query}: {e}')
+
+ return collected_results