Skip to content

Building AI agents, atomically

fix(bocha_search): correct BaseTool types, safe dict access, snippet type; update README and tests

Jintao Wei677e1ad81732
diff --git a/atomic-forge/tools/bocha_search/README.md b/atomic-forge/tools/bocha_search/README.md
index 057ce5d..31a612a 100644
--- a/atomic-forge/tools/bocha_search/README.md
+++ b/atomic-forge/tools/bocha_search/README.md
@@ -7,7 +7,7 @@ The BoCha Search Tool is a powerful utility within the Atomic Agents ecosystem t
- Python 3.9 or later
- atomic-agents (See [here](/README.md) for installation instructions)
- pydantic
-- requests
+- aiohttp
## Installation
You can install the tool using any of the following options:
@@ -19,15 +19,15 @@ You can install the tool using any of the following options:
### Parameters
-- `api_url` (str): The api key of the BoCha user.
-- `max_results` (int, optional): The maximum number of search results to return.
+- `api_key` (str): The api key of the BoCha user.
+- `count` (int, optional): The maximum number of search results to return.
### Example
```python
config = BoChaSearchToolConfig(
api_key="my-api-key",
- max_results=5
+ count=5
)
```
@@ -53,14 +53,14 @@ Here's an example of how to use the BoCha Search Tool:
```python
import os
-from tool.bocha_search import BoChaTool, BoChaSearchToolConfig
+from tool.bocha_search import BoChaSearchTool, BoChaSearchToolConfig, BoChaSearchToolInputSchema
# Initialize the tool with your BoCha instance URL
-config = BoChaSearchToolConfig(api_key=os.getenv("BOCHA_API_KEY"), max_results=5)
-search_tool = BoChaTool(config=config)
+config = BoChaSearchToolConfig(api_key=os.getenv("BOCHA_API_KEY"), count=5)
+search_tool = BoChaSearchTool(config=config)
# Define input data
-input_data = BoChaTool.input_schema(
+input_data = BoChaSearchToolInputSchema(
queries=["Python programming", "Machine learning"],
)
diff --git a/atomic-forge/tools/bocha_search/pyproject.toml b/atomic-forge/tools/bocha_search/pyproject.toml
index 75e4d6e..2fb992a 100644
--- a/atomic-forge/tools/bocha_search/pyproject.toml
+++ b/atomic-forge/tools/bocha_search/pyproject.toml
@@ -13,7 +13,7 @@ readme = "README.md"
authors = [
{ name = "Jintao Wei", email = "[email protected]" }
]
-requires-python = ">=3.12"
+requires-python = ">=3.9"
dependencies = [
"atomic-agents",
"pydantic>=2.10.3,<3.0.0",
diff --git a/atomic-forge/tools/bocha_search/requirements.txt b/atomic-forge/tools/bocha_search/requirements.txt
index e7586f3..93768d3 100644
--- a/atomic-forge/tools/bocha_search/requirements.txt
+++ b/atomic-forge/tools/bocha_search/requirements.txt
@@ -1,4 +1,3 @@
atomic-agents>=1.0.0,<2.0.0
pydantic>=2.8.2,<3.0.0
-sympy>=1.12,<2.0.0
aiohttp>=3.9.0,<4.0.0
\ No newline at end of file
diff --git a/atomic-forge/tools/bocha_search/tests/test_bocha_seach.py b/atomic-forge/tools/bocha_search/tests/test_bocha_search.py
similarity index 58%
rename from atomic-forge/tools/bocha_search/tests/test_bocha_seach.py
rename to atomic-forge/tools/bocha_search/tests/test_bocha_search.py
index 8327e08..ded7405 100644
--- a/atomic-forge/tools/bocha_search/tests/test_bocha_seach.py
+++ b/atomic-forge/tools/bocha_search/tests/test_bocha_search.py
@@ -3,6 +3,7 @@ import sys
import pytest
from unittest.mock import patch, AsyncMock, MagicMock
from types import SimpleNamespace
+import asyncio
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
@@ -11,7 +12,6 @@ from tool.bocha_search import ( # noqa: E402
BoChaSearchToolInputSchema,
BoChaSearchToolConfig,
BoChaSearchToolOutputSchema,
- # BoChaSearchResultItemSchema,
)
@@ -95,8 +95,8 @@ def test_bocha_search_tool_sync_run(mock_aiohttp_session):
@pytest.mark.asyncio
-async def test_bocha_search_tool_max_results(mock_aiohttp_session):
- """Test max_results parameter"""
+async def test_bocha_search_tool_count(mock_aiohttp_session):
+ """Test count parameter"""
mock_api_key = "KEY"
mock_query = "max results query"
@@ -119,7 +119,7 @@ async def test_bocha_search_tool_max_results(mock_aiohttp_session):
input_schema = BoChaSearchToolInputSchema(queries=[mock_query])
# Test limiting to 5 results
- result = await tool.run_async(input_schema, max_results=5)
+ result = await tool.run_async(input_schema, count=5)
assert len(result.results) == 5
# Test default count from config
@@ -148,8 +148,8 @@ async def test_bocha_search_tool_no_results(mock_aiohttp_session):
@pytest.mark.asyncio
-async def test_bocha_search_tool_http_error(mock_aiohttp_session):
- """Test that HTTP errors raise an exception"""
+async def test_bocha_search_tool_http_error_handled(mock_aiohttp_session, caplog):
+ """Test that HTTP errors are logged and skipped, not raised"""
mock_api_key = "KEY"
mock_query = "error query"
@@ -162,10 +162,92 @@ async def test_bocha_search_tool_http_error(mock_aiohttp_session):
tool = BoChaSearchTool(BoChaSearchToolConfig(api_key=mock_api_key))
input_schema = BoChaSearchToolInputSchema(queries=[mock_query])
- with pytest.raises(Exception) as excinfo:
- await tool.run_async(input_schema)
+ with caplog.at_level("WARNING"):
+ result = await tool.run_async(input_schema)
- assert "Failed to fetch search results" in str(excinfo.value)
+ # The result should be empty because the query failed
+ assert len(result.results) == 0
+ # Check that a warning was logged
+ assert any("Query 'error query' failed" in rec.message for rec in caplog.records)
+
+
+async def test_bocha_search_tool_empty_queries(mock_aiohttp_session):
+ """Test behavior when queries=[]"""
+ mock_api_key = "KEY"
+ tool = BoChaSearchTool(BoChaSearchToolConfig(api_key=mock_api_key))
+ input_schema = BoChaSearchToolInputSchema(queries=[])
+ result = await tool.run_async(input_schema)
+ assert len(result.results) == 0
+
+
+async def test_bocha_search_tool_concurrent_queries(mock_aiohttp_session):
+ """Test multiple concurrent queries"""
+ mock_api_key = "KEY"
+ tool = BoChaSearchTool(BoChaSearchToolConfig(api_key=mock_api_key))
+ queries = ["query1", "query2", "query3"]
+ input_schemas = [BoChaSearchToolInputSchema(queries=[q]) for q in queries]
+
+ results = await asyncio.gather(*(tool.run_async(schema) for schema in input_schemas))
+ assert all(len(r.results) == 1 for r in results)
+ assert [r.results[0].name for r in results] == ["Mock Title"] * 3
+
+
+async def test_bocha_search_tool_config_params_real_case_cn(mock_aiohttp_session):
+ """Test that config params freshness/include/exclude are included in request payload with Chinese websites"""
+ mock_api_key = os.getenv("BOCHA_API_KEY")
+
+ # Tool configuration with domestic websites
+ tool = BoChaSearchTool(
+ BoChaSearchToolConfig(
+ api_key=mock_api_key,
+ freshness="oneMonth", # Search results from the past month
+ include="baidu.com|sina.com.cn", # Only include these domestic websites
+ exclude="ads.example.com|spam.cn", # Exclude ad/spam websites
+ )
+ )
+
+ # Use a realistic Chinese query
+ input_schema = BoChaSearchToolInputSchema(queries=["人工智能发展趋势"])
+
+ await tool.run_async(input_schema)
+
+ # Retrieve the payload sent in the request
+ payload_sent = mock_aiohttp_session.post.call_args[1]["json"]
+
+ # Assert that the configuration parameters are correctly included
+ assert payload_sent["freshness"] == "oneMonth"
+ assert "baidu.com" in payload_sent["include"]
+ assert "sina.com.cn" in payload_sent["include"]
+ assert "ads.example.com" in payload_sent["exclude"]
+ assert "spam.cn" in payload_sent["exclude"]
+
+ # Assert that the query keyword is included in the payload
+ assert "人工智能发展趋势" in payload_sent["query"] or "queries" in payload_sent
+
+
+async def test_bocha_search_tool_malformed_response(mock_aiohttp_session):
+ """Test API response missing 'data' or 'webPages' keys"""
+ mock_api_key = "KEY"
+ tool = BoChaSearchTool(BoChaSearchToolConfig(api_key=mock_api_key))
+ input_schema = BoChaSearchToolInputSchema(queries=["test query"])
+
+ # response completely missing 'data'
+ mock_response_data = {"unexpected": "structure"}
+ mock_aiohttp_session.post.return_value.__aenter__.return_value.json.return_value = mock_response_data
+
+ result = await tool.run_async(input_schema)
+ assert len(result.results) == 0
+
+ # response missing 'webPages'
+ mock_response_data2 = {"data": {"otherKey": []}}
+ mock_aiohttp_session.post.return_value.__aenter__.return_value.json.return_value = mock_response_data2
+
+ result2 = await tool.run_async(input_schema)
+ assert len(result2.results) == 0
if __name__ == "__main__":
diff --git a/atomic-forge/tools/bocha_search/tool/bocha_search.py b/atomic-forge/tools/bocha_search/tool/bocha_search.py
index 3b2e186..8b7e762 100644
--- a/atomic-forge/tools/bocha_search/tool/bocha_search.py
+++ b/atomic-forge/tools/bocha_search/tool/bocha_search.py
@@ -1,8 +1,8 @@
import os
-from typing import List, Optional
+from typing import List, Optional, Literal
import asyncio
from concurrent.futures import ThreadPoolExecutor
-
+import logging
import aiohttp
from pydantic import Field
@@ -29,7 +29,7 @@ class BoChaSearchResultItemSchema(BaseIOSchema):
name: str = Field(..., description="The title of the search result")
url: str = Field(..., description="The URL of the search result")
- snippet: str = Field(None, description="The content snippet of the search result")
+ snippet: Optional[str] = Field(None, description="The content snippet of the search result")
query: Optional[str] = Field(None, description="The query used to obtain this search result")
@@ -45,13 +45,15 @@ class BoChaSearchToolOutputSchema(BaseIOSchema):
class BoChaSearchToolConfig(BaseToolConfig):
api_key: str = ""
- freshness: str = "noLimit"
+ freshness: Literal["noLimit", "oneDay", "oneWeek", "oneMonth", "oneYear", "YYYY-MM-DD..YYYY-MM-DD", "YYYY-MM-DD"] = (
+ "noLimit"
+ )
include: Optional[str] = None
exclude: Optional[str] = None
count: int = 10
-class BoChaSearchTool(BaseTool[BoChaSearchResultItemSchema, BoChaSearchToolOutputSchema]):
+class BoChaSearchTool(BaseTool[BoChaSearchToolInputSchema, BoChaSearchToolOutputSchema]):
"""
Tool for performing searches using the BoCha search API.
@@ -71,7 +73,7 @@ class BoChaSearchTool(BaseTool[BoChaSearchResultItemSchema, BoChaSearchToolOutpu
Configuration for the tool, including API key, max results, and optional title and description overrides.
"""
super().__init__(config)
- self.api_key = config.api_key or os.getenv("BoCha_API_KEY", "")
+ self.api_key = config.api_key or os.getenv("BOCHA_API_KEY", "")
self.count = config.count
self.freshness = config.freshness
self.include = config.include
@@ -87,9 +89,11 @@ class BoChaSearchTool(BaseTool[BoChaSearchResultItemSchema, BoChaSearchToolOutpu
"query": query,
"count": self.count,
"freshness": self.freshness,
- "include": self.include,
- "exclude": self.exclude,
}
+ if self.include is not None:
+ json_data["include"] = self.include
+ if self.exclude is not None:
+ json_data["exclude"] = self.exclude
async with session.post("https://api.bochaai.com/v1/web-search", headers=headers, json=json_data) as response:
if response.status != 200:
@@ -99,7 +103,10 @@ class BoChaSearchTool(BaseTool[BoChaSearchResultItemSchema, BoChaSearchToolOutpu
)
data = await response.json()
- results = data["data"]["webPages"]["value"]
+ results = []
+ webpages = data.get("data", {}).get("webPages", {})
+ if isinstance(webpages, dict):
+ results = webpages.get("value", [])
# Add query information to each result
for result in results:
@@ -107,17 +114,19 @@ class BoChaSearchTool(BaseTool[BoChaSearchResultItemSchema, BoChaSearchToolOutpu
return {"results": results}
- async def run_async(
- self, params: BoChaSearchToolInputSchema, max_results: Optional[int] = None
- ) -> BoChaSearchToolOutputSchema:
+ async def run_async(self, params: BoChaSearchToolInputSchema, count: Optional[int] = None) -> BoChaSearchToolOutputSchema:
async with aiohttp.ClientSession() as session:
# Fetch results for all queries
tasks = [self._fetch_search_results(session, query) for query in params.queries]
- raw_responses = await asyncio.gather(*tasks)
+ raw_responses = await asyncio.gather(*tasks, return_exceptions=True)
# Process results for each query
processed_results = []
- for response in raw_responses:
+ for query, response in zip(params.queries, raw_responses):
+ if isinstance(response, Exception):
+ # Log the failure, skip or handle as needed
+ logging.warning(f"Query '{query}' failed: {response}")
+ continue
query_results = response["results"]
query_processed = []
for result in query_results:
@@ -134,12 +143,12 @@ class BoChaSearchTool(BaseTool[BoChaSearchResultItemSchema, BoChaSearchToolOutpu
print(f"Skipping result due to missing keys: {result}")
# Limit results per query
- query_processed = query_processed[: max_results or self.count]
+ query_processed = query_processed[: count or self.count]
processed_results.extend(query_processed)
return BoChaSearchToolOutputSchema(results=processed_results)
- def run(self, params: BoChaSearchToolInputSchema, max_results: Optional[int] = None) -> BoChaSearchToolOutputSchema:
+ def run(self, params: BoChaSearchToolInputSchema, count: Optional[int] = None) -> BoChaSearchToolOutputSchema:
"""
Runs the BoChaTool synchronously with the given parameters.
@@ -147,7 +156,7 @@ class BoChaSearchTool(BaseTool[BoChaSearchResultItemSchema, BoChaSearchToolOutpu
Args:
params (BoChaSearchToolInputSchema): The input parameters for the tool, adhering to the input schema.
- max_results (Optional[int]): The maximum number of search results to return.
+ count (Optional[int]): The maximum number of search results to return.
Returns:
BoChaSearchToolOutputSchema: The output of the tool, adhering to the output schema.
@@ -161,7 +170,7 @@ class BoChaSearchTool(BaseTool[BoChaSearchResultItemSchema, BoChaSearchToolOutpu
asyncio.run,
self.run_async(
params,
- max_results,
+ count,
),
).result()
@@ -177,7 +186,7 @@ if __name__ == "__main__":
load_dotenv()
rich_console = Console()
- search_tool_instance = BoChaSearchTool(config=BoChaSearchToolConfig(api_key="sk-**************", max_results=2))
+ search_tool_instance = BoChaSearchTool(config=BoChaSearchToolConfig(api_key=os.getenv("BOCHA_API_KEY"), count=2))
# search_input = BoChaSearchToolInputSchema(queries=["北京天气怎么样?", "天津天气怎么样?", "杭州天气怎么样?"])
search_input = BoChaSearchToolInputSchema(queries=["Python programming", "Machine learning"])
diff --git a/pyproject.toml b/pyproject.toml
index 737e94c..e4f8835 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "atomic-agents"
-version = "2.6.0"
+version = "2.7.0"
description = "A versatile framework for creating and managing intelligent agents."
readme = "README.md"
license = "MIT"
diff --git a/uv.lock b/uv.lock
index 0651c51..27774d2 100644
--- a/uv.lock
+++ b/uv.lock
@@ -11,6 +11,7 @@ members = [
"atomic-agents",
"basic-multimodal",
"basic-pdf-analysis",
+ "bocha-search",
"calculator",
"deep-research",
"dspy-integration",
@@ -24,7 +25,6 @@ members = [
"rag-chatbot",
"searxng-search",
"tavily-search",
- "bocha_search",
"web-search-agent",
"webpage-scraper",
"youtube-summarizer",
@@ -193,7 +193,7 @@ wheels = [
[[package]]
name = "atomic-agents"
-version = "2.6.0"
+version = "2.7.0"
source = { editable = "." }
dependencies = [
{ name = "gitpython" },
@@ -444,6 +444,43 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/8d/a7/4b27c50537ebca8bec139b872861f9d2bf501c5ec51fcf897cb924d9e264/black-24.10.0-py3-none-any.whl", hash = "sha256:3bb2b7a1f7b685f85b11fed1ef10f8a9148bceb49853e47a294a3dd963c1dd7d", size = 206898, upload-time = "2024-10-07T19:20:48.317Z" },
]
+[[package]]
+name = "bocha-search"
+version = "1.0.0"
+source = { editable = "atomic-forge/tools/bocha_search" }
+dependencies = [
+ { name = "aiohttp" },
+ { name = "atomic-agents" },
+ { name = "pydantic" },
+]
+
+[package.dev-dependencies]
+dev = [
+ { name = "coverage" },
+ { name = "pytest" },
+ { name = "pytest-asyncio" },
+ { name = "pytest-cov" },
+ { name = "python-dotenv" },
+ { name = "rich" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "aiohttp", specifier = ">=3.9.0,<4.0.0" },
+ { name = "atomic-agents", editable = "." },
+ { name = "pydantic", specifier = ">=2.10.3,<3.0.0" },
+]
+
+[package.metadata.requires-dev]
+dev = [
+ { name = "coverage", specifier = ">=7.6.1,<8.0.0" },
+ { name = "pytest", specifier = ">=8.3.3,<9.0.0" },
+ { name = "pytest-asyncio", specifier = ">=0.23.5,<1.0.0" },
+ { name = "pytest-cov", specifier = ">=5.0.0,<6.0.0" },
+ { name = "python-dotenv", specifier = ">=1.0.0,<2.0.0" },
+ { name = "rich", specifier = ">=13.7.0,<14.0.0" },
+]
+
[[package]]
name = "build"
version = "1.3.0"
@@ -4009,43 +4046,6 @@ dev = [
{ name = "rich", specifier = ">=13.7.0,<14.0.0" },
]
-[[package]]
-name = "bocha-search"
-version = "1.0.0"
-source = { editable = "atomic-forge/tools/bocha_search" }
-dependencies = [
- { name = "aiohttp" },
- { name = "atomic-agents" },
- { name = "pydantic" },
-]
-
-[package.dev-dependencies]
-dev = [
- { name = "coverage" },
- { name = "pytest" },
- { name = "pytest-asyncio" },
- { name = "pytest-cov" },
- { name = "python-dotenv" },
- { name = "rich" },
-]
-
-[package.metadata]
-requires-dist = [
- { name = "aiohttp", specifier = ">=3.9.0,<4.0.0" },
- { name = "atomic-agents", editable = "." },
- { name = "pydantic", specifier = ">=2.10.3,<3.0.0" },
-]
-
-[package.metadata.requires-dev]
-dev = [
- { name = "coverage", specifier = ">=7.6.1,<8.0.0" },
- { name = "pytest", specifier = ">=8.3.3,<9.0.0" },
- { name = "pytest-asyncio", specifier = ">=0.23.5,<1.0.0" },
- { name = "pytest-cov", specifier = ">=5.0.0,<6.0.0" },
- { name = "python-dotenv", specifier = ">=1.0.0,<2.0.0" },
- { name = "rich", specifier = ">=13.7.0,<14.0.0" },
-]
-
[[package]]
name = "tenacity"
version = "9.1.2"