Building AI agents, atomically
Add Serply Search tool to the Atomic Forge
serply05e8c9764709
diff --git a/AGENTS.md b/AGENTS.mdindex d9e4b7c..ac320a4 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -103,6 +103,7 @@ Each example is self-contained and demonstrates specific patterns and capabiliti- `hackernews_search/` - Hacker News search via the free Algolia API- `pdf_reader/` - PDF text + metadata extraction (local file or URL, page-range support)- `searxng_search/` - Privacy-focused search integration+- `serply_search/` - Google web, news, and scholar search via the Serply API- `tavily_search/` - Tavily API search tool- `weather/` - Current conditions and daily/hourly forecast via Open-Meteo (no key)- `webpage_scraper/` - Web scraping capabilitiesdiff --git a/README.md b/README.mdindex 242f846..270f558 100644--- a/README.md+++ b/README.md@@ -352,6 +352,7 @@ Atomic Forge is a collection of tools that can be used with Atomic Agents to ext- Hacker News Search- PDF Reader- SearXNG Search+- Serply Search- Tavily Search- Webpage Scraper- Weatherdiff --git a/atomic-forge/README.md b/atomic-forge/README.mdindex bf05ca5..d34c5a0 100644--- a/atomic-forge/README.md+++ b/atomic-forge/README.md@@ -21,6 +21,7 @@ The Atomic Forge project includes the following tools:- [Hacker News Search](/atomic-forge/tools/hackernews_search/README.md) — search HN stories, comments, Show HN, Ask HN via the free Algolia API.- [PDF Reader](/atomic-forge/tools/pdf_reader/README.md) — extract text and metadata from a local or remote PDF, with page-range filtering.- [SearXNG Search](/atomic-forge/tools/searxng_search/README.md)+- [Serply Search](/atomic-forge/tools/serply_search/README.md)- [Tavily Search](/atomic-forge/tools/tavily_search/README.md)- [Webpage Scraper](/atomic-forge/tools/webpage_scraper/README.md)- [Weather](/atomic-forge/tools/weather/README.md) — current conditions and forecast via the free Open-Meteo API.diff --git a/atomic-forge/tools/serply_search/.coveragerc b/atomic-forge/tools/serply_search/.coveragercnew file mode 100644index 0000000..c45136e--- /dev/null+++ b/atomic-forge/tools/serply_search/.coveragerc@@ -0,0 +1,8 @@+[run]+source = tool+omit = */tests/*++[report]+exclude_lines =+ if __name__ == "__main__":+show_missing = Truediff --git a/atomic-forge/tools/serply_search/README.md b/atomic-forge/tools/serply_search/README.mdnew file mode 100644index 0000000..a367969--- /dev/null+++ b/atomic-forge/tools/serply_search/README.md@@ -0,0 +1,59 @@+# Serply Search Tool++## Overview+Searches Google web results, Google News, or Google Scholar through the [Serply](https://serply.io) API and returns each result's title, URL, and snippet, plus the publish date and source for news and the authors and citation count for papers. Requires a Serply API key.++## Prerequisites and Dependencies+- Python 3.12 or later+- `atomic-agents`+- `pydantic`+- `aiohttp`+- A Serply API key from [serply.io](https://serply.io)++## Installation+1. Use the Atomic Assembler CLI: run `atomic` and pick `serply_search`.+2. Or copy the `tool/` folder directly into your project.++## Configuration+- `api_key` (str): Serply API key. Falls back to the `SERPLY_API_KEY` environment variable when empty.+- `base_url` (str): API base URL (default `https://api.serply.io/v1`).+- `hl` (str): interface language code, e.g. `en` (default `en`).+- `gl` (str): country code for the search, e.g. `us` (default `us`).+- `user_agent` (str): user agent sent with each request.+- `timeout` (float): HTTP timeout in seconds (default 30).++## Input & Output Structure++### Input Schema+- `queries` (list[str]): search queries to run.+- `search_type` (str): `search` (Google web), `news` (Google News), or `scholar` (Google Scholar). Default `search`.+- `max_results_per_query` (int): 1-100 (default 10).++### Output Schema+A list of `SerplySearchResultItem` items. Each has `query`, `title`, `url`, and optional `description`, `position` (web search), `published` and `source` (news), `authors` and `citations` (scholar).++## Usage++```python+from tool.serply_search import SerplySearchTool, SerplySearchToolConfig, SerplySearchToolInputSchema++tool = SerplySearchTool(config=SerplySearchToolConfig(api_key="your-serply-api-key"))++output = tool.run(SerplySearchToolInputSchema(+ queries=["retrieval augmented generation"],+ search_type="scholar",+ max_results_per_query=3,+))++for item in output.results:+ print(item.title, "-", item.url)+ print(item.authors, item.citations)+```++The request and response formats for each endpoint are documented at [serply.io/docs](https://serply.io/docs).++## Contributing+PRs welcome. See the main repo `CONTRIBUTING.md`.++## License+Same as the main Atomic Agents project.diff --git a/atomic-forge/tools/serply_search/pyproject.toml b/atomic-forge/tools/serply_search/pyproject.tomlnew file mode 100644index 0000000..51fd779--- /dev/null+++ b/atomic-forge/tools/serply_search/pyproject.toml@@ -0,0 +1,34 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["tool"]++[project]+name = "serply-search"+version = "1.0.0"+description = "Google web, news, and scholar search tool for Atomic Agents via the Serply API"+readme = "README.md"+authors = [+ { name = "Serply", email = "[email protected]" }+]+requires-python = ">=3.12"+dependencies = [+ "atomic-agents",+ "pydantic>=2.10.3,<3.0.0",+ "aiohttp>=3.9.0,<4.0.0",+]++[dependency-groups]+dev = [+ "coverage>=7.6.1,<8.0.0",+ "pytest>=8.3.3,<9.0.0",+ "pytest-asyncio>=0.23.5,<1.0.0",+ "pytest-cov>=5.0.0,<6.0.0",+ "python-dotenv>=1.0.0,<2.0.0",+ "rich>=13.7.0,<14.0.0",+]++[tool.uv.sources]+atomic-agents = { workspace = true }diff --git a/atomic-forge/tools/serply_search/requirements.txt b/atomic-forge/tools/serply_search/requirements.txtnew file mode 100644index 0000000..469c7e9--- /dev/null+++ b/atomic-forge/tools/serply_search/requirements.txt@@ -0,0 +1,3 @@+atomic-agents>=2.0.0,<3.0.0+pydantic>=2.10.3,<3.0.0+aiohttp>=3.9.0,<4.0.0diff --git a/atomic-forge/tools/serply_search/tests/test_serply_search.py b/atomic-forge/tools/serply_search/tests/test_serply_search.pynew file mode 100644index 0000000..1a3de14--- /dev/null+++ b/atomic-forge/tools/serply_search/tests/test_serply_search.py@@ -0,0 +1,203 @@+import os+import sys+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))++from tool.serply_search import ( # noqa: E402+ SerplySearchResultItem,+ SerplySearchTool,+ SerplySearchToolConfig,+ SerplySearchToolInputSchema,+ SerplySearchToolOutputSchema,+)+++SEARCH_HIT = {+ "title": "Welcome to Python.org",+ "description": "Python is a programming language that lets you work quickly.",+ "position": 1,+ "realPosition": 1,+ "result_type": "organic",+ "link": "https://www.python.org/",+}++NEWS_HIT = {+ "title": "Python 3.14 released - example.com",+ "link": "https://example.com/python-3-14",+ "published": "Wed, 10 Jun 2026 07:00:00 GMT",+ "summary": '<a href="https://example.com/python-3-14">Python 3.14 released</a>',+ "source": {"href": "https://example.com", "title": "example.com"},+}++SCHOLAR_HIT = {+ "title": "SciPy 1.0: fundamental algorithms for scientific computing in Python",+ "link": "https://example.com/scipy-1-0",+ "id": "W3003257820",+ "author": {"names": "Pauli Virtanen, Ralf Gommers"},+ "description": "SciPy is an open-source scientific computing library.",+ "extras": {"citations": {"count": 12345}},+}+++def _mock_session(status: int, payload: dict, reason: str = "OK") -> MagicMock:+ session = MagicMock()+ response = SimpleNamespace(status=status, reason=reason, json=AsyncMock(return_value=payload))+ session.get.return_value.__aenter__.return_value = response+ return session+++def tool():+ return SerplySearchTool(config=SerplySearchToolConfig(api_key="test-key", hl="de", gl="ch"))+++def test_to_item_search(tool):+ item = SerplySearchTool._to_item(SEARCH_HIT, "python")+ assert isinstance(item, SerplySearchResultItem)+ assert item.query == "python"+ assert item.title == "Welcome to Python.org"+ assert item.url == "https://www.python.org/"+ assert item.description.startswith("Python is a programming language")+ assert item.position == 1+ assert item.published is None+ assert item.authors is None+++def test_to_item_news(tool):+ """News entries carry a summary, a publish date, and a source dict."""+ item = SerplySearchTool._to_item(NEWS_HIT, "python")+ assert item.description.startswith("<a href=")+ assert item.published == "Wed, 10 Jun 2026 07:00:00 GMT"+ assert item.source == "example.com"+ assert item.position is None+++def test_to_item_scholar(tool):+ """Scholar articles carry authors and a citation count."""+ item = SerplySearchTool._to_item(SCHOLAR_HIT, "scipy")+ assert item.authors == "Pauli Virtanen, Ralf Gommers"+ assert item.citations == 12345+ assert item.description == "SciPy is an open-source scientific computing library."+++async def test_fetch_builds_request(tool):+ session = _mock_session(200, {"results": [SEARCH_HIT]})++ items = await tool._fetch(session, "python", "search", 5)++ assert len(items) == 1+ assert items[0].url == "https://www.python.org/"+ call_args = session.get.call_args+ assert call_args[0][0] == "https://api.serply.io/v1/search/"+ assert call_args[1]["params"] == {"q": "python", "num": "5", "hl": "de", "gl": "ch"}+++async def test_fetch_news_trims_to_max_results(tool):+ """The news endpoint ignores num, so the tool cuts the entries client side."""+ session = _mock_session(200, {"entries": [NEWS_HIT] * 5})++ items = await tool._fetch(session, "python", "news", 2)++ assert len(items) == 2+ assert session.get.call_args[0][0] == "https://api.serply.io/v1/news/"+++async def test_fetch_skips_hits_without_title_or_link(tool):+ hits = [SEARCH_HIT, {"title": "no link"}, {"link": "https://example.com/no-title"}]+ session = _mock_session(200, {"results": hits})++ items = await tool._fetch(session, "python", "search", 10)++ assert [item.url for item in items] == ["https://www.python.org/"]+++async def test_fetch_raises_on_http_error(tool):+ session = _mock_session(401, {}, reason="Unauthorized")++ with pytest.raises(Exception, match="Serply search failed for 'python': 401 Unauthorized"):+ await tool._fetch(session, "python", "search", 10)+++async def test_run_async_aggregates_results(tool):+ async def fake_fetch(self, session, query, search_type, max_results):+ return [SerplySearchTool._to_item(SEARCH_HIT, query), SerplySearchTool._to_item(SCHOLAR_HIT, query)]++ with patch.object(SerplySearchTool, "_fetch", fake_fetch):+ out = await tool.run_async(SerplySearchToolInputSchema(queries=["q1", "q2"]))++ assert isinstance(out, SerplySearchToolOutputSchema)+ assert len(out.results) == 4+ assert {r.query for r in out.results} == {"q1", "q2"}+++async def test_run_async_skips_failing_query(tool):+ async def fake_fetch(self, session, query, search_type, max_results):+ if query == "bad":+ raise Exception("rate limited")+ return [SerplySearchTool._to_item(SEARCH_HIT, query)]++ with patch.object(SerplySearchTool, "_fetch", fake_fetch):+ out = await tool.run_async(SerplySearchToolInputSchema(queries=["bad", "good"]))++ assert len(out.results) == 1+ assert out.results[0].query == "good"+++async def test_run_async_sends_api_key_header(tool):+ captured = {}++ class FakeSession:+ def __init__(self, headers=None, timeout=None):+ captured["headers"] = headers++ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return False++ async def fake_fetch(self, session, query, search_type, max_results):+ return []++ with patch("tool.serply_search.aiohttp.ClientSession", FakeSession), patch.object(SerplySearchTool, "_fetch", fake_fetch):+ await tool.run_async(SerplySearchToolInputSchema(queries=["q"]))++ assert captured["headers"]["X-Api-Key"] == "test-key"+ assert "User-Agent" in captured["headers"]+++async def test_run_async_requires_api_key(monkeypatch):+ monkeypatch.delenv("SERPLY_API_KEY", raising=False)+ tool = SerplySearchTool(config=SerplySearchToolConfig())++ with pytest.raises(ValueError, match="SERPLY_API_KEY"):+ await tool.run_async(SerplySearchToolInputSchema(queries=["q"]))+++def test_api_key_falls_back_to_environment(monkeypatch):+ monkeypatch.setenv("SERPLY_API_KEY", "env-key")+ tool = SerplySearchTool(config=SerplySearchToolConfig())+ assert tool.api_key == "env-key"+++def test_run_invokes_run_async(tool):+ sentinel = SerplySearchToolOutputSchema(results=[])+ with patch.object(SerplySearchTool, "run_async", AsyncMock(return_value=sentinel)):+ out = tool.run(SerplySearchToolInputSchema(queries=["x"]))+ assert out is sentinel+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/atomic-forge/tools/serply_search/tool/serply_search.py b/atomic-forge/tools/serply_search/tool/serply_search.pynew file mode 100644index 0000000..378205b--- /dev/null+++ b/atomic-forge/tools/serply_search/tool/serply_search.py@@ -0,0 +1,192 @@+import asyncio+import logging+import os+from concurrent.futures import ThreadPoolExecutor+from typing import List, Literal, Optional++import aiohttp+from pydantic import Field++from atomic_agents import BaseIOSchema, BaseTool, BaseToolConfig+++logger = logging.getLogger(__name__)+++################+# INPUT SCHEMA #+################+class SerplySearchToolInputSchema(BaseIOSchema):+ """+ Search Google web results, Google News, or Google Scholar through the Serply API.+ Use this to find current information, news coverage, or academic papers on a topic.+ Requires a Serply API key.+ """++ queries: List[str] = Field(..., description="Search queries to run.")+ search_type: Literal["search", "news", "scholar"] = Field(+ default="search",+ description=(+ "Which Serply endpoint to query. 'search' = Google web results; 'news' = Google News"+ " articles; 'scholar' = Google Scholar papers."+ ),+ )+ max_results_per_query: int = Field(default=10, ge=1, le=100, description="Maximum results per query.")+++####################+# OUTPUT SCHEMA(S) #+####################+class SerplySearchResultItem(BaseIOSchema):+ """A single Serply search result (web page, news article, or paper)."""++ query: str = Field(..., description="The query that produced this result.")+ title: str = Field(..., description="Title of the result.")+ url: str = Field(..., description="URL of the result.")+ description: Optional[str] = Field(None, description="Snippet, summary, or abstract text.")+ position: Optional[int] = Field(None, description="Rank of the result on the results page (web search only).")+ published: Optional[str] = Field(None, description="Publication date string (news only).")+ source: Optional[str] = Field(None, description="Publisher name (news only).")+ authors: Optional[str] = Field(None, description="Comma-separated author names (scholar only).")+ citations: Optional[int] = Field(None, description="Citation count (scholar only).")+++class SerplySearchToolOutputSchema(BaseIOSchema):+ """Output of the Serply search tool."""++ results: List[SerplySearchResultItem] = Field(..., description="Matching results across all queries.")+++#################+# CONFIGURATION #+#################+class SerplySearchToolConfig(BaseToolConfig):+ """Configuration for the SerplySearchTool."""++ api_key: str = Field(default="", description="Serply API key. Falls back to the SERPLY_API_KEY environment variable.")+ base_url: str = Field(default="https://api.serply.io/v1", description="Serply API base URL.")+ hl: str = Field(default="en", description="Interface language code passed to Google, e.g. 'en' or 'de'.")+ gl: str = Field(default="us", description="Country code for the search, e.g. 'us' or 'gb'.")+ user_agent: str = Field(+ default="atomic-agents-serply-tool/1.0 (+https://github.com/eigenwise/atomic-agents)",+ description="User agent for HTTP requests.",+ )+ timeout: float = Field(default=30.0, ge=1.0, le=120.0, description="HTTP request timeout in seconds.")+++#####################+# MAIN TOOL & LOGIC #+#####################+class SerplySearchTool(BaseTool[SerplySearchToolInputSchema, SerplySearchToolOutputSchema]):+ """Tool for searching Google web, news, and scholar results via the Serply API."""++ RESULT_KEYS = {"search": "results", "news": "entries", "scholar": "articles"}++ def __init__(self, config: SerplySearchToolConfig = SerplySearchToolConfig()):+ super().__init__(config)+ self.api_key = config.api_key or os.getenv("SERPLY_API_KEY", "")+ self.base_url = config.base_url.rstrip("/")+ self.hl = config.hl+ self.gl = config.gl+ self.user_agent = config.user_agent+ self.timeout = config.timeout++ @classmethod+ def _to_item(cls, hit: dict, query: str) -> SerplySearchResultItem:+ source = hit.get("source")+ if isinstance(source, dict):+ source = source.get("title") or source.get("href")++ author = hit.get("author")+ authors = author.get("names") if isinstance(author, dict) else author++ citations = None+ extras = hit.get("extras")+ if isinstance(extras, dict) and isinstance(extras.get("citations"), dict):+ citations = extras["citations"].get("count")++ return SerplySearchResultItem(+ query=query,+ title=hit["title"],+ url=hit["link"],+ description=hit.get("description") or hit.get("summary"),+ position=hit.get("position"),+ published=hit.get("published"),+ source=str(source) if source else None,+ authors=str(authors) if authors else None,+ citations=citations,+ )++ async def _fetch(+ self,+ session: aiohttp.ClientSession,+ query: str,+ search_type: str,+ max_results: int,+ ) -> List[SerplySearchResultItem]:+ params = {"q": query, "num": str(max_results), "hl": self.hl, "gl": self.gl}++ async with session.get(f"{self.base_url}/{search_type}/", params=params) as resp:+ if resp.status != 200:+ raise Exception(f"Serply {search_type} failed for '{query}': {resp.status} {resp.reason}")+ data = await resp.json()++ hits = data.get(self.RESULT_KEYS[search_type], [])+ items = [self._to_item(hit, query) for hit in hits if hit.get("title") and hit.get("link")]+ return items[:max_results]++ async def run_async(self, params: SerplySearchToolInputSchema) -> SerplySearchToolOutputSchema:+ if not self.api_key:+ raise ValueError(+ "Serply API key is missing. Set SerplySearchToolConfig.api_key or the SERPLY_API_KEY environment variable."+ )++ headers = {"X-Api-Key": self.api_key, "User-Agent": self.user_agent, "Accept": "application/json"}+ timeout = aiohttp.ClientTimeout(total=self.timeout)+ async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session:+ tasks = [self._fetch(session, q, params.search_type, params.max_results_per_query) for q in params.queries]+ grouped = await asyncio.gather(*tasks, return_exceptions=True)++ results: List[SerplySearchResultItem] = []+ for query, group in zip(params.queries, grouped):+ if isinstance(group, Exception):+ logger.warning("Serply query '%s' failed: %s", query, group)+ continue+ results.extend(group)+ return SerplySearchToolOutputSchema(results=results)++ def run(self, params: SerplySearchToolInputSchema) -> SerplySearchToolOutputSchema:+ with ThreadPoolExecutor() as executor:+ return executor.submit(asyncio.run, self.run_async(params)).result()+++#################+# EXAMPLE USAGE #+#################+if __name__ == "__main__": # pragma: no cover+ from dotenv import load_dotenv+ from rich.console import Console++ load_dotenv()+ console = Console()+ tool = SerplySearchTool(config=SerplySearchToolConfig(api_key=os.getenv("SERPLY_API_KEY", "")))++ for search_type in ("search", "news", "scholar"):+ output = tool.run(+ SerplySearchToolInputSchema(+ queries=["atomic agents framework"],+ search_type=search_type,+ max_results_per_query=3,+ )+ )+ console.rule(f"[bold cyan]{search_type}")+ for item in output.results:+ console.print(f"[bold]{item.title}[/bold]")+ console.print(item.url)+ if item.description:+ console.print(item.description[:200])+ if item.published:+ console.print(f"[bold]Published:[/bold] {item.published} [bold]Source:[/bold] {item.source}")+ if item.authors:+ console.print(f"[bold]Authors:[/bold] {item.authors[:120]} [bold]Citations:[/bold] {item.citations}")+ console.print()diff --git a/docs/guides/tools.md b/docs/guides/tools.mdindex 9b5d9cb..5d29036 100644--- a/docs/guides/tools.md+++ b/docs/guides/tools.md@@ -153,6 +153,7 @@ The Atomic Forge ships with several pre-built tools:- **Hacker News Search**: Search HN stories, comments, Show HN, Ask HN, polls (free Algolia API)- **PDF Reader**: Extract text and metadata from local or remote PDFs, with page-range filtering- **SearXNG Search**: Search the web using SearXNG+- **Serply Search**: Google web, news, and scholar search via the Serply API- **Tavily Search**: AI-powered web search- **Weather**: Current conditions and daily/hourly forecasts via Open-Meteo (no key required)- **Webpage Scraper**: Extract content from web pagesdiff --git a/uv.lock b/uv.lockindex f17798d..29e756a 100644--- a/uv.lock+++ b/uv.lock@@ -31,6 +31,7 @@ members = ["quickstart","rag-chatbot","searxng-search",+ "serply-search","tavily-search","weather-tool","web-search-agent",@@ -3929,6 +3930,43 @@ dev = [{ name = "rich", specifier = ">=13.7.0,<14.0.0" },]+[[package]]+name = "serply-search"+version = "1.0.0"+source = { editable = "atomic-forge/tools/serply_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 = "shellingham"version = "1.5.4"