Skip to content

Commit 3005e07

Browse files
sandrohaneaSandro Hanea
andauthored
Added Bing APIs and docs (#29)
Co-authored-by: Sandro Hanea <[email protected]>
1 parent 4eaca1a commit 3005e07

File tree

5 files changed

+46
-16
lines changed

5 files changed

+46
-16
lines changed

.env.template

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
OPENAI_API_KEY=""
22
SEARCHAPI_API_KEY=""
33
GOOGLE_CSE_ID=""
4-
GOOGLE_API_KEY=""
4+
GOOGLE_API_KEY=""
5+
BING_API_KEY=""

README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,19 @@ poetry install
9696

9797
```python
9898
OPENAI_API_KEY="" # for OpenAI LLM backend
99-
SEARCHAPI_API_KEY="" # for Web Search
99+
BING_API_KEY="" # for Bing Web Search
100+
GOOGLE_API_KEY="" # for Google Web Search
101+
SEARCHAPI_API_KEY="" # for SearchAPI Web Search
100102
```
101103

104+
**Selecting the Search Engine**
105+
106+
The system will automatically select the appropriate search engine based on the following priority:
107+
108+
- [Bing API](https://www.microsoft.com/en-us/bing/apis/bing-web-search-api): If `BING_API_KEY` is provided
109+
- [Search API](https://www.searchapi.io/): If `SEARCHAPI_API_KEY` is provided
110+
- [Google API](https://developers.google.com/custom-search/?csw=1): If `GOOGLE_API_KEY` is provided
111+
102112
**Getting started with GPTSwarm is easy. Quickly run a predefined swarm**
103113

104114
```python

swarm/environment/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
from swarm.environment.tools.reader.readers import GeneralReader
2-
from swarm.environment.tools.search.search import GoogleSearchEngine, SearchAPIEngine
2+
from swarm.environment.tools.search.search import GoogleSearchEngine, SearchAPIEngine, BingSearchEngine
33

44

55
__all__ = [
66
"GeneralReader",
77
"GoogleSearchEngine",
8-
"SearchAPIEngine"
8+
"SearchAPIEngine",
9+
"BingSearchEngine"
910
]

swarm/environment/operations/web_search.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
33

4+
import os
45
from copy import deepcopy
56
from collections import defaultdict
7+
from dotenv import load_dotenv
68
from typing import List, Any, Optional
79

810
from swarm.llm.format import Message
911
from swarm.graph import Node
10-
from swarm.environment import GoogleSearchEngine, SearchAPIEngine
12+
from swarm.environment import GoogleSearchEngine, SearchAPIEngine, BingSearchEngine
1113
from swarm.utils.log import logger, swarmlog
1214
from swarm.utils.globals import Cost
1315
from swarm.environment.prompt.prompt_set_registry import PromptSetRegistry
1416
from swarm.llm import LLMRegistry
1517

16-
#searcher = GoogleSearchEngine()
17-
searcher = SearchAPIEngine()
18-
19-
2018
class WebSearch(Node):
2119
def __init__(self,
2220
domain: str,
@@ -29,10 +27,20 @@ def __init__(self,
2927
self.prompt_set = PromptSetRegistry.get(domain)
3028
self.role = self.prompt_set.get_role()
3129
self.constraint = self.prompt_set.get_constraint()
30+
self.searcher =self._get_searcher()
3231

3332
@property
3433
def node_name(self):
3534
return self.__class__.__name__
35+
36+
def _get_searcher(self):
37+
load_dotenv()
38+
if os.getenv("BING_API_KEY"):
39+
return BingSearchEngine()
40+
if os.getenv("SEARCHAPI_API_KEY"):
41+
return SearchAPIEngine()
42+
if os.getenv("GOOGLE_API_KEY"):
43+
return GoogleSearchEngine()
3644

3745
async def _execute(self, inputs: List[Any] = [], max_keywords: int = 5, **kwargs):
3846

@@ -78,6 +86,6 @@ async def _execute(self, inputs: List[Any] = [], max_keywords: int = 5, **kwargs
7886
return outputs
7987

8088
def web_search(self, query):
81-
return searcher.search(query)
89+
return self.searcher.search(query)
8290

8391

swarm/environment/tools/search/search.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,27 @@
22
# -*- coding: utf-8 -*-
33

44
import os
5-
from dotenv import load_dotenv
65
from googleapiclient.discovery import build
76
import requests
87
import ast
9-
load_dotenv()
108

9+
class BingSearchEngine():
10+
def __init__(self) -> None:
11+
self.api_key = os.getenv("BING_API_KEY")
12+
self.endpoint = "https://api.bing.microsoft.com/v7.0/search"
13+
self.headers = {"Ocp-Apim-Subscription-Key": self.api_key}
14+
15+
def search(self, query: str, num: int = 3):
16+
try:
17+
params = {"q": query, "count": num}
18+
res = requests.get(self.endpoint, headers=self.headers, params=params)
19+
res = res.json()
20+
return '\n'.join([item['snippet'] for item in res['webPages']['value']])
21+
except:
22+
return 'Cannot get search results from Bing API'
1123

1224
class GoogleSearchEngine():
1325
def __init__(self) -> None:
14-
load_dotenv()
1526
self.api_key = os.getenv("GOOGLE_API_KEY")
1627
self.cse_id = os.getenv("GOOGLE_CSE_ID")
1728
self.service = build("customsearch", "v1", developerKey=self.api_key)
@@ -21,8 +32,7 @@ def search(self, query: str, num: int = 3):
2132
res = self.service.cse().list(q=query, cx=self.cse_id, num=num).execute()
2233
return '\n'.join([item['snippet'] for item in res['items']])
2334
except:
24-
return ''
25-
35+
return 'Cannot get search results from Google API'
2636

2737
class SearchAPIEngine():
2838

@@ -45,7 +55,7 @@ def search(self, query: str, item_num: int = 3):
4555
if 'organic_results' in response.keys() and len(response['organic_results']) > 0:
4656

4757
return '\n'.join([res['snippet'] for res in response['organic_results'][:item_num]])
48-
return ''
58+
return 'Cannot get search results from SearchAPI'
4959

5060

5161

0 commit comments

Comments
 (0)