Skip to content

Commit 8102896

Browse files
denglianghao.dlhtuhahaha
authored andcommitted
add web search tool with serper api
1 parent 9331efb commit 8102896

File tree

5 files changed

+58
-3
lines changed

5 files changed

+58
-3
lines changed

‎examples/assistant_qwq.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ def init_agent_service():
1919

2020
tools = [
2121
'image_gen',
22+
# 'web_search', # Apply for an apikey here (https://serper.dev) and set it as an environment variable by `export SERPER_API_KEY=xxxxxx`
2223
]
2324
bot = Assistant(
2425
llm=llm_cfg,

‎qwen_agent/agents/fncall_agent.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ def __init__(self,
4040
description=description)
4141

4242
if not hasattr(self, 'mem'):
43-
# Default to use Memory to manage files
4443
# Default to use Memory to manage files
4544
if 'qwq' in self.llm.model or 'qvq' in self.llm.model:
4645
mem_llm = {

‎qwen_agent/tools/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from .simple_doc_parser import SimpleDocParser
1111
from .storage import Storage
1212
from .web_extractor import WebExtractor
13+
from .web_search import WebSearch
1314

1415
__all__ = [
1516
'BaseTool',
@@ -28,4 +29,5 @@
2829
'FrontPageSearch',
2930
'ExtractDocVocabulary',
3031
'PythonExecutor',
32+
'WebSearch',
3133
]

‎qwen_agent/tools/base.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,11 +150,11 @@ def _verify_json_format_args(self, params: Union[str, dict], strict_json: bool =
150150
@property
151151
def function(self) -> dict: # Bad naming. It should be `function_info`.
152152
return {
153-
'name_for_human': self.name_for_human,
153+
# 'name_for_human': self.name_for_human,
154154
'name': self.name,
155155
'description': self.description,
156156
'parameters': self.parameters,
157-
'args_format': self.args_format
157+
# 'args_format': self.args_format
158158
}
159159

160160
@property

‎qwen_agent/tools/web_search.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import os
2+
from typing import Any, List, Union
3+
4+
import requests
5+
6+
from qwen_agent.tools.base import BaseTool, register_tool
7+
8+
SERPER_API_KEY = os.getenv('SERPER_API_KEY', '')
9+
SERPER_URL = os.getenv('SERPER_URL', 'https://google.serper.dev/search')
10+
11+
12+
@register_tool('web_search', allow_overwrite=True)
13+
class WebSearch(BaseTool):
14+
name = 'web_search'
15+
description = 'Search for information from the internet.'
16+
parameters = {
17+
'type': 'object',
18+
'properties': {
19+
'query': {
20+
'type': 'string',
21+
}
22+
},
23+
'required': ['query'],
24+
}
25+
26+
def call(self, params: Union[str, dict], **kwargs) -> str:
27+
params = self._verify_json_format_args(params)
28+
query = params['query']
29+
30+
search_results = self.search(query)
31+
formatted_results = self._format_results(search_results)
32+
return formatted_results
33+
34+
@staticmethod
35+
def search(query: str) -> List[Any]:
36+
if not SERPER_API_KEY:
37+
raise ValueError(
38+
'SERPER_API_KEY is None! Please Apply for an apikey from https://serper.dev and set it as an environment variable by `export SERPER_API_KEY=xxxxxx`'
39+
)
40+
headers = {'Content-Type': 'application/json', 'X-API-KEY': SERPER_API_KEY}
41+
payload = {'q': query}
42+
response = requests.post(SERPER_URL, json=payload, headers=headers)
43+
response.raise_for_status()
44+
45+
return response.json()['organic']
46+
47+
@staticmethod
48+
def _format_results(search_results: List[Any]) -> str:
49+
content = '```\n{}\n```'.format('\n\n'.join([
50+
f"[{i}]\"{doc['title']}\n{doc.get('snippet', '')}\"{doc.get('date', '')}"
51+
for i, doc in enumerate(search_results, 1)
52+
]))
53+
return content

0 commit comments

Comments
 (0)