Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: Add bocha search in search toolkit (#1804)

hp107cd890ebea
diff --git a/.env b/.env
index a2f95a9af..e9f79f382 100644
--- a/.env
+++ b/.env
@@ -99,3 +99,6 @@
# OpenBB Platform API (https://my.openbb.co/app/credentials)
# OPENBB_TOKEN="Fill your API key here"
+
+# Bocha Platform API(https://open.bochaai.com)
+# BOCHA_API_KEY="Fill your API key here"
\ No newline at end of file
diff --git a/camel/toolkits/search_toolkit.py b/camel/toolkits/search_toolkit.py
index 037558d8f..968f74dcf 100644
--- a/camel/toolkits/search_toolkit.py
+++ b/camel/toolkits/search_toolkit.py
@@ -704,6 +704,68 @@ class SearchToolkit(BaseToolkit):
except Exception as e:
return [{"error": f"An unexpected error occurred: {e!s}"}]
+ @api_keys_required([(None, 'BOCHA_API_KEY')])
+ def search_bocha(
+ self,
+ query: str,
+ freshness: str = "noLimit",
+ summary: bool = False,
+ count: int = 10,
+ page: int = 1,
+ ) -> Dict[str, Any]:
+ r"""Query the Bocha AI search API and return search results.
+
+ Args:
+ query (str): The search query.
+ freshness (str): Time frame filter for search results. Default
+ is "noLimit". Options include:
+ - 'noLimit': no limit (default).
+ - 'oneDay': past day.
+ - 'oneWeek': past week.
+ - 'oneMonth': past month.
+ - 'oneYear': past year.
+ summary (bool): Whether to include text summaries in results.
+ Default is False.
+ count (int): Number of results to return (1-50). Default is 10.
+ page (int): Page number of results. Default is 1.
+
+ Returns:
+ Dict[str, Any]: A dictionary containing search results, including
+ web pages, images, and videos if available. The structure follows
+ the Bocha AI search API response format.
+ """
+ import json
+
+ BOCHA_API_KEY = os.getenv("BOCHA_API_KEY")
+
+ url = "https://api.bochaai.com/v1/web-search"
+ headers = {
+ "Authorization": f"Bearer {BOCHA_API_KEY}",
+ "Content-Type": "application/json",
+ }
+
+ payload = json.dumps(
+ {
+ "query": query,
+ "freshness": freshness,
+ "summary": summary,
+ "count": count,
+ "page": page,
+ }
+ )
+ try:
+ response = requests.post(url, headers=headers, data=payload)
+ if response.status_code != 200:
+ return {
+ "error": (
+ f"Bocha API failed with {response.status_code}: "
+ f"{response.text}"
+ )
+ }
+ return response.json()["data"]
+ except requests.exceptions.RequestException as e:
+ return {"error": f"Bocha AI search failed: {e!s}"}
+
def get_tools(self) -> List[FunctionTool]:
r"""Returns a list of FunctionTool objects representing the
functions in the toolkit.
@@ -720,4 +782,5 @@ class SearchToolkit(BaseToolkit):
FunctionTool(self.query_wolfram_alpha),
FunctionTool(self.tavily_search),
FunctionTool(self.search_brave),
+ FunctionTool(self.search_bocha),
]
diff --git a/examples/toolkits/search_toolkit.py b/examples/toolkits/search_toolkit.py
index 2d29a830c..31e803785 100644
--- a/examples/toolkits/search_toolkit.py
+++ b/examples/toolkits/search_toolkit.py
@@ -213,3 +213,33 @@ Goeppert-Mayer (1963) 3. Donna Strickland (2018) 4. (4th winner not mentioned
in the provided data) 5. (5th winner not mentioned in the provided data). Less
than 5 women have won the Nobel Prize in Physics out of 225 total laureates.'}
"""
+
+search_bocha_response = SearchToolkit().search_bocha(
+ query="阿里巴巴2024年的esg报告",
+ freshness="noLimit",
+ summary=False,
+ count=10,
+)
+print(search_bocha_response)
+
+"""
+{"_type":"SearchResponse","queryContext":{"originalQuery":"阿里巴巴2024年的esg报
+告"},"webPages":{"webSearchUrl":"","totalEstimatedMatches":8912791,"value":[
+{"id":None,"name":"阿里巴巴发布2024年ESG报告持续推进减碳与数字化普惠","url":"ht
+tps://www.alibabagroup.com/document-1752073403914780672","displayUrl":"htt
+ps://www.alibabagroup.com/document-1752073403914780672","snippet":"阿里巴巴
+集团发布《2024财年环境、社会和治理(ESG)报告》(下称"报告"),详细分享过去一年在ESG各方面取
+得的进展。报告显示,阿里巴巴扎实推进减碳举措,全集团自身运营净碳排放和价值链碳...","siteName"
+:"www.alibabagroup.com","siteIcon":"https://th.bochaai.com/favicon?domain_url=
+https://www.alibabagroup.com/document-1752073403914780672","dateLastCrawled":
+"2024-07-22T00:00:00Z","cachedPageUrl":None,"language":None,"isFamilyFriendly"
+:None,"isNavigational":None},],"someResultsRemoved":true},"images":{"id":None,
+"readLink":None,"webSearchUrl":None,"value":[{"webSearchUrl":None,"name":None,
+"thumbnailUrl":"http://q7.itc.cn/q_70/images01/20240726/ee26d6fa8658472d8b4c5
+e7236b1640a.png","datePublished":None,"contentUrl":"http://q7.itc.cn/q_70/im
+ages01/20240726/ee26d6fa8658472d8b4c5e7236b1640a.png","hostPageUrl":"https://
+m.sohu.com/a/796245119_121713887/?pvid=000115_3w_a","contentSize":None,"enco
+dingFormat":None,"hostPageDisplayUrl":"https://m.sohu.com/a/796245119_121713887
+/?pvid=000115_3w_a","width":1285,"height":722,"thumbnail":None}],"isFamilyFrien
+dly":None},"videos":None}
+"""
diff --git a/test/toolkits/test_search_functions.py b/test/toolkits/test_search_functions.py
index 12c746b0d..803c5850d 100644
--- a/test/toolkits/test_search_functions.py
+++ b/test/toolkits/test_search_functions.py
@@ -402,3 +402,65 @@ def test_search_linkup_error(search_toolkit):
result = search_toolkit.search_linkup(query="test query")
assert result == {"error": "An unexpected error occurred: Test error"}
+
+
+def test_search_bocha_success(search_toolkit):
+ """Test successful Bocha AI search with basic parameters."""
+ import json
+
+ mock_response = {
+ "code": 200,
+ "data": {
+ "_type": "SearchResponse",
+ "queryContext": {"originalQuery": "test_query"},
+ "webPages": {
+ "webSearchUrl": "",
+ "value": [],
+ },
+ "images": {},
+ "videos": {},
+ },
+ }
+ with patch('requests.post') as mock_post:
+ mock_post.return_value.json.return_value = mock_response
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.text = "OK"
+ mock_post.return_value.raise_for_status = lambda: None
+
+ with patch.dict(os.environ, {'BOCHA_API_KEY': 'test_key'}):
+ result = search_toolkit.search_bocha(
+ query="test query",
+ )
+
+ assert result == mock_response["data"]
+
+ mock_post.assert_called_once()
+ args, kwargs = mock_post.call_args
+ assert kwargs['headers'] == {
+ "Content-Type": "application/json",
+ "Authorization": "Bearer test_key",
+ }
+
+ assert kwargs['data'] == json.dumps(
+ {
+ "query": "test query",
+ "freshness": "noLimit",
+ "summary": False,
+ "count": 10,
+ "page": 1,
+ }
+ )
+
+
+def test_search_bocha_error(search_toolkit):
+ """Test error handling in Bocha AI search."""
+ with patch('requests.post') as mock_post:
+ mock_post.side_effect = requests.exceptions.RequestException(
+ "Connection error"
+ )
+
+ with patch.dict(os.environ, {'BOCHA_API_KEY': 'test_key'}):
+ result = search_toolkit.search_bocha(query="test query")
+
+ assert "error" in result
+ assert "Connection error" in result["error"]