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.

Updated examples + rm to use duckduckgo

zenith1100a5a3191770e
diff --git a/examples/run_storm_wiki_claude.py b/examples/run_storm_wiki_claude.py
index a3d3727..ccefc37 100644
--- a/examples/run_storm_wiki_claude.py
+++ b/examples/run_storm_wiki_claude.py
@@ -2,7 +2,7 @@
STORM Wiki pipeline powered by Claude family models and You.com search engine.
You need to set up the following environment variables to run this script:
- ANTHROPIC_API_KEY: Anthropic API key
- - YDC_API_KEY: You.com API key; or, BING_SEARCH_API_KEY: Bing Search API key
+ - YDC_API_KEY: You.com API key; BING_SEARCH_API_KEY: Bing Search API key, SERPER_API_KEY: Serper API key, BRAVE_API_KEY: Brave API key
Output will be structured as below
args.output_dir/
@@ -21,7 +21,7 @@ from argparse import ArgumentParser
from knowledge_storm import STORMWikiRunnerArguments, STORMWikiRunner, STORMWikiLMConfigs
from knowledge_storm.lm import ClaudeModel
-from knowledge_storm.rm import YouRM, BingSearch, BraveRM
+from knowledge_storm.rm import YouRM, BingSearch, BraveRM, SerperRM, DuckDuckGoSearchRM
from knowledge_storm.utils import load_api_key
@@ -61,13 +61,20 @@ def main(args):
# STORM is a knowledge curation system which consumes information from the retrieval module.
# Currently, the information source is the Internet and we use search engine API as the retrieval module.
- if args.retriever == 'bing':
- rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'you':
- rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'brave':
- rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
-
+ match args.retriver:
+ case 'bing':
+ rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
+ case 'you':
+ rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
+ case 'brave':
+ rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ case 'duckduckgo':
+ rm = DuckDuckGoSearchRM(k=engine_args.search_top_k, safe_search='On', region='us-en')
+ case 'serper':
+ rm = SerperRM(serper_search_api_key=os.getenv('SERPER_API_KEY'), query_params={'autocorrect': True, 'num': 10, 'page': 1})
+ case _:
+ raise ValueError(f'Invalid retriever: {args.retriever}. Choose either "bing", "you", "brave", "duckduckgo", or "serper"')
+
runner = STORMWikiRunner(engine_args, lm_configs, rm)
topic = input('Topic: ')
@@ -91,7 +98,7 @@ if __name__ == '__main__':
help='Maximum number of threads to use. The information seeking part and the article generation'
'part can speed up by using multiple threads. Consider reducing it if keep getting '
'"Exceed rate limit" error when calling LM API.')
- parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave'],
+ parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave', 'serper', 'duckduckgo'],
help='The search engine API to use for retrieving information.')
# stage of the pipeline
parser.add_argument('--do-research', action='store_true',
diff --git a/examples/run_storm_wiki_deepseek.py b/examples/run_storm_wiki_deepseek.py
index 340935d..8ac5e99 100644
--- a/examples/run_storm_wiki_deepseek.py
+++ b/examples/run_storm_wiki_deepseek.py
@@ -3,7 +3,7 @@ STORM Wiki pipeline powered by DeepSeek models and You.com or Bing search engine
You need to set up the following environment variables to run this script:
- DEEPSEEK_API_KEY: DeepSeek API key
- DEEPSEEK_API_BASE: DeepSeek API base URL (default is https://api.deepseek.com)
- - YDC_API_KEY: You.com API key; or, BING_SEARCH_API_KEY: Bing Search API key
+ - YDC_API_KEY: You.com API key; BING_SEARCH_API_KEY: Bing Search API key, SERPER_API_KEY: Serper API key, BRAVE_API_KEY: Brave API key
Output will be structured as below
args.output_dir/
@@ -25,7 +25,7 @@ from argparse import ArgumentParser
from knowledge_storm import STORMWikiRunnerArguments, STORMWikiRunner, STORMWikiLMConfigs
from knowledge_storm.lm import DeepSeekModel
-from knowledge_storm.rm import YouRM, BingSearch, BraveRM
+from knowledge_storm.rm import YouRM, BingSearch, BraveRM, SerperRM, DuckDuckGoSearchRM
from knowledge_storm.utils import load_api_key
@@ -51,6 +51,8 @@ def main(args):
load_api_key(toml_file_path='secrets.toml')
lm_configs = STORMWikiLMConfigs()
+ logger = logging.getLogger(__name__)
+
# Ensure DEEPSEEK_API_KEY is set
if not os.getenv("DEEPSEEK_API_KEY"):
raise ValueError("DEEPSEEK_API_KEY environment variable is not set. Please set it in your secrets.toml file.")
@@ -86,14 +88,19 @@ def main(args):
# STORM is a knowledge curation system which consumes information from the retrieval module.
# Currently, the information source is the Internet and we use search engine API as the retrieval module.
- if args.retriever == 'bing':
- rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'you':
- rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'brave':
- rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
- else:
- raise ValueError(f"Invalid retriever: {args.retriever}. Choose either 'bing' or 'you'.")
+ match args.retriver:
+ case 'bing':
+ rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
+ case 'you':
+ rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
+ case 'brave':
+ rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ case 'duckduckgo':
+ rm = DuckDuckGoSearchRM(k=engine_args.search_top_k, safe_search='On', region='us-en')
+ case 'serper':
+ rm = SerperRM(serper_search_api_key=os.getenv('SERPER_API_KEY'), query_params={'autocorrect': True, 'num': 10, 'page': 1})
+ case _:
+ raise ValueError(f'Invalid retriever: {args.retriever}. Choose either "bing", "you", "brave", "duckduckgo", or "serper"')
runner = STORMWikiRunner(engine_args, lm_configs, rm)
@@ -125,7 +132,7 @@ if __name__ == '__main__':
help='Maximum number of threads to use. The information seeking part and the article generation'
'part can speed up by using multiple threads. Consider reducing it if keep getting '
'"Exceed rate limit" error when calling LM API.')
- parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave'], required=True,
+ parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave', 'serper', 'duckduckgo'], required=True,
help='The search engine API to use for retrieving information.')
parser.add_argument('--model', type=str, choices=['deepseek-chat', 'deepseek-coder'], default='deepseek-chat',
help='DeepSeek model to use. "deepseek-chat" for general tasks, "deepseek-coder" for coding tasks.')
diff --git a/examples/run_storm_wiki_gemini.py b/examples/run_storm_wiki_gemini.py
index dac20cb..81d430f 100644
--- a/examples/run_storm_wiki_gemini.py
+++ b/examples/run_storm_wiki_gemini.py
@@ -2,7 +2,7 @@
STORM Wiki pipeline powered by Google Gemini models and search engine.
You need to set up the following environment variables to run this script:
- GOOGLE_API_KEY: Google API key (Can be obtained from https://ai.google.dev/gemini-api/docs/api-key)
- - YDC_API_KEY: You.com API key; or, BING_SEARCH_API_KEY: Bing Search API key
+ - YDC_API_KEY: You.com API key; BING_SEARCH_API_KEY: Bing Search API key, SERPER_API_KEY: Serper API key, BRAVE_API_KEY: Brave API key
Output will be structured as below
args.output_dir/
@@ -21,7 +21,7 @@ from argparse import ArgumentParser
from knowledge_storm import STORMWikiRunnerArguments, STORMWikiRunner, STORMWikiLMConfigs
from knowledge_storm.lm import GoogleModel
-from knowledge_storm.rm import YouRM, BingSearch, BraveRM
+from knowledge_storm.rm import YouRM, BingSearch, BraveRM, SerperRM, DuckDuckGoSearchRM
from knowledge_storm.utils import load_api_key
@@ -63,12 +63,19 @@ def main(args):
# STORM is a knowledge curation system which consumes information from the retrieval module.
# Currently, the information source is the Internet and we use search engine API as the retrieval module.
- if args.retriever == 'bing':
- rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'you':
- rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'brave':
- rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ match args.retriver:
+ case 'bing':
+ rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
+ case 'you':
+ rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
+ case 'brave':
+ rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ case 'duckduckgo':
+ rm = DuckDuckGoSearchRM(k=engine_args.search_top_k, safe_search='On', region='us-en')
+ case 'serper':
+ rm = SerperRM(serper_search_api_key=os.getenv('SERPER_API_KEY'), query_params={'autocorrect': True, 'num': 10, 'page': 1})
+ case _:
+ raise ValueError(f'Invalid retriever: {args.retriever}. Choose either "bing", "you", "brave", "duckduckgo", or "serper"')
runner = STORMWikiRunner(engine_args, lm_configs, rm)
@@ -93,7 +100,7 @@ if __name__ == '__main__':
help='Maximum number of threads to use. The information seeking part and the article generation'
'part can speed up by using multiple threads. Consider reducing it if keep getting '
'"Exceed rate limit" error when calling LM API.')
- parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave'],
+ parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave', 'serper', 'duckduckgo'],
help='The search engine API to use for retrieving information.')
# stage of the pipeline
parser.add_argument('--do-research', action='store_true',
diff --git a/examples/run_storm_wiki_gpt.py b/examples/run_storm_wiki_gpt.py
index bc0b904..530b8a1 100644
--- a/examples/run_storm_wiki_gpt.py
+++ b/examples/run_storm_wiki_gpt.py
@@ -5,7 +5,7 @@ You need to set up the following environment variables to run this script:
- OPENAI_API_TYPE: OpenAI API type (e.g., 'openai' or 'azure')
- AZURE_API_BASE: Azure API base URL if using Azure API
- AZURE_API_VERSION: Azure API version if using Azure API
- - YDC_API_KEY: You.com API key; or, BING_SEARCH_API_KEY: Bing Search API key
+ - YDC_API_KEY: You.com API key; BING_SEARCH_API_KEY: Bing Search API key, SERPER_API_KEY: Serper API key, BRAVE_API_KEY: Brave API key
Output will be structured as below
args.output_dir/
@@ -24,7 +24,7 @@ from argparse import ArgumentParser
from knowledge_storm import STORMWikiRunnerArguments, STORMWikiRunner, STORMWikiLMConfigs
from knowledge_storm.lm import OpenAIModel, AzureOpenAIModel
-from knowledge_storm.rm import YouRM, BingSearch, BraveRM
+from knowledge_storm.rm import YouRM, BingSearch, BraveRM, SerperRM, DuckDuckGoSearchRM
from knowledge_storm.utils import load_api_key
@@ -73,12 +73,19 @@ def main(args):
# STORM is a knowledge curation system which consumes information from the retrieval module.
# Currently, the information source is the Internet and we use search engine API as the retrieval module.
- if args.retriever == 'bing':
- rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'you':
- rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'brave':
- rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ match args.retriver:
+ case 'bing':
+ rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
+ case 'you':
+ rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
+ case 'brave':
+ rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ case 'duckduckgo':
+ rm = DuckDuckGoSearchRM(k=engine_args.search_top_k, safe_search='On', region='us-en')
+ case 'serper':
+ rm = SerperRM(serper_search_api_key=os.getenv('SERPER_API_KEY'), query_params={'autocorrect': True, 'num': 10, 'page': 1})
+ case _:
+ raise ValueError(f'Invalid retriever: {args.retriever}. Choose either "bing", "you", "brave", "duckduckgo", or "serper"')
runner = STORMWikiRunner(engine_args, lm_configs, rm)
@@ -103,7 +110,7 @@ if __name__ == '__main__':
help='Maximum number of threads to use. The information seeking part and the article generation'
'part can speed up by using multiple threads. Consider reducing it if keep getting '
'"Exceed rate limit" error when calling LM API.')
- parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave'],
+ parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave', 'serper', 'duckduckgo'],
help='The search engine API to use for retrieving information.')
# stage of the pipeline
parser.add_argument('--do-research', action='store_true',
diff --git a/examples/run_storm_wiki_mistral.py b/examples/run_storm_wiki_mistral.py
index 7a2ecf8..b4ecc60 100644
--- a/examples/run_storm_wiki_mistral.py
+++ b/examples/run_storm_wiki_mistral.py
@@ -1,7 +1,7 @@
"""
STORM Wiki pipeline powered by Mistral-7B-Instruct-v0.2 hosted by VLLM server and You.com search engine.
You need to set up the following environment variables to run this script:
- - YDC_API_KEY: You.com API key; or, BING_SEARCH_API_KEY: Bing Search API key
+ - YDC_API_KEY: You.com API key; BING_SEARCH_API_KEY: Bing Search API key, SERPER_API_KEY: Serper API key, BRAVE_API_KEY: Brave API key
You also need to have a VLLM server running with the Mistral-7B-Instruct-v0.2 model. Specify `--url` and `--port` accordingly.
Output will be structured as below
@@ -22,7 +22,7 @@ from dspy import Example
from knowledge_storm import STORMWikiRunnerArguments, STORMWikiRunner, STORMWikiLMConfigs
from knowledge_storm.lm import VLLMClient
-from knowledge_storm.rm import YouRM, BingSearch, BraveRM
+from knowledge_storm.rm import YouRM, BingSearch, BraveRM, SerperRM, DuckDuckGoSearchRM
from knowledge_storm.utils import load_api_key
@@ -59,12 +59,19 @@ def main(args):
# STORM is a knowledge curation system which consumes information from the retrieval module.
# Currently, the information source is the Internet and we use search engine API as the retrieval module.
- if args.retriever == 'bing':
- rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'you':
- rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'brave':
- rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ match args.retriver:
+ case 'bing':
+ rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
+ case 'you':
+ rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
+ case 'brave':
+ rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ case 'duckduckgo':
+ rm = DuckDuckGoSearchRM(k=engine_args.search_top_k, safe_search='On', region='us-en')
+ case 'serper':
+ rm = SerperRM(serper_search_api_key=os.getenv('SERPER_API_KEY'), query_params={'autocorrect': True, 'num': 10, 'page': 1})
+ case _:
+ raise ValueError(f'Invalid retriever: {args.retriever}. Choose either "bing", "you", "brave", "duckduckgo", or "serper"')
runner = STORMWikiRunner(engine_args, lm_configs, rm)
@@ -149,7 +156,7 @@ if __name__ == '__main__':
help='Maximum number of threads to use. The information seeking part and the article generation'
'part can speed up by using multiple threads. Consider reducing it if keep getting '
'"Exceed rate limit" error when calling LM API.')
- parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave'],
+ parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave', 'serper', 'duckduckgo'],
help='The search engine API to use for retrieving information.')
# stage of the pipeline
parser.add_argument('--do-research', action='store_true',
diff --git a/examples/run_storm_wiki_ollama.py b/examples/run_storm_wiki_ollama.py
index c526f1e..af35572 100644
--- a/examples/run_storm_wiki_ollama.py
+++ b/examples/run_storm_wiki_ollama.py
@@ -1,7 +1,7 @@
"""
STORM Wiki pipeline powered by local model hosted by Ollama server and You.com or Bing search engine.
You need to set up the following environment variables to run this script:
- - YDC_API_KEY: You.com API key; or, BING_SEARCH_API_KEY: Bing Search API key
+ - YDC_API_KEY: You.com API key; BING_SEARCH_API_KEY: Bing Search API key, SERPER_API_KEY: Serper API key, BRAVE_API_KEY: Brave API key
You also need to have a Ollama server running with the llama3 model or other. Specify `--url`, `--port` and `--model` accordingly.
Output will be structured as below
@@ -22,10 +22,10 @@ from argparse import ArgumentParser
from dspy import Example
sys.path.append('./src')
-from lm import OllamaClient
-from rm import YouRM, BingSearch, BraveRM
-from storm_wiki.engine import STORMWikiRunnerArguments, STORMWikiRunner, STORMWikiLMConfigs
-from utils import load_api_key
+from knowledge_storm.lm import OllamaClient
+from knowledge_storm.rm import YouRM, BingSearch, BraveRM, SerperRM, DuckDuckGoSearchRM
+from knowledge_storm import STORMWikiRunnerArguments, STORMWikiRunner, STORMWikiLMConfigs
+from knowledge_storm.utils import load_api_key
def main(args):
@@ -61,12 +61,19 @@ def main(args):
# STORM is a knowledge curation system which consumes information from the retrieval module.
# Currently, the information source is the Internet and we use search engine API as the retrieval module.
- if args.retriever == 'bing':
- rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'you':
- rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
- elif args.retriever == 'brave':
- rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ match args.retriver:
+ case 'bing':
+ rm = BingSearch(bing_search_api=os.getenv('BING_SEARCH_API_KEY'), k=engine_args.search_top_k)
+ case 'you':
+ rm = YouRM(ydc_api_key=os.getenv('YDC_API_KEY'), k=engine_args.search_top_k)
+ case 'brave':
+ rm = BraveRM(brave_search_api_key=os.getenv('BRAVE_API_KEY'), k=engine_args.search_top_k)
+ case 'duckduckgo':
+ rm = DuckDuckGoSearchRM(k=engine_args.search_top_k, safe_search='On', region='us-en')
+ case 'serper':
+ rm = SerperRM(serper_search_api_key=os.getenv('SERPER_API_KEY'), query_params={'autocorrect': True, 'num': 10, 'page': 1})
+ case _:
+ raise ValueError(f'Invalid retriever: {args.retriever}. Choose either "bing", "you", "brave", "duckduckgo", or "serper"')
runner = STORMWikiRunner(engine_args, lm_configs, rm)
@@ -153,7 +160,7 @@ if __name__ == '__main__':
help='Maximum number of threads to use. The information seeking part and the article generation'
'part can speed up by using multiple threads. Consider reducing it if keep getting '
'"Exceed rate limit" error when calling LM API.')
- parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave'],
+ parser.add_argument('--retriever', type=str, choices=['bing', 'you', 'brave', 'serper', 'duckduckgo'],
help='The search engine API to use for retrieving information.')
# stage of the pipeline
parser.add_argument('--do-research', action='store_true',
diff --git a/knowledge_storm/rm.py b/knowledge_storm/rm.py
index 4c438c4..afb7942 100644
--- a/knowledge_storm/rm.py
+++ b/knowledge_storm/rm.py
@@ -1,7 +1,7 @@
import logging
import os
from typing import Callable, Union, List
-
+from duckduckgo_search import DDGS
import dspy
import requests
@@ -509,3 +509,119 @@ class BraveRM(dspy.Retrieve):
logging.error(f'Error occurs when searching query {query}: {e}')
return collected_results
+
+class DuckDuckGoSearchRM(dspy.Retrieve):
+ def __init__(
+ self,
+ k: int =3,
+ is_valid_source: Callable = None,
+ min_char_count: int = 150,
+ snippet_chunk_size: int = 1000,
+ webpage_helper_max_threads=10,
+ safe_search: str = 'On',
+ region: str = 'us-en'
+ **kwargs,
+ ):
+ """
+ Params:
+ min_char_count: Minimum character count for the article to be considered valid.
+ snippet_chunk_size: Maximum character count for each snippet.
+ webpage_helper_max_threads: Maximum number of threads to use for webpage helper.
+ **kwargs: Additional parameters for the OpenAI API.
+ """
+ super().__init__(k=k)
+
+ self.k = k
+ self.webpage_helper = WebPageHelper(
+ min_char_count=min_char_count,
+ snippet_chunk_size=snippet_chunk_size,
+ max_thread_num=webpage_helper_max_threads,
+ )
+ self.usage = 0
+
+ # All params for search can be found here:
+ # https://duckduckgo.com/duckduckgo-help-pages/settings/params/
+
+ # Sets the backend to be api
+ self.duck_duck_go_backend = 'api'
+
+ # Only gets safe search results
+ self.duck_duck_go_safe_search = safe_search
+
+ # Specifies the region that the search will use
+ self.duck_duck_go_region = region
+
+
+ # If not None, is_valid_source shall be a function that takes a URL and returns a boolean.
+ if is_valid_source:
+ self.is_valid_source = is_valid_source
+ else:
+ self.is_valid_source = lambda x: True
+
+ # Import the duckduckgo search library found here: https://github.com/deedy5/duckduckgo_search
+ self.ddgs = DDGS()
+
+ # Store usage of credits and reset the class usage variable
+ def get_usage_and_reset(self):
+ usage = self.usage
+ self.usage = 0
+ return {'DuckDuckGoRM': usage}
+
+ # this is the important function that is used by Retriever in the pipeline
+ def forward(
+ self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = []
+ ):
+ """Search with DuckDuckGoSearch 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 = []
+
+ for query in queries:
+ # list of dicts that will be parsed to return
+ results = self.ddgs.text(
+ query, max_results=self.k, backend=self.duck_duck_go_backend
+ )
+
+ for d in results:
+ # assert d is dict
+ if not isinstance(d, dict):
+ print(f'Invalid result: {d}\n')
+ continue
+
+ try:
+ # ensure keys are present
+ url = d.get('href', None)
+ title = d.get('title', None)
+ description = d.get('description', title)
+ snippets = [d.get('body', None)]
+
+ # raise exception of missing key(s)
+ if not all([url, title, description, snippets]):
+ raise ValueError(f'Missing key(s) in result: {d}')
+ if self.is_valid_source(url) and url not in exclude_urls:
+ result = {
+ 'url': url,
+ 'title': title,
+ 'description': description,
+ 'snippets': snippets,
+ }
+ collected_results.append(result)
+ else:
+ print(f'invalid source {url} or url in exclude_urls')
+ except Exception as e:
+ print(f'Error occurs when processing {result=}: {e}\n')
+ print(f'Error occurs when searching query {query}: {e}')
+
+ return collected_results
+
diff --git a/requirements.txt b/requirements.txt
index 79ee9d6..5a679ff 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -8,3 +8,4 @@ langchain-huggingface
qdrant-client
langchain-qdrant
numpy==1.26.4
+duckduckgo_search
\ No newline at end of file