Building AI agents, atomically
feat(tools): add 6 forge tools and unblock per-tool tests
KennyVaneetveldef53c965f95a1
diff --git a/README.md b/README.mdindex 8085450..9537c19 100644--- a/README.md+++ b/README.md@@ -314,8 +314,18 @@ If you're upgrading from v1.x, please read our comprehensive [**Upgrade Guide**]Atomic Forge is a collection of tools that can be used with Atomic Agents to extend its functionality. Current tools include:+- arXiv Search+- BoCha Search- Calculator+- DateTime+- Fía Signals+- Hacker News Search+- PDF Reader- SearXNG Search+- Tavily Search+- Webpage Scraper+- Weather+- Wikipedia Search- YouTube Transcript ScraperFor more information on using and creating tools, see the [Atomic Forge README](/atomic-forge/README.md).diff --git a/agents.md b/agents.mdindex e4e0956..8510706 100644--- a/agents.md+++ b/agents.md@@ -99,10 +99,18 @@ Each example is self-contained and demonstrates specific patterns and capabiliti**Philosophy:** Tools are NOT bundled with the framework. Instead, users download individual tools for full control and customization.**Available Tools:**+- `arxiv_search/` - Academic paper search via the public arXiv API+- `bocha_search/` - BoCha web search- `calculator/` - Mathematical computation tool+- `datetime_tool/` - Timezone-aware now / parse / convert / shift / diff+- `fia_signals/` - Crypto market intelligence (regime, signals, yields, gas, trending, wallet risk)+- `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- `tavily_search/` - Tavily API search tool+- `weather/` - Current conditions and daily/hourly forecast via Open-Meteo (no key)- `webpage_scraper/` - Web scraping capabilities+- `wikipedia_search/` - Wikipedia search in any language edition (no key)- `youtube_transcript_scraper/` - YouTube transcript extraction**Benefits:**diff --git a/atomic-forge/README.md b/atomic-forge/README.mdindex 10e25fc..bf05ca5 100644--- a/atomic-forge/README.md+++ b/atomic-forge/README.md@@ -13,11 +13,19 @@ Please use the [Atomic Assembler CLI](../README.md) as mentioned in the main [RE## ToolsThe Atomic Forge project includes the following tools:+- [arXiv Search](/atomic-forge/tools/arxiv_search/README.md) — search the free arXiv public API for academic papers.+- [BoCha Search](/atomic-forge/tools/bocha_search/README.md)- [Calculator](/atomic-forge/tools/calculator/README.md)+- [DateTime](/atomic-forge/tools/datetime_tool/README.md) — timezone-aware now/parse/convert/shift/diff.+- [Fía Signals](/atomic-forge/tools/fia_signals/README.md)+- [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)- [Tavily Search](/atomic-forge/tools/tavily_search/README.md)-- [YouTube Transcript Scraper](/atomic-forge/tools/youtube_transcript_scraper/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.+- [Wikipedia Search](/atomic-forge/tools/wikipedia_search/README.md) — search Wikipedia in any language edition (no API key).+- [YouTube Transcript Scraper](/atomic-forge/tools/youtube_transcript_scraper/README.md)## Creating Custom ToolsCreating your own tools is easy! See the [Creating Tools](/atomic-forge/guides/tool_structure.md) guide for more information.diff --git a/atomic-forge/tools/arxiv_search/.coveragerc b/atomic-forge/tools/arxiv_search/.coveragercnew file mode 100644index 0000000..c45136e--- /dev/null+++ b/atomic-forge/tools/arxiv_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/arxiv_search/README.md b/atomic-forge/tools/arxiv_search/README.mdnew file mode 100644index 0000000..928a82e--- /dev/null+++ b/atomic-forge/tools/arxiv_search/README.md@@ -0,0 +1,50 @@+# arXiv Search Tool++## Overview+Searches arXiv for academic papers via the free public API and returns each paper's title, authors, abstract, dates, categories, and links to the abstract page and the PDF. No API key required.++## Prerequisites and Dependencies+- Python 3.12 or later+- `atomic-agents`+- `pydantic`+- `aiohttp`++## Installation+1. Use the Atomic Assembler CLI: run `atomic` and pick `arxiv_search`.+2. Or copy the `tool/` folder directly into your project.++## Input & Output Structure++### Input Schema+- `queries` (list[str]): plain keywords or arXiv field-prefixed expressions (`ti:`, `au:`, `abs:`, `cat:`, `id:`, `all:`).+- `max_results_per_query` (int): 1–50 (default 5).+- `sort_by` (str): `relevance`, `lastUpdatedDate`, or `submittedDate` (default `relevance`).+- `sort_order` (str): `ascending` or `descending` (default `descending`).+- `category` (str, optional): arXiv category filter (e.g. `cs.AI`).++### Output Schema+A list of `ArxivPaper` items. Each has `arxiv_id`, `title`, `summary`, `authors`, `published`, `updated`, `categories`, `primary_category`, `pdf_url`, `abs_url`, optional `comment` and `journal_ref`.++## Usage++```python+from tool.arxiv_search import ArxivSearchTool, ArxivSearchToolInputSchema++tool = ArxivSearchTool()++output = tool.run(ArxivSearchToolInputSchema(+ queries=["retrieval augmented generation"],+ max_results_per_query=3,+ category="cs.AI",+))++for paper in output.results:+ print(paper.arxiv_id, "-", paper.title)+ print(paper.pdf_url)+```++## Contributing+PRs welcome — see the main repo `CONTRIBUTING.md`.++## License+Same as the main Atomic Agents project.diff --git a/atomic-forge/tools/arxiv_search/pyproject.toml b/atomic-forge/tools/arxiv_search/pyproject.tomlnew file mode 100644index 0000000..d00634f--- /dev/null+++ b/atomic-forge/tools/arxiv_search/pyproject.toml@@ -0,0 +1,32 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["tool"]++[project]+name = "arxiv-search"+version = "1.0.0"+description = "arXiv search tool for Atomic Agents (free public API)"+readme = "README.md"+authors = [+ { name = "Kenny Vaneetvelde", 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",+]++[tool.uv.sources]+atomic-agents = { workspace = true }diff --git a/atomic-forge/tools/arxiv_search/requirements.txt b/atomic-forge/tools/arxiv_search/requirements.txtnew file mode 100644index 0000000..469c7e9--- /dev/null+++ b/atomic-forge/tools/arxiv_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/arxiv_search/tests/test_arxiv_search.py b/atomic-forge/tools/arxiv_search/tests/test_arxiv_search.pynew file mode 100644index 0000000..2f27794--- /dev/null+++ b/atomic-forge/tools/arxiv_search/tests/test_arxiv_search.py@@ -0,0 +1,137 @@+from unittest.mock import AsyncMock, patch++import pytest++from tool.arxiv_search import (+ ArxivPaper,+ ArxivSearchTool,+ ArxivSearchToolConfig,+ ArxivSearchToolInputSchema,+ ArxivSearchToolOutputSchema,+)+++SAMPLE_FEED = """<?xml version="1.0" encoding="UTF-8"?>+<feed xmlns="http://www.w3.org/2005/Atom" xmlns:arxiv="http://arxiv.org/schemas/atom">+ <entry>+ <id>http://arxiv.org/abs/2401.12345v2</id>+ <updated>2024-02-01T10:00:00Z</updated>+ <published>2024-01-20T09:00:00Z</published>+ <title>A Cool Paper About RAG</title>+ <summary>+ We propose a new method for retrieval-augmented generation+ that improves accuracy across many tasks.+ </summary>+ <author><name>Alice Researcher</name></author>+ <author><name>Bob Engineer</name></author>+ <link href="http://arxiv.org/abs/2401.12345v2" rel="alternate" type="text/html"/>+ <link href="http://arxiv.org/pdf/2401.12345v2.pdf" rel="related" title="pdf" type="application/pdf"/>+ <arxiv:primary_category term="cs.AI"/>+ <category term="cs.AI"/>+ <category term="cs.CL"/>+ <arxiv:comment>Accepted at ACL 2024</arxiv:comment>+ <arxiv:journal_ref>ACL 2024</arxiv:journal_ref>+ </entry>+ <entry>+ <id>http://arxiv.org/abs/2402.99999v1</id>+ <updated>2024-03-15T11:00:00Z</updated>+ <published>2024-03-10T08:00:00Z</published>+ <title>Another Cool Paper</title>+ <summary>Short abstract.</summary>+ <author><name>Carol Scholar</name></author>+ <link href="http://arxiv.org/abs/2402.99999v1" rel="alternate" type="text/html"/>+ <arxiv:primary_category term="cs.LG"/>+ <category term="cs.LG"/>+ </entry>+</feed>+"""+++def tool():+ return ArxivSearchTool(config=ArxivSearchToolConfig())+++def test_build_search_query_plain(tool):+ assert tool._build_search_query("agentic LLM", None) == "all:agentic LLM"+++def test_build_search_query_with_field_prefix(tool):+ assert tool._build_search_query("ti:RAG", None) == "ti:RAG"+++def test_build_search_query_with_category(tool):+ assert tool._build_search_query("RAG", "cs.AI") == "all:RAG AND cat:cs.AI"+++def test_build_search_query_field_prefix_and_category(tool):+ assert tool._build_search_query("ti:RAG", "cs.AI") == "ti:RAG AND cat:cs.AI"+++def test_extract_id_strips_version_and_url(tool):+ assert tool._extract_id("http://arxiv.org/abs/2401.12345v2") == "2401.12345"+ assert tool._extract_id("http://arxiv.org/abs/2401.12345") == "2401.12345"+++def test_parse_feed_returns_papers(tool):+ papers = ArxivSearchTool.parse_feed(SAMPLE_FEED, "RAG")+ assert len(papers) == 2++ paper = papers[0]+ assert isinstance(paper, ArxivPaper)+ assert paper.query == "RAG"+ assert paper.arxiv_id == "2401.12345"+ assert paper.title == "A Cool Paper About RAG"+ assert paper.summary.startswith("We propose a new method")+ assert paper.authors == ["Alice Researcher", "Bob Engineer"]+ assert paper.categories == ["cs.AI", "cs.CL"]+ assert paper.primary_category == "cs.AI"+ assert paper.pdf_url == "http://arxiv.org/pdf/2401.12345v2.pdf"+ assert paper.abs_url == "http://arxiv.org/abs/2401.12345v2"+ assert paper.comment == "Accepted at ACL 2024"+ assert paper.journal_ref == "ACL 2024"++ second = papers[1]+ # PDF url is derived when not explicitly present+ assert second.pdf_url == "http://arxiv.org/pdf/2402.99999v1"+ assert second.comment is None+++async def test_run_async_uses_parse_feed(tool):+ """Bypass the network: stub _fetch with parsed sample feed."""++ async def fake_fetch(self, session, query, max_results, sort_by, sort_order, category):+ return ArxivSearchTool.parse_feed(SAMPLE_FEED, query)++ with patch.object(ArxivSearchTool, "_fetch", fake_fetch):+ out = await tool.run_async(ArxivSearchToolInputSchema(queries=["RAG", "agents"]))++ assert isinstance(out, ArxivSearchToolOutputSchema)+ assert len(out.results) == 4 # 2 sample papers x 2 queries+ assert {p.query for p in out.results} == {"RAG", "agents"}+++async def test_run_async_skips_failed_query(tool):+ async def fake_fetch(self, session, query, *_):+ if query == "bad":+ raise Exception("network down")+ return ArxivSearchTool.parse_feed(SAMPLE_FEED, query)++ with patch.object(ArxivSearchTool, "_fetch", fake_fetch):+ out = await tool.run_async(ArxivSearchToolInputSchema(queries=["good", "bad"]))++ assert len(out.results) == 2+ assert all(p.query == "good" for p in out.results)+++def test_run_invokes_run_async(tool):+ sentinel = ArxivSearchToolOutputSchema(results=[])+ with patch.object(ArxivSearchTool, "run_async", AsyncMock(return_value=sentinel)):+ out = tool.run(ArxivSearchToolInputSchema(queries=["q"]))+ assert out is sentinel+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/atomic-forge/tools/arxiv_search/tool/arxiv_search.py b/atomic-forge/tools/arxiv_search/tool/arxiv_search.pynew file mode 100644index 0000000..e78377e--- /dev/null+++ b/atomic-forge/tools/arxiv_search/tool/arxiv_search.py@@ -0,0 +1,255 @@+import asyncio+import logging+import xml.etree.ElementTree as ET+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__)+++ATOM_NS = {"atom": "http://www.w3.org/2005/Atom", "arxiv": "http://arxiv.org/schemas/atom"}+++################+# INPUT SCHEMA #+################+class ArxivSearchToolInputSchema(BaseIOSchema):+ """+ Search arXiv for academic papers. Each query is sent to the public arXiv API+ (no key needed) and the matching papers are returned with title, authors,+ abstract, dates, categories, and links to the abstract page and PDF.+ """++ queries: List[str] = Field(+ ...,+ description=(+ "Search queries to run. Use plain keywords (e.g. 'retrieval augmented"+ " generation') or arXiv field-prefixed expressions (e.g. 'ti:LLM AND"+ " abs:agents')."+ ),+ )+ max_results_per_query: int = Field(default=5, ge=1, le=50, description="Maximum number of papers per query.")+ sort_by: Literal["relevance", "lastUpdatedDate", "submittedDate"] = Field(+ default="relevance", description="Sort order for results."+ )+ sort_order: Literal["ascending", "descending"] = Field(default="descending", description="Direction for the chosen sort.")+ category: Optional[str] = Field(+ default=None,+ description=(+ "Optional arXiv category to filter to (e.g. 'cs.AI', 'cs.CL',"+ " 'stat.ML'). Combined with the query as `cat:<value>`."+ ),+ )+++####################+# OUTPUT SCHEMA(S) #+####################+class ArxivPaper(BaseIOSchema):+ """A single paper returned by arXiv."""++ query: str = Field(..., description="The query that produced this paper.")+ arxiv_id: str = Field(..., description="arXiv identifier (e.g. '2401.12345').")+ title: str = Field(..., description="Paper title.")+ summary: str = Field(..., description="Abstract / summary.")+ authors: List[str] = Field(..., description="Author names.")+ published: str = Field(..., description="First publication timestamp (ISO 8601).")+ updated: str = Field(..., description="Most recent update timestamp (ISO 8601).")+ categories: List[str] = Field(..., description="arXiv categories (e.g. ['cs.AI']).")+ primary_category: Optional[str] = Field(None, description="Primary arXiv category.")+ pdf_url: str = Field(..., description="Direct URL to the PDF.")+ abs_url: str = Field(..., description="URL to the abstract page.")+ comment: Optional[str] = Field(None, description="Author-supplied comment, if any (e.g. 'Accepted at NeurIPS 2024').")+ journal_ref: Optional[str] = Field(None, description="Journal reference, if provided.")+++class ArxivSearchToolOutputSchema(BaseIOSchema):+ """Output of the arXiv search tool."""++ results: List[ArxivPaper] = Field(..., description="Matching papers across all queries.")+++#################+# CONFIGURATION #+#################+class ArxivSearchToolConfig(BaseToolConfig):+ """Configuration for the ArxivSearchTool."""++ base_url: str = Field(default="https://export.arxiv.org/api/query", description="Base URL of the arXiv API.")+ user_agent: str = Field(+ default="atomic-agents-arxiv-tool/1.0 (+https://github.com/BrainBlend-AI/atomic-agents)",+ description="User agent string for arXiv requests.",+ )+ timeout: float = Field(default=20.0, ge=1.0, le=120.0, description="HTTP request timeout in seconds.")+++#####################+# MAIN TOOL & LOGIC #+#####################+class ArxivSearchTool(BaseTool[ArxivSearchToolInputSchema, ArxivSearchToolOutputSchema]):+ """Tool for searching arXiv (free public API)."""++ def __init__(self, config: ArxivSearchToolConfig = ArxivSearchToolConfig()):+ super().__init__(config)+ self.base_url = config.base_url+ self.user_agent = config.user_agent+ self.timeout = config.timeout++ @staticmethod+ def _build_search_query(query: str, category: Optional[str]) -> str:+ # If the user already used field prefixes, leave them alone; otherwise wrap as `all:`+ if any(prefix in query for prefix in ("ti:", "au:", "abs:", "cat:", "all:", "id:")):+ base = query+ else:+ base = f"all:{query}"+ if category:+ base = f"{base} AND cat:{category}"+ return base++ @staticmethod+ def _extract_id(entry_id: str) -> str:+ """Strip the version suffix and the URL prefix from an arXiv entry id."""+ # entry id looks like: http://arxiv.org/abs/2401.12345v2+ tail = entry_id.rsplit("/abs/", 1)[-1]+ return tail.split("v")[0] if "v" in tail else tail++ @classmethod+ def _parse_entry(cls, entry: ET.Element, query: str) -> ArxivPaper:+ def _text(tag: str) -> str:+ el = entry.find(tag, ATOM_NS)+ return (el.text or "").strip() if el is not None else ""++ entry_id = _text("atom:id")+ arxiv_id = cls._extract_id(entry_id)++ title = " ".join(_text("atom:title").split())+ summary = " ".join(_text("atom:summary").split())++ authors = [+ (a.findtext("atom:name", default="", namespaces=ATOM_NS) or "").strip()+ for a in entry.findall("atom:author", ATOM_NS)+ ]+ authors = [name for name in authors if name]++ categories = [c.attrib.get("term", "") for c in entry.findall("atom:category", ATOM_NS) if c.attrib.get("term")]++ primary_el = entry.find("arxiv:primary_category", ATOM_NS)+ primary_category = primary_el.attrib.get("term") if primary_el is not None else None++ pdf_url = ""+ abs_url = entry_id # default to the id URL+ for link in entry.findall("atom:link", ATOM_NS):+ if link.attrib.get("title") == "pdf" or link.attrib.get("type") == "application/pdf":+ pdf_url = link.attrib.get("href", "")+ elif link.attrib.get("rel") == "alternate":+ abs_url = link.attrib.get("href", abs_url)+ if not pdf_url and abs_url:+ pdf_url = abs_url.replace("/abs/", "/pdf/")++ comment_el = entry.find("arxiv:comment", ATOM_NS)+ journal_el = entry.find("arxiv:journal_ref", ATOM_NS)++ return ArxivPaper(+ query=query,+ arxiv_id=arxiv_id,+ title=title,+ summary=summary,+ authors=authors,+ published=_text("atom:published"),+ updated=_text("atom:updated"),+ categories=categories,+ primary_category=primary_category,+ pdf_url=pdf_url,+ abs_url=abs_url,+ comment=(comment_el.text or "").strip() if comment_el is not None and comment_el.text else None,+ journal_ref=(journal_el.text or "").strip() if journal_el is not None and journal_el.text else None,+ )++ @classmethod+ def parse_feed(cls, xml_text: str, query: str) -> List[ArxivPaper]:+ """Parse the Atom feed XML returned by arXiv into a list of ArxivPaper."""+ root = ET.fromstring(xml_text)+ return [cls._parse_entry(entry, query) for entry in root.findall("atom:entry", ATOM_NS)]++ async def _fetch(+ self,+ session: aiohttp.ClientSession,+ query: str,+ max_results: int,+ sort_by: str,+ sort_order: str,+ category: Optional[str],+ ) -> List[ArxivPaper]:+ params = {+ "search_query": self._build_search_query(query, category),+ "start": "0",+ "max_results": str(max_results),+ "sortBy": sort_by,+ "sortOrder": sort_order,+ }+ async with session.get(self.base_url, params=params) as resp:+ if resp.status != 200:+ raise Exception(f"arXiv search failed for '{query}': {resp.status} {resp.reason}")+ text = await resp.text()+ return self.parse_feed(text, query)++ async def run_async(self, params: ArxivSearchToolInputSchema) -> ArxivSearchToolOutputSchema:+ headers = {"User-Agent": self.user_agent, "Accept": "application/atom+xml"}+ timeout = aiohttp.ClientTimeout(total=self.timeout)+ async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session:+ tasks = [+ self._fetch(+ session,+ q,+ params.max_results_per_query,+ params.sort_by,+ params.sort_order,+ params.category,+ )+ for q in params.queries+ ]+ grouped = await asyncio.gather(*tasks, return_exceptions=True)++ results: List[ArxivPaper] = []+ for query, group in zip(params.queries, grouped):+ if isinstance(group, Exception):+ logger.warning("arXiv query '%s' failed: %s", query, group)+ continue+ results.extend(group)+ return ArxivSearchToolOutputSchema(results=results)++ def run(self, params: ArxivSearchToolInputSchema) -> ArxivSearchToolOutputSchema:+ with ThreadPoolExecutor() as executor:+ return executor.submit(asyncio.run, self.run_async(params)).result()+++#################+# EXAMPLE USAGE #+#################+if __name__ == "__main__": # pragma: no cover+ from rich.console import Console++ console = Console()+ tool = ArxivSearchTool()++ output = tool.run(+ ArxivSearchToolInputSchema(+ queries=["retrieval augmented generation", "agentic LLM tool use"],+ max_results_per_query=2,+ category="cs.AI",+ )+ )+ for paper in output.results:+ console.rule(f"[bold cyan]{paper.arxiv_id} — {paper.title}")+ console.print(f"[bold]Authors:[/bold] {', '.join(paper.authors)}")+ console.print(f"[bold]Published:[/bold] {paper.published} [bold]Updated:[/bold] {paper.updated}")+ console.print(f"[bold]Categories:[/bold] {', '.join(paper.categories)}")+ console.print(f"[bold]Abstract URL:[/bold] {paper.abs_url}")+ console.print(f"[bold]PDF URL:[/bold] {paper.pdf_url}")+ console.print(paper.summary)diff --git a/atomic-forge/tools/datetime_tool/.coveragerc b/atomic-forge/tools/datetime_tool/.coveragercnew file mode 100644index 0000000..c45136e--- /dev/null+++ b/atomic-forge/tools/datetime_tool/.coveragerc@@ -0,0 +1,8 @@+[run]+source = tool+omit = */tests/*++[report]+exclude_lines =+ if __name__ == "__main__":+show_missing = Truediff --git a/atomic-forge/tools/datetime_tool/README.md b/atomic-forge/tools/datetime_tool/README.mdnew file mode 100644index 0000000..24bfe2c--- /dev/null+++ b/atomic-forge/tools/datetime_tool/README.md@@ -0,0 +1,63 @@+# DateTime Tool++## Overview+A timezone-aware date and time tool. Use it to:++- get the current time in any IANA timezone (`now`)+- parse an ISO 8601 datetime string into structured fields (`parse`)+- convert a datetime from one timezone to another (`convert`)+- shift a datetime by days/hours/minutes/seconds (`shift`)+- compute the difference between two datetimes (`diff`)++It uses the standard library only (`datetime`, `zoneinfo`) plus `tzdata` so the tool also works on Windows where the OS does not ship the IANA timezone database.++## Prerequisites and Dependencies+- Python 3.12 or later+- `atomic-agents`+- `pydantic`+- `tzdata`++## Installation+1. Using the Atomic Assembler CLI: run `atomic` and select `datetime_tool`.+2. Or copy the `tool/` folder directly into your project.++## Input & Output Structure++### Input Schema+- `operation` (Literal): one of `now`, `parse`, `convert`, `shift`, `diff`.+- `timezone` (str): IANA timezone name. Defaults to `UTC`. For `convert` this is the source timezone of `input`.+- `target_timezone` (str, optional): required for `convert`.+- `input` (str, optional): ISO 8601 datetime string for non-`now` operations.+- `input_2` (str, optional): second datetime, required for `diff` (computes `input_2 - input`).+- `days`, `hours`, `minutes`, `seconds` (int): duration components for `shift` (negative values subtract).++### Output Schema+- `operation` (str): operation that was performed.+- `iso`, `timezone`, `unix_timestamp`, `year`, `month`, `day`, `hour`, `minute`, `second`, `weekday`, `human`: populated for `now`/`parse`/`convert`/`shift`.+- `diff_seconds`, `diff_human`: populated for `diff`.+- `error` (str, optional): set when something went wrong.++## Usage++```python+from tool.datetime_tool import DateTimeTool, DateTimeToolInputSchema++tool = DateTimeTool()++# Current time in Tokyo+print(tool.run(DateTimeToolInputSchema(operation="now", timezone="Asia/Tokyo")))++# Convert a Brussels meeting time to New York+print(tool.run(DateTimeToolInputSchema(+ operation="convert",+ input="2026-04-29T15:30:00",+ timezone="Europe/Brussels",+ target_timezone="America/New_York",+)))+```++## Contributing+PRs welcome — see the main repo `CONTRIBUTING.md`.++## License+Same as the main Atomic Agents project.diff --git a/atomic-forge/tools/datetime_tool/pyproject.toml b/atomic-forge/tools/datetime_tool/pyproject.tomlnew file mode 100644index 0000000..517a3ed--- /dev/null+++ b/atomic-forge/tools/datetime_tool/pyproject.toml@@ -0,0 +1,31 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["tool"]++[project]+name = "datetime-tool"+version = "1.0.0"+description = "Date and time operations (now, parse, convert, shift, diff) for Atomic Agents"+readme = "README.md"+authors = [+ { name = "Kenny Vaneetvelde", email = "[email protected]" }+]+requires-python = ">=3.12"+dependencies = [+ "atomic-agents",+ "pydantic>=2.10.3,<3.0.0",+ "tzdata>=2024.1",+]++[dependency-groups]+dev = [+ "coverage>=7.6.1,<8.0.0",+ "pytest-cov>=5.0.0,<6.0.0",+ "pytest>=8.3.3,<9.0.0",+]++[tool.uv.sources]+atomic-agents = { workspace = true }diff --git a/atomic-forge/tools/datetime_tool/requirements.txt b/atomic-forge/tools/datetime_tool/requirements.txtnew file mode 100644index 0000000..7476a5b--- /dev/null+++ b/atomic-forge/tools/datetime_tool/requirements.txt@@ -0,0 +1,3 @@+atomic-agents>=2.0.0,<3.0.0+pydantic>=2.10.3,<3.0.0+tzdata>=2024.1diff --git a/atomic-forge/tools/datetime_tool/tests/test_datetime_tool.py b/atomic-forge/tools/datetime_tool/tests/test_datetime_tool.pynew file mode 100644index 0000000..1b98c2e--- /dev/null+++ b/atomic-forge/tools/datetime_tool/tests/test_datetime_tool.py@@ -0,0 +1,135 @@+from tool.datetime_tool import (+ DateTimeTool,+ DateTimeToolInputSchema,+ DateTimeToolOutputSchema,+)+++def test_now_default_utc():+ tool = DateTimeTool()+ out = tool.run(DateTimeToolInputSchema(operation="now"))+ assert isinstance(out, DateTimeToolOutputSchema)+ assert out.operation == "now"+ assert out.iso is not None+ assert out.error is None+ assert out.weekday in {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}+++def test_now_in_tokyo():+ tool = DateTimeTool()+ out = tool.run(DateTimeToolInputSchema(operation="now", timezone="Asia/Tokyo"))+ assert out.error is None+ assert out.timezone == "Asia/Tokyo"+ assert "+09:00" in out.iso+++def test_parse_iso_with_timezone():+ tool = DateTimeTool()+ out = tool.run(DateTimeToolInputSchema(operation="parse", input="2026-04-29T15:30:00Z"))+ assert out.error is None+ assert (out.year, out.month, out.day, out.hour, out.minute) == (2026, 4, 29, 15, 30)+ assert out.iso.startswith("2026-04-29T15:30:00")+++def test_parse_naive_uses_default_tz():+ tool = DateTimeTool()+ out = tool.run(DateTimeToolInputSchema(operation="parse", input="2026-04-29T15:30:00", timezone="Europe/Brussels"))+ assert out.error is None+ assert out.timezone == "Europe/Brussels"+++def test_convert_brussels_to_new_york():+ tool = DateTimeTool()+ out = tool.run(+ DateTimeToolInputSchema(+ operation="convert",+ input="2026-04-29T15:30:00",+ timezone="Europe/Brussels",+ target_timezone="America/New_York",+ )+ )+ assert out.error is None+ assert out.timezone == "America/New_York"+ assert (out.year, out.month, out.day) == (2026, 4, 29)+ assert (out.hour, out.minute) == (9, 30)+++def test_shift_forward_and_backward():+ tool = DateTimeTool()+ out = tool.run(+ DateTimeToolInputSchema(+ operation="shift",+ input="2026-04-29T00:00:00Z",+ days=3,+ hours=-2,+ minutes=30,+ )+ )+ assert out.error is None+ assert out.year == 2026+ assert out.month == 5+ assert out.day == 1+ assert out.hour == 22+ assert out.minute == 30+++def test_diff_positive():+ tool = DateTimeTool()+ out = tool.run(+ DateTimeToolInputSchema(+ operation="diff",+ input="2026-04-29T00:00:00Z",+ input_2="2026-04-30T01:30:00Z",+ )+ )+ assert out.error is None+ assert out.diff_seconds == 25 * 3600 + 30 * 60+ assert "1 day" in out.diff_human and "1 hour" in out.diff_human and "30 minute" in out.diff_human+++def test_diff_negative_keeps_sign():+ tool = DateTimeTool()+ out = tool.run(+ DateTimeToolInputSchema(+ operation="diff",+ input="2026-04-30T00:00:00Z",+ input_2="2026-04-29T00:00:00Z",+ )+ )+ assert out.error is None+ assert out.diff_seconds == -86400.0+ assert out.diff_human.startswith("-")+++def test_unknown_timezone_returns_error():+ tool = DateTimeTool()+ out = tool.run(DateTimeToolInputSchema(operation="now", timezone="Mars/Olympus"))+ assert out.error is not None+ assert "Unknown timezone" in out.error+++def test_missing_input_for_parse_returns_error():+ tool = DateTimeTool()+ out = tool.run(DateTimeToolInputSchema(operation="parse"))+ assert out.error is not None+ assert "input" in out.error+++def test_missing_target_timezone_for_convert():+ tool = DateTimeTool()+ out = tool.run(DateTimeToolInputSchema(operation="convert", input="2026-04-29T15:30:00Z"))+ assert out.error is not None+ assert "target_timezone" in out.error+++def test_unparseable_input():+ tool = DateTimeTool()+ out = tool.run(DateTimeToolInputSchema(operation="parse", input="not-a-date"))+ assert out.error is not None+ assert "Could not parse" in out.error+++if __name__ == "__main__":+ import pytest++ pytest.main([__file__, "-v"])diff --git a/atomic-forge/tools/datetime_tool/tool/datetime_tool.py b/atomic-forge/tools/datetime_tool/tool/datetime_tool.pynew file mode 100644index 0000000..03de138--- /dev/null+++ b/atomic-forge/tools/datetime_tool/tool/datetime_tool.py@@ -0,0 +1,257 @@+from datetime import datetime, timedelta, timezone+from typing import Literal, Optional+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++from pydantic import Field++from atomic_agents import BaseIOSchema, BaseTool, BaseToolConfig+++################+# INPUT SCHEMA #+################+class DateTimeToolInputSchema(BaseIOSchema):+ """+ Tool for date and time operations: getting the current time in any timezone,+ parsing datetime strings, converting between timezones, shifting a datetime by a+ duration, and computing the difference between two datetimes. Use this whenever+ you need to know "what is today's date", convert a meeting time across regions,+ or do any temporal arithmetic.+ """++ operation: Literal["now", "parse", "convert", "shift", "diff"] = Field(+ ...,+ description=(+ "The operation to perform. 'now' returns the current time. 'parse' parses"+ " an input datetime string. 'convert' converts a datetime from one"+ " timezone to another. 'shift' adds a duration to a datetime. 'diff'"+ " computes the time difference between two datetimes."+ ),+ )+ timezone: str = Field(+ default="UTC",+ description=(+ "IANA timezone name to interpret the input/result in (e.g. 'UTC',"+ " 'America/New_York', 'Europe/Brussels', 'Asia/Tokyo'). For 'convert'"+ " this is the source timezone of `input`."+ ),+ )+ target_timezone: Optional[str] = Field(+ default=None,+ description="Target IANA timezone for the 'convert' operation.",+ )+ input: Optional[str] = Field(+ default=None,+ description=(+ "Datetime string for 'parse', 'convert', and 'shift' operations. ISO 8601"+ " is preferred (e.g. '2026-04-29T15:30:00'). If the string has no"+ " timezone info, `timezone` is used."+ ),+ )+ input_2: Optional[str] = Field(+ default=None,+ description="Second datetime string for the 'diff' operation (computes input_2 - input).",+ )+ days: int = Field(default=0, description="Days to add for 'shift' (negative to subtract).")+ hours: int = Field(default=0, description="Hours to add for 'shift' (negative to subtract).")+ minutes: int = Field(default=0, description="Minutes to add for 'shift' (negative to subtract).")+ seconds: int = Field(default=0, description="Seconds to add for 'shift' (negative to subtract).")+++#################+# OUTPUT SCHEMA #+#################+class DateTimeToolOutputSchema(BaseIOSchema):+ """Output of the DateTimeTool. `error` is populated only when the operation fails."""++ operation: str = Field(..., description="The operation that was performed.")+ iso: Optional[str] = Field(None, description="ISO 8601 representation of the resulting datetime.")+ timezone: Optional[str] = Field(None, description="IANA timezone of the resulting datetime.")+ unix_timestamp: Optional[float] = Field(None, description="POSIX/Unix timestamp (seconds since epoch).")+ year: Optional[int] = Field(None, description="Year component of the resulting datetime.")+ month: Optional[int] = Field(None, description="Month component (1-12).")+ day: Optional[int] = Field(None, description="Day-of-month component (1-31).")+ hour: Optional[int] = Field(None, description="Hour component (0-23).")+ minute: Optional[int] = Field(None, description="Minute component (0-59).")+ second: Optional[int] = Field(None, description="Second component (0-59).")+ weekday: Optional[str] = Field(None, description="Day name, e.g. 'Monday'.")+ human: Optional[str] = Field(None, description="Human-readable formatted datetime, e.g. 'Wed, 29 Apr 2026 15:30 UTC'.")+ diff_seconds: Optional[float] = Field(None, description="Total seconds between input_2 and input (for 'diff').")+ diff_human: Optional[str] = Field(None, description="Human-readable difference, e.g. '2 days, 3 hours, 15 minutes'.")+ error: Optional[str] = Field(None, description="Error message if the operation failed.")+++#################+# CONFIGURATION #+#################+class DateTimeToolConfig(BaseToolConfig):+ """Configuration for the DateTimeTool. Currently has no tunable settings beyond title/description overrides."""+++#####################+# MAIN TOOL & LOGIC #+#####################+class DateTimeTool(BaseTool[DateTimeToolInputSchema, DateTimeToolOutputSchema]):+ """Date and time operations: now, parse, convert, shift, diff."""++ def __init__(self, config: DateTimeToolConfig = DateTimeToolConfig()):+ super().__init__(config)++ @staticmethod+ def _zone(name: str) -> ZoneInfo:+ try:+ return ZoneInfo(name)+ except ZoneInfoNotFoundError as e:+ raise ValueError(f"Unknown timezone '{name}'. Use an IANA name like 'UTC' or 'America/New_York'.") from e++ @classmethod+ def _parse(cls, value: str, default_tz: str) -> datetime:+ """+ Parse an ISO 8601 datetime string. Trailing 'Z' is treated as UTC. If the+ parsed value is naive (no tzinfo), `default_tz` is attached.+ """+ text = value.strip()+ if text.endswith("Z"):+ text = text[:-1] + "+00:00"+ try:+ dt = datetime.fromisoformat(text)+ except ValueError as e:+ raise ValueError(f"Could not parse datetime '{value}': {e}") from e+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=cls._zone(default_tz))+ return dt++ @staticmethod+ def _humanize_delta(delta: timedelta) -> str:+ total = int(delta.total_seconds())+ sign = "-" if total < 0 else ""+ total = abs(total)+ days, remainder = divmod(total, 86400)+ hours, remainder = divmod(remainder, 3600)+ minutes, seconds = divmod(remainder, 60)+ parts = []+ if days:+ parts.append(f"{days} day{'s' if days != 1 else ''}")+ if hours:+ parts.append(f"{hours} hour{'s' if hours != 1 else ''}")+ if minutes:+ parts.append(f"{minutes} minute{'s' if minutes != 1 else ''}")+ if seconds or not parts:+ parts.append(f"{seconds} second{'s' if seconds != 1 else ''}")+ return sign + ", ".join(parts)++ def _build(self, dt: datetime, operation: str) -> DateTimeToolOutputSchema:+ tzname = str(dt.tzinfo) if dt.tzinfo and not isinstance(dt.tzinfo, timezone) else (dt.tzname() or "UTC")+ return DateTimeToolOutputSchema(+ operation=operation,+ iso=dt.isoformat(),+ timezone=tzname,+ unix_timestamp=dt.timestamp(),+ year=dt.year,+ month=dt.month,+ day=dt.day,+ hour=dt.hour,+ minute=dt.minute,+ second=dt.second,+ weekday=dt.strftime("%A"),+ human=dt.strftime("%a, %d %b %Y %H:%M %Z").strip(),+ )++ def run(self, params: DateTimeToolInputSchema) -> DateTimeToolOutputSchema:+ try:+ if params.operation == "now":+ dt = datetime.now(self._zone(params.timezone))+ return self._build(dt, "now")++ if params.operation == "parse":+ if not params.input:+ raise ValueError("'parse' operation requires `input`.")+ dt = self._parse(params.input, params.timezone)+ return self._build(dt, "parse")++ if params.operation == "convert":+ if not params.input or not params.target_timezone:+ raise ValueError("'convert' operation requires `input` and `target_timezone`.")+ dt = self._parse(params.input, params.timezone).astimezone(self._zone(params.target_timezone))+ return self._build(dt, "convert")++ if params.operation == "shift":+ if not params.input:+ raise ValueError("'shift' operation requires `input`.")+ dt = self._parse(params.input, params.timezone) + timedelta(+ days=params.days,+ hours=params.hours,+ minutes=params.minutes,+ seconds=params.seconds,+ )+ return self._build(dt, "shift")++ if params.operation == "diff":+ if not params.input or not params.input_2:+ raise ValueError("'diff' operation requires `input` and `input_2`.")+ a = self._parse(params.input, params.timezone)+ b = self._parse(params.input_2, params.timezone)+ delta = b - a+ return DateTimeToolOutputSchema(+ operation="diff",+ diff_seconds=delta.total_seconds(),+ diff_human=self._humanize_delta(delta),+ )++ raise ValueError(f"Unknown operation '{params.operation}'.")+ except Exception as e:+ return DateTimeToolOutputSchema(operation=params.operation, error=str(e))+++#################+# EXAMPLE USAGE #+#################+if __name__ == "__main__": # pragma: no cover+ from rich.console import Console++ console = Console()+ tool = DateTimeTool()++ console.rule("[bold cyan]now in Asia/Tokyo")+ console.print(tool.run(DateTimeToolInputSchema(operation="now", timezone="Asia/Tokyo")))++ console.rule("[bold cyan]parse 2026-04-29T15:30 (Europe/Brussels)")+ console.print(+ tool.run(DateTimeToolInputSchema(operation="parse", input="2026-04-29T15:30:00", timezone="Europe/Brussels"))+ )++ console.rule("[bold cyan]convert Europe/Brussels -> America/New_York")+ console.print(+ tool.run(+ DateTimeToolInputSchema(+ operation="convert",+ input="2026-04-29T15:30:00",+ timezone="Europe/Brussels",+ target_timezone="America/New_York",+ )+ )+ )++ console.rule("[bold cyan]shift +3 days, -2 hours")+ console.print(+ tool.run(+ DateTimeToolInputSchema(+ operation="shift",+ input="2026-04-29T15:30:00",+ timezone="UTC",+ days=3,+ hours=-2,+ )+ )+ )++ console.rule("[bold cyan]diff between two datetimes")+ console.print(+ tool.run(+ DateTimeToolInputSchema(+ operation="diff",+ input="2026-04-29T15:30:00Z",+ input_2="2026-05-02T18:45:00Z",+ )+ )+ )diff --git a/atomic-forge/tools/fia_signals/tool/__init__.py b/atomic-forge/tools/fia_signals/tool/__init__.pydeleted file mode 100644index 4f68225..0000000--- a/atomic-forge/tools/fia_signals/tool/__init__.py+++ /dev/null@@ -1,13 +0,0 @@-from .fia_signals import (- FIASignalsTool,- FIASignalsToolConfig,- FIASignalsToolInputSchema,- FIASignalsToolOutputSchema,-)--__all__ = [- "FIASignalsTool",- "FIASignalsToolConfig",- "FIASignalsToolInputSchema",- "FIASignalsToolOutputSchema",-]diff --git a/atomic-forge/tools/hackernews_search/.coveragerc b/atomic-forge/tools/hackernews_search/.coveragercnew file mode 100644index 0000000..c45136e--- /dev/null+++ b/atomic-forge/tools/hackernews_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/hackernews_search/README.md b/atomic-forge/tools/hackernews_search/README.mdnew file mode 100644index 0000000..2f978e8--- /dev/null+++ b/atomic-forge/tools/hackernews_search/README.md@@ -0,0 +1,50 @@+# Hacker News Search Tool++## Overview+Searches Hacker News stories, comments, Show HN, Ask HN, and polls via the free Algolia HN search API. Supports relevance and date sorting and arbitrary numeric filters (`points>100`, `num_comments>50`, etc.). No authentication required.++## Prerequisites and Dependencies+- Python 3.12 or later+- `atomic-agents`+- `pydantic`+- `aiohttp`++## Installation+1. Use the Atomic Assembler CLI: run `atomic` and pick `hackernews_search`.+2. Or copy the `tool/` folder directly into your project.++## Input & Output Structure++### Input Schema+- `queries` (list[str]): one or more search queries.+- `tags` (str): `story`, `comment`, `show_hn`, `ask_hn`, `poll`, or `front_page` (default `story`).+- `sort_by` (str): `relevance` or `date` (default `relevance`).+- `max_results_per_query` (int): 1–50 (default 10).+- `numeric_filters` (str, optional): Algolia numeric filter expression (e.g. `points>100`).++### Output Schema+A list of `HackerNewsItem` items, each with `object_id`, `title`, `url`, `hn_url`, `author`, `points`, `num_comments`, `created_at`, `story_text`, `comment_text`, `parent_id`, `story_id`.++## Usage++```python+from tool.hackernews_search import HackerNewsSearchTool, HackerNewsSearchToolInputSchema++tool = HackerNewsSearchTool()+output = tool.run(HackerNewsSearchToolInputSchema(+ queries=["MCP server", "atomic agents"],+ sort_by="date",+ max_results_per_query=5,+ numeric_filters="points>10",+))++for item in output.results:+ print(item.title, "-", item.points, "points")+ print(item.hn_url)+```++## Contributing+PRs welcome — see the main repo `CONTRIBUTING.md`.++## License+Same as the main Atomic Agents project.diff --git a/atomic-forge/tools/hackernews_search/pyproject.toml b/atomic-forge/tools/hackernews_search/pyproject.tomlnew file mode 100644index 0000000..6cb5c6f--- /dev/null+++ b/atomic-forge/tools/hackernews_search/pyproject.toml@@ -0,0 +1,32 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["tool"]++[project]+name = "hackernews-search"+version = "1.0.0"+description = "Hacker News search tool for Atomic Agents (free Algolia API)"+readme = "README.md"+authors = [+ { name = "Kenny Vaneetvelde", 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",+]++[tool.uv.sources]+atomic-agents = { workspace = true }diff --git a/atomic-forge/tools/hackernews_search/requirements.txt b/atomic-forge/tools/hackernews_search/requirements.txtnew file mode 100644index 0000000..469c7e9--- /dev/null+++ b/atomic-forge/tools/hackernews_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/hackernews_search/tests/test_hackernews_search.py b/atomic-forge/tools/hackernews_search/tests/test_hackernews_search.pynew file mode 100644index 0000000..8bcbf5f--- /dev/null+++ b/atomic-forge/tools/hackernews_search/tests/test_hackernews_search.py@@ -0,0 +1,116 @@+from unittest.mock import AsyncMock, patch++import pytest++from tool.hackernews_search import (+ HackerNewsItem,+ HackerNewsSearchTool,+ HackerNewsSearchToolConfig,+ HackerNewsSearchToolInputSchema,+ HackerNewsSearchToolOutputSchema,+)+++SAMPLE_HITS = [+ {+ "objectID": "12345",+ "title": "Show HN: Atomic Agents",+ "url": "https://example.com/atomic",+ "author": "alice",+ "points": 250,+ "num_comments": 42,+ "created_at": "2026-04-01T12:00:00Z",+ },+ {+ "objectID": "67890",+ "story_title": "MCP Server Roundup",+ "story_url": "https://example.com/mcp",+ "comment_text": "Best discussion on this so far.",+ "author": "bob",+ "points": None,+ "num_comments": None,+ "created_at": "2026-04-15T09:30:00Z",+ "parent_id": 67889,+ "story_id": 67889,+ },+]+++def tool():+ return HackerNewsSearchTool(config=HackerNewsSearchToolConfig())+++def test_to_item_story(tool):+ item = HackerNewsSearchTool._to_item(SAMPLE_HITS[0], "atomic")+ assert isinstance(item, HackerNewsItem)+ assert item.object_id == "12345"+ assert item.title == "Show HN: Atomic Agents"+ assert item.url == "https://example.com/atomic"+ assert item.hn_url == "https://news.ycombinator.com/item?id=12345"+ assert item.points == 250+ assert item.num_comments == 42+++def test_to_item_comment(tool):+ """Comments come back with story_title/story_url and parent/story ids."""+ item = HackerNewsSearchTool._to_item(SAMPLE_HITS[1], "MCP")+ assert item.title == "MCP Server Roundup" # falls back to story_title+ assert item.url == "https://example.com/mcp"+ assert item.comment_text == "Best discussion on this so far."+ assert item.parent_id == "67889"+ assert item.story_id == "67889"+++async def test_run_async_uses_correct_endpoint(tool):+ """Sort by date should hit search_by_date; relevance hits search."""+ captured: list[str] = []++ async def fake_get_text(self, session, query, tags, sort_by, max_results, numeric_filters):+ endpoint = "search_by_date" if sort_by == "date" else "search"+ captured.append(endpoint)+ return [HackerNewsSearchTool._to_item(SAMPLE_HITS[0], query)]++ with patch.object(HackerNewsSearchTool, "_fetch", fake_get_text):+ await tool.run_async(HackerNewsSearchToolInputSchema(queries=["a"], sort_by="date"))+ await tool.run_async(HackerNewsSearchToolInputSchema(queries=["b"], sort_by="relevance"))+ assert captured == ["search_by_date", "search"]+++async def test_run_async_aggregates_results(tool):+ async def fake_fetch(self, session, query, *_):+ return [HackerNewsSearchTool._to_item(hit, query) for hit in SAMPLE_HITS]++ with patch.object(HackerNewsSearchTool, "_fetch", fake_fetch):+ out = await tool.run_async(HackerNewsSearchToolInputSchema(queries=["q1", "q2"]))++ assert isinstance(out, HackerNewsSearchToolOutputSchema)+ 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, *_):+ if query == "bad":+ raise Exception("rate limited")+ return [HackerNewsSearchTool._to_item(SAMPLE_HITS[0], query)]++ with patch.object(HackerNewsSearchTool, "_fetch", fake_fetch):+ out = await tool.run_async(HackerNewsSearchToolInputSchema(queries=["bad", "good"]))++ assert len(out.results) == 1+ assert out.results[0].query == "good"+++def test_run_invokes_run_async(tool):+ sentinel = HackerNewsSearchToolOutputSchema(results=[])+ with patch.object(HackerNewsSearchTool, "run_async", AsyncMock(return_value=sentinel)):+ out = tool.run(HackerNewsSearchToolInputSchema(queries=["x"]))+ assert out is sentinel+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/atomic-forge/tools/hackernews_search/tool/hackernews_search.py b/atomic-forge/tools/hackernews_search/tool/hackernews_search.pynew file mode 100644index 0000000..e37d247--- /dev/null+++ b/atomic-forge/tools/hackernews_search/tool/hackernews_search.py@@ -0,0 +1,208 @@+import asyncio+import logging+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 HackerNewsSearchToolInputSchema(BaseIOSchema):+ """+ Search Hacker News stories, comments, Show HN posts, Ask HN posts, and polls+ via the free Algolia HN search API. No authentication required. Use this to+ find tech news, discussions, and threads on a topic.+ """++ queries: List[str] = Field(..., description="Search queries to run against Hacker News.")+ tags: Literal["story", "comment", "show_hn", "ask_hn", "poll", "front_page"] = Field(+ default="story",+ description=(+ "Type of item to search for. 'story' = regular submissions; 'comment' ="+ " HN comments; 'show_hn'/'ask_hn' = labelled posts; 'poll' = polls;"+ " 'front_page' = stories that reached the front page."+ ),+ )+ sort_by: Literal["relevance", "date"] = Field(+ default="relevance",+ description=(+ "'relevance' uses Algolia's relevance ranking; 'date' returns the newest"+ " items first (uses the search_by_date endpoint)."+ ),+ )+ max_results_per_query: int = Field(default=10, ge=1, le=50, description="Maximum results per query.")+ numeric_filters: Optional[str] = Field(+ default=None,+ description=(+ "Optional Algolia numeric filter expression to narrow results, e.g."+ " 'points>100', 'created_at_i>1700000000', or"+ " 'num_comments>50,points>20'."+ ),+ )+++####################+# OUTPUT SCHEMA(S) #+####################+class HackerNewsItem(BaseIOSchema):+ """A single Hacker News item (story, comment, or other)."""++ query: str = Field(..., description="The query that produced this item.")+ object_id: str = Field(..., description="Hacker News item id.")+ title: Optional[str] = Field(None, description="Title (stories only; absent for comments).")+ url: Optional[str] = Field(None, description="External URL submitted to HN (absent for Ask HN posts and comments).")+ hn_url: str = Field(..., description="Direct URL to the item on news.ycombinator.com.")+ author: Optional[str] = Field(None, description="Username of the poster.")+ points: Optional[int] = Field(None, description="Score of the item, if applicable.")+ num_comments: Optional[int] = Field(None, description="Number of comments on the story, if applicable.")+ created_at: Optional[str] = Field(None, description="ISO 8601 timestamp the item was posted.")+ story_text: Optional[str] = Field(None, description="Body text for Ask HN posts and self-posts (HTML).")+ comment_text: Optional[str] = Field(None, description="Body text for comments (HTML).")+ parent_id: Optional[str] = Field(None, description="Parent item id (for comments).")+ story_id: Optional[str] = Field(None, description="Story this comment belongs to (for comments).")+++class HackerNewsSearchToolOutputSchema(BaseIOSchema):+ """Output of the Hacker News search tool."""++ results: List[HackerNewsItem] = Field(..., description="Matching items across all queries.")+++#################+# CONFIGURATION #+#################+class HackerNewsSearchToolConfig(BaseToolConfig):+ """Configuration for the HackerNewsSearchTool."""++ base_url: str = Field(default="https://hn.algolia.com/api/v1", description="Algolia HN search base URL.")+ user_agent: str = Field(+ default="atomic-agents-hackernews-tool/1.0 (+https://github.com/BrainBlend-AI/atomic-agents)",+ description="User agent for HTTP requests.",+ )+ timeout: float = Field(default=15.0, ge=1.0, le=120.0, description="HTTP request timeout in seconds.")+++#####################+# MAIN TOOL & LOGIC #+#####################+class HackerNewsSearchTool(BaseTool[HackerNewsSearchToolInputSchema, HackerNewsSearchToolOutputSchema]):+ """Tool for searching Hacker News via the public Algolia API."""++ HN_ITEM_BASE = "https://news.ycombinator.com/item?id="++ def __init__(self, config: HackerNewsSearchToolConfig = HackerNewsSearchToolConfig()):+ super().__init__(config)+ self.base_url = config.base_url+ self.user_agent = config.user_agent+ self.timeout = config.timeout++ @classmethod+ def _to_item(cls, hit: dict, query: str) -> HackerNewsItem:+ object_id = str(hit.get("objectID") or hit.get("story_id") or "")+ return HackerNewsItem(+ query=query,+ object_id=object_id,+ title=hit.get("title") or hit.get("story_title"),+ url=hit.get("url") or hit.get("story_url"),+ hn_url=f"{cls.HN_ITEM_BASE}{object_id}" if object_id else "https://news.ycombinator.com/",+ author=hit.get("author"),+ points=hit.get("points"),+ num_comments=hit.get("num_comments"),+ created_at=hit.get("created_at"),+ story_text=hit.get("story_text"),+ comment_text=hit.get("comment_text"),+ parent_id=str(hit["parent_id"]) if hit.get("parent_id") is not None else None,+ story_id=str(hit["story_id"]) if hit.get("story_id") is not None else None,+ )++ async def _fetch(+ self,+ session: aiohttp.ClientSession,+ query: str,+ tags: str,+ sort_by: str,+ max_results: int,+ numeric_filters: Optional[str],+ ) -> List[HackerNewsItem]:+ endpoint = "search_by_date" if sort_by == "date" else "search"+ params = {+ "query": query,+ "tags": tags,+ "hitsPerPage": str(max_results),+ }+ if numeric_filters:+ params["numericFilters"] = numeric_filters++ async with session.get(f"{self.base_url}/{endpoint}", params=params) as resp:+ if resp.status != 200:+ raise Exception(f"HN search failed for '{query}': {resp.status} {resp.reason}")+ data = await resp.json()+ return [self._to_item(hit, query) for hit in data.get("hits", [])]++ async def run_async(self, params: HackerNewsSearchToolInputSchema) -> HackerNewsSearchToolOutputSchema:+ headers = {"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.tags,+ params.sort_by,+ params.max_results_per_query,+ params.numeric_filters,+ )+ for q in params.queries+ ]+ grouped = await asyncio.gather(*tasks, return_exceptions=True)++ results: List[HackerNewsItem] = []+ for query, group in zip(params.queries, grouped):+ if isinstance(group, Exception):+ logger.warning("HN query '%s' failed: %s", query, group)+ continue+ results.extend(group)+ return HackerNewsSearchToolOutputSchema(results=results)++ def run(self, params: HackerNewsSearchToolInputSchema) -> HackerNewsSearchToolOutputSchema:+ with ThreadPoolExecutor() as executor:+ return executor.submit(asyncio.run, self.run_async(params)).result()+++#################+# EXAMPLE USAGE #+#################+if __name__ == "__main__": # pragma: no cover+ from rich.console import Console++ console = Console()+ tool = HackerNewsSearchTool()++ output = tool.run(+ HackerNewsSearchToolInputSchema(+ queries=["atomic agents", "MCP server"],+ tags="story",+ sort_by="relevance",+ max_results_per_query=3,+ numeric_filters="points>10",+ )+ )++ for item in output.results:+ console.rule(f"[bold cyan]{item.title or item.object_id}")+ console.print(+ f"[bold]Author:[/bold] {item.author} [bold]Points:[/bold] {item.points} "+ f"[bold]Comments:[/bold] {item.num_comments}"+ )+ console.print(f"[bold]Posted:[/bold] {item.created_at}")+ console.print(f"[bold]HN URL:[/bold] {item.hn_url}")+ if item.url:+ console.print(f"[bold]Submitted URL:[/bold] {item.url}")diff --git a/atomic-forge/tools/pdf_reader/.coveragerc b/atomic-forge/tools/pdf_reader/.coveragercnew file mode 100644index 0000000..c45136e--- /dev/null+++ b/atomic-forge/tools/pdf_reader/.coveragerc@@ -0,0 +1,8 @@+[run]+source = tool+omit = */tests/*++[report]+exclude_lines =+ if __name__ == "__main__":+show_missing = Truediff --git a/atomic-forge/tools/pdf_reader/README.md b/atomic-forge/tools/pdf_reader/README.mdnew file mode 100644index 0000000..985e15b--- /dev/null+++ b/atomic-forge/tools/pdf_reader/README.md@@ -0,0 +1,60 @@+# PDF Reader Tool++## Overview+Extracts text and metadata from a PDF, given either a local file path or an HTTP(S) URL. Supports page-range filtering (e.g. `1-5`, `3`, `1,3,5-7`) and exposes per-page text plus the concatenated full text. Backed by `pypdf` — pure Python, no native binaries needed.++## Prerequisites and Dependencies+- Python 3.12 or later+- `atomic-agents`+- `pydantic`+- `pypdf`+- `requests`++## Installation+1. Use the Atomic Assembler CLI: run `atomic` and pick `pdf_reader`.+2. Or copy the `tool/` folder directly into your project.++## Input & Output Structure++### Input Schema+- `source` (str): a local file path or HTTP(S) URL pointing at a PDF.+- `page_range` (str, optional): `'1'`, `'1-5'`, `'1,3,5-7'`, etc. (1-based). Out-of-range pages are silently skipped.+- `include_metadata` (bool): default `True`.++### Output Schema+- `source` (str): echo of the input source.+- `text` (str): concatenated text for the extracted pages, separated by `\f` (form feed).+- `pages` (list[PdfPage]): per-page extracted text with 1-based `page_number`.+- `page_count` (int): number of pages extracted (after page_range filter).+- `total_page_count` (int): total pages in the source document.+- `metadata` (PdfMetadata, optional): document info dictionary.+- `error` (str, optional): set when the operation failed.++## Usage++```python+from tool.pdf_reader import PdfReaderTool, PdfReaderToolInputSchema++tool = PdfReaderTool()++# Read remote PDF, only first two pages+out = tool.run(PdfReaderToolInputSchema(+ source="https://arxiv.org/pdf/1706.03762",+ page_range="1-2",+))+print(out.text[:1000])++# Read a local PDF, every page+out = tool.run(PdfReaderToolInputSchema(source="./paper.pdf"))+```++## Notes+- The tool fails gracefully and returns `error` set in the output rather than raising.+- For URL sources, the download is hard-capped by `max_size_bytes` in the config (default 50 MB).+- Encrypted PDFs are not currently supported.++## Contributing+PRs welcome — see the main repo `CONTRIBUTING.md`.++## License+Same as the main Atomic Agents project.diff --git a/atomic-forge/tools/pdf_reader/pyproject.toml b/atomic-forge/tools/pdf_reader/pyproject.tomlnew file mode 100644index 0000000..a059b06--- /dev/null+++ b/atomic-forge/tools/pdf_reader/pyproject.toml@@ -0,0 +1,33 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["tool"]++[project]+name = "pdf-reader"+version = "1.0.0"+description = "PDF reader tool for Atomic Agents (local files or URLs, page-range support)"+readme = "README.md"+authors = [+ { name = "Kenny Vaneetvelde", email = "[email protected]" }+]+requires-python = ">=3.12"+dependencies = [+ "atomic-agents",+ "pydantic>=2.10.3,<3.0.0",+ "pypdf>=5.1.0,<7.0.0",+ "requests>=2.32.3,<3.0.0",+]++[dependency-groups]+dev = [+ "coverage>=7.6.1,<8.0.0",+ "pytest>=8.3.3,<9.0.0",+ "pytest-cov>=5.0.0,<6.0.0",+ "reportlab>=4.0.0,<5.0.0",+]++[tool.uv.sources]+atomic-agents = { workspace = true }diff --git a/atomic-forge/tools/pdf_reader/requirements.txt b/atomic-forge/tools/pdf_reader/requirements.txtnew file mode 100644index 0000000..6d1b3d2--- /dev/null+++ b/atomic-forge/tools/pdf_reader/requirements.txt@@ -0,0 +1,4 @@+atomic-agents>=2.0.0,<3.0.0+pydantic>=2.10.3,<3.0.0+pypdf>=5.1.0,<7.0.0+requests>=2.32.3,<3.0.0diff --git a/atomic-forge/tools/pdf_reader/tests/test_pdf_reader.py b/atomic-forge/tools/pdf_reader/tests/test_pdf_reader.pynew file mode 100644index 0000000..7f60889--- /dev/null+++ b/atomic-forge/tools/pdf_reader/tests/test_pdf_reader.py@@ -0,0 +1,164 @@+import io++import pytest+from reportlab.lib.pagesizes import letter+from reportlab.pdfgen import canvas++from tool.pdf_reader import (+ PdfReaderTool,+ PdfReaderToolConfig,+ PdfReaderToolInputSchema,+ PdfReaderToolOutputSchema,+)+++def _make_pdf(pages: list[str], title: str = "Test Doc", author: str = "tester") -> bytes:+ """Build a small in-memory PDF with the given text on each page."""+ buffer = io.BytesIO()+ c = canvas.Canvas(buffer, pagesize=letter)+ c.setTitle(title)+ c.setAuthor(author)+ for index, body in enumerate(pages):+ c.drawString(72, 720, f"Page {index + 1}")+ for offset, line in enumerate(body.splitlines() or [body]):+ c.drawString(72, 700 - 14 * offset, line)+ c.showPage()+ c.save()+ return buffer.getvalue()+++def sample_pdf(tmp_path):+ path = tmp_path / "sample.pdf"+ path.write_bytes(_make_pdf(["Hello World", "Second Page Content", "Third Page"]))+ return path+++def tool():+ return PdfReaderTool(config=PdfReaderToolConfig())+++def test_parse_page_range_singletons(tool):+ assert PdfReaderTool.parse_page_range("3", 10) == [3]+++def test_parse_page_range_range(tool):+ assert PdfReaderTool.parse_page_range("2-4", 10) == [2, 3, 4]+++def test_parse_page_range_mixed(tool):+ assert PdfReaderTool.parse_page_range("1,3,5-7", 10) == [1, 3, 5, 6, 7]+++def test_parse_page_range_clips_to_total(tool):+ assert PdfReaderTool.parse_page_range("1,3,5-7", 4) == [1, 3]+++def test_parse_page_range_rejects_empty(tool):+ with pytest.raises(ValueError):+ PdfReaderTool.parse_page_range("", 10)+++def test_parse_page_range_rejects_invalid(tool):+ with pytest.raises(ValueError):+ PdfReaderTool.parse_page_range("foo", 10)+ with pytest.raises(ValueError):+ PdfReaderTool.parse_page_range("5-2", 10)+ with pytest.raises(ValueError):+ PdfReaderTool.parse_page_range("0", 10)+++def test_parse_page_range_no_pages_selected(tool):+ """Range entirely outside the doc should fail loudly so the agent knows."""+ with pytest.raises(ValueError):+ PdfReaderTool.parse_page_range("8-9", 4)+++def test_run_local_file_reads_all_pages(tool, sample_pdf):+ out = tool.run(PdfReaderToolInputSchema(source=str(sample_pdf)))+ assert isinstance(out, PdfReaderToolOutputSchema)+ assert out.error is None+ assert out.total_page_count == 3+ assert out.page_count == 3+ assert "Hello World" in out.pages[0].text+ assert "Second Page Content" in out.pages[1].text+ assert "Third Page" in out.pages[2].text+ assert "Hello World" in out.text and "\f" in out.text+++def test_run_local_file_with_page_range(tool, sample_pdf):+ out = tool.run(PdfReaderToolInputSchema(source=str(sample_pdf), page_range="2"))+ assert out.error is None+ assert out.page_count == 1+ assert out.total_page_count == 3+ assert "Second Page Content" in out.pages[0].text+ # First page text should NOT appear when only page 2 was requested+ assert "Hello World" not in out.text+++def test_run_metadata_present(tool, sample_pdf):+ out = tool.run(PdfReaderToolInputSchema(source=str(sample_pdf)))+ assert out.metadata is not None+ assert out.metadata.title == "Test Doc"+ assert out.metadata.author == "tester"+++def test_run_metadata_can_be_disabled(tool, sample_pdf):+ out = tool.run(PdfReaderToolInputSchema(source=str(sample_pdf), include_metadata=False))+ assert out.metadata is None+++def test_run_missing_local_file_returns_error(tool, tmp_path):+ out = tool.run(PdfReaderToolInputSchema(source=str(tmp_path / "missing.pdf")))+ assert out.error is not None+ assert "not found" in out.error.lower()+++def test_run_invalid_page_range_returns_error(tool, sample_pdf):+ out = tool.run(PdfReaderToolInputSchema(source=str(sample_pdf), page_range="abc"))+ assert out.error is not None+++def test_run_url_source(monkeypatch, tool, sample_pdf):+ pdf_bytes = sample_pdf.read_bytes()++ class FakeResp:+ headers = {"Content-Length": str(len(pdf_bytes))}++ def raise_for_status(self):+ return None++ def iter_content(self, chunk_size):+ yield pdf_bytes++ def fake_get(url, headers, timeout, stream):+ assert url.startswith("https://example.com/")+ return FakeResp()++ import tool.pdf_reader as pdf_module++ monkeypatch.setattr(pdf_module.requests, "get", fake_get)+ out = tool.run(PdfReaderToolInputSchema(source="https://example.com/sample.pdf"))+ assert out.error is None+ assert out.total_page_count == 3+++def test_run_url_too_large_by_header(monkeypatch, tool):+ class FakeResp:+ headers = {"Content-Length": str(1_000_000_000)}++ def raise_for_status(self):+ return None++ def iter_content(self, chunk_size):+ return iter(())++ monkeypatch.setattr("tool.pdf_reader.requests.get", lambda *a, **kw: FakeResp())+ out = tool.run(PdfReaderToolInputSchema(source="https://example.com/huge.pdf"))+ assert out.error is not None+ assert "too large" in out.error.lower()+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/atomic-forge/tools/pdf_reader/tool/pdf_reader.py b/atomic-forge/tools/pdf_reader/tool/pdf_reader.pynew file mode 100644index 0000000..a112b6d--- /dev/null+++ b/atomic-forge/tools/pdf_reader/tool/pdf_reader.py@@ -0,0 +1,258 @@+import io+import re+from pathlib import Path+from typing import List, Optional, Set++import requests+from pydantic import Field+from pypdf import PdfReader++from atomic_agents import BaseIOSchema, BaseTool, BaseToolConfig+++################+# INPUT SCHEMA #+################+class PdfReaderToolInputSchema(BaseIOSchema):+ """+ Read a PDF file and extract its text. The source can be a local file path or+ an HTTP(S) URL. An optional page range limits extraction to specific pages+ (1-based, e.g. '1', '3-5', '1,3,5-7'). Use this whenever the agent needs the+ contents of a PDF — papers, reports, datasheets, etc.+ """++ source: str = Field(+ ...,+ min_length=1,+ description="Local file path (absolute or relative) or HTTP(S) URL of the PDF to read.",+ )+ page_range: Optional[str] = Field(+ default=None,+ description=(+ "Optional 1-based page-range expression to limit extraction. Single"+ " pages (`'3'`), ranges (`'1-5'`), and comma-separated combinations"+ " (`'1,3,5-7'`) are supported. When omitted, all pages are read."+ ),+ )+ include_metadata: bool = Field(default=True, description="Whether to include document metadata in the output.")+++####################+# OUTPUT SCHEMA(S) #+####################+class PdfPage(BaseIOSchema):+ """A single extracted PDF page."""++ page_number: int = Field(..., description="1-based page number in the source document.")+ text: str = Field(..., description="Extracted text for this page.")+++class PdfMetadata(BaseIOSchema):+ """Metadata fields read from the PDF document info dictionary."""++ title: Optional[str] = Field(None, description="Document title.")+ author: Optional[str] = Field(None, description="Document author.")+ subject: Optional[str] = Field(None, description="Document subject.")+ creator: Optional[str] = Field(None, description="Application that created the original document.")+ producer: Optional[str] = Field(None, description="Application that produced the PDF.")+ creation_date: Optional[str] = Field(None, description="Raw creation date string from the PDF.")+ modification_date: Optional[str] = Field(None, description="Raw modification date string from the PDF.")+++class PdfReaderToolOutputSchema(BaseIOSchema):+ """Output of the PdfReaderTool."""++ source: str = Field(..., description="The source path or URL that was read (echoed back).")+ text: str = Field(..., description="Concatenated text across all extracted pages, separated by form feeds.")+ pages: List[PdfPage] = Field(..., description="Per-page extracted text.")+ page_count: int = Field(..., description="Number of pages extracted (after page_range filtering).")+ total_page_count: int = Field(..., description="Total number of pages in the source document.")+ metadata: Optional[PdfMetadata] = Field(None, description="Document metadata, when requested.")+ error: Optional[str] = Field(None, description="Error message when the operation failed.")+++#################+# CONFIGURATION #+#################+class PdfReaderToolConfig(BaseToolConfig):+ """Configuration for the PdfReaderTool."""++ user_agent: str = Field(+ default=(+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"+ " (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"+ ),+ description="User agent for HTTP requests when the source is a URL.",+ )+ timeout: float = Field(default=30.0, ge=1.0, le=600.0, description="HTTP timeout in seconds for URL sources.")+ max_size_bytes: int = Field(+ default=50 * 1024 * 1024,+ ge=1,+ description="Maximum allowed PDF size in bytes when downloading from a URL (default 50 MB).",+ )+++#####################+# MAIN TOOL & LOGIC #+#####################+class PdfReaderTool(BaseTool[PdfReaderToolInputSchema, PdfReaderToolOutputSchema]):+ """Tool for extracting text and metadata from local or remote PDF files."""++ def __init__(self, config: PdfReaderToolConfig = PdfReaderToolConfig()):+ super().__init__(config)+ self.user_agent = config.user_agent+ self.timeout = config.timeout+ self.max_size_bytes = config.max_size_bytes++ @staticmethod+ def _is_url(source: str) -> bool:+ return bool(re.match(r"^https?://", source, re.IGNORECASE))++ def _load_bytes(self, source: str) -> bytes:+ if self._is_url(source):+ headers = {"User-Agent": self.user_agent, "Accept": "application/pdf"}+ response = requests.get(source, headers=headers, timeout=self.timeout, stream=True)+ response.raise_for_status()+ content_length = response.headers.get("Content-Length")+ if content_length and int(content_length) > self.max_size_bytes:+ raise ValueError(f"PDF too large: declared {content_length} bytes (limit {self.max_size_bytes}).")+ data = bytearray()+ for chunk in response.iter_content(chunk_size=64 * 1024):+ if chunk:+ data.extend(chunk)+ if len(data) > self.max_size_bytes:+ raise ValueError(f"PDF too large: exceeded {self.max_size_bytes} bytes during download.")+ return bytes(data)++ path = Path(source).expanduser()+ if not path.exists():+ raise FileNotFoundError(f"PDF not found at '{source}'.")+ if not path.is_file():+ raise ValueError(f"'{source}' is not a file.")+ return path.read_bytes()++ @staticmethod+ def parse_page_range(expression: str, total_pages: int) -> List[int]:+ """+ Parse a 1-based page-range expression into a sorted list of 1-based page+ numbers, clipped to ``total_pages``. Raises ValueError on malformed input.+ """+ text = expression.strip()+ if not text:+ raise ValueError("page_range cannot be empty when provided.")+ result: Set[int] = set()+ for part in text.split(","):+ chunk = part.strip()+ if not chunk:+ continue+ if "-" in chunk:+ start_str, end_str = chunk.split("-", 1)+ try:+ start = int(start_str)+ end = int(end_str)+ except ValueError as e:+ raise ValueError(f"Invalid page range segment '{chunk}'.") from e+ if start < 1 or end < 1 or end < start:+ raise ValueError(f"Invalid page range segment '{chunk}'.")+ for page in range(start, end + 1):+ if page <= total_pages:+ result.add(page)+ else:+ try:+ page = int(chunk)+ except ValueError as e:+ raise ValueError(f"Invalid page number '{chunk}'.") from e+ if page < 1:+ raise ValueError(f"Page numbers must be >= 1 (got '{chunk}').")+ if page <= total_pages:+ result.add(page)+ if not result:+ raise ValueError(f"No pages selected by '{expression}' (document has {total_pages} pages).")+ return sorted(result)++ @staticmethod+ def _format_metadata(reader: PdfReader) -> PdfMetadata:+ info = reader.metadata or {}++ def _g(key: str) -> Optional[str]:+ value = info.get(key) if hasattr(info, "get") else None+ return str(value) if value not in (None, "") else None++ return PdfMetadata(+ title=_g("/Title"),+ author=_g("/Author"),+ subject=_g("/Subject"),+ creator=_g("/Creator"),+ producer=_g("/Producer"),+ creation_date=_g("/CreationDate"),+ modification_date=_g("/ModDate"),+ )++ def run(self, params: PdfReaderToolInputSchema) -> PdfReaderToolOutputSchema:+ try:+ data = self._load_bytes(params.source)+ reader = PdfReader(io.BytesIO(data))+ total_pages = len(reader.pages)++ if params.page_range:+ page_numbers = self.parse_page_range(params.page_range, total_pages)+ else:+ page_numbers = list(range(1, total_pages + 1))++ pages: List[PdfPage] = []+ for page_number in page_numbers:+ page = reader.pages[page_number - 1]+ pages.append(PdfPage(page_number=page_number, text=page.extract_text() or ""))++ text = "\n\f\n".join(page.text for page in pages)+ metadata = self._format_metadata(reader) if params.include_metadata else None++ return PdfReaderToolOutputSchema(+ source=params.source,+ text=text,+ pages=pages,+ page_count=len(pages),+ total_page_count=total_pages,+ metadata=metadata,+ )+ except Exception as e:+ return PdfReaderToolOutputSchema(+ source=params.source,+ text="",+ pages=[],+ page_count=0,+ total_page_count=0,+ metadata=None,+ error=str(e),+ )+++#################+# EXAMPLE USAGE #+#################+if __name__ == "__main__": # pragma: no cover+ import sys++ from rich.console import Console++ # Force UTF-8 output so PDFs containing non-ASCII characters render on+ # Windows consoles with a default cp1252 codepage.+ if hasattr(sys.stdout, "reconfigure"):+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")++ console = Console()+ tool = PdfReaderTool()++ # The classic "Attention Is All You Need" paper from arXiv — a stable test PDF.+ output = tool.run(PdfReaderToolInputSchema(source="https://arxiv.org/pdf/1706.03762", page_range="1-2"))++ if output.error:+ console.print(f"[red]Error:[/red] {output.error}")+ else:+ if output.metadata:+ console.rule("[bold cyan]Metadata")+ console.print(output.metadata.model_dump())+ console.rule(f"[bold cyan]Pages {output.page_count} of {output.total_page_count}")+ snippet = output.text[:1500] + ("..." if len(output.text) > 1500 else "")+ # Print via stdout (UTF-8 reconfigured) to bypass rich's legacy-Windows code path.+ print(snippet)diff --git a/atomic-forge/tools/weather/.coveragerc b/atomic-forge/tools/weather/.coveragercnew file mode 100644index 0000000..c45136e--- /dev/null+++ b/atomic-forge/tools/weather/.coveragerc@@ -0,0 +1,8 @@+[run]+source = tool+omit = */tests/*++[report]+exclude_lines =+ if __name__ == "__main__":+show_missing = Truediff --git a/atomic-forge/tools/weather/README.md b/atomic-forge/tools/weather/README.mdnew file mode 100644index 0000000..8843b12--- /dev/null+++ b/atomic-forge/tools/weather/README.md@@ -0,0 +1,57 @@+# Weather Tool++## Overview+Looks up current conditions and a daily/hourly forecast for any location using the free [Open-Meteo](https://open-meteo.com) APIs. Accepts city names (resolved via Open-Meteo's geocoding API) or `lat,lon` pairs. No API key required.++## Prerequisites and Dependencies+- Python 3.12 or later+- `atomic-agents`+- `pydantic`+- `requests`++## Installation+1. Use the Atomic Assembler CLI: run `atomic` and pick `weather`.+2. Or copy the `tool/` folder directly into your project.++## Input & Output Structure++### Input Schema+- `location` (str): city name, `'City, Region'`, or `'lat,lon'`.+- `units` (str): `metric` (Celsius / km/h / mm) or `imperial` (Fahrenheit / mph / inches). Default `metric`.+- `forecast_days` (int): 1–16, default 3.+- `include_hourly` (bool): include hourly forecast data, default `False`.+- `language` (str): geocoder language hint (default `en`).++### Output Schema+- `location_name`, `country`, `latitude`, `longitude`, `timezone`, `units` (dict).+- `current` (`WeatherCurrent`): now-cast fields.+- `daily` (list[`WeatherDay`]): forecast buckets.+- `hourly` (list[`WeatherHour`]): only populated when `include_hourly=True`.+- `error` (str, optional): set when the operation failed.++## Usage++```python+from tool.weather import WeatherTool, WeatherToolInputSchema++tool = WeatherTool()+out = tool.run(WeatherToolInputSchema(location="Brussels", units="metric", forecast_days=3))++if out.error:+ print("Error:", out.error)+else:+ print(out.location_name, out.country)+ print("Now:", out.current.temperature, out.units["temperature"], out.current.weather_description)+ for day in out.daily:+ print(day.date, day.temperature_min, "→", day.temperature_max, day.weather_description)+```++## Notes+- Weather codes are translated to human-readable descriptions via the WMO interpretation table (Open-Meteo).+- The tool fails gracefully and returns `error` set on the output rather than raising.++## Contributing+PRs welcome — see the main repo `CONTRIBUTING.md`.++## License+Same as the main Atomic Agents project.diff --git a/atomic-forge/tools/weather/pyproject.toml b/atomic-forge/tools/weather/pyproject.tomlnew file mode 100644index 0000000..82a0a8d--- /dev/null+++ b/atomic-forge/tools/weather/pyproject.toml@@ -0,0 +1,31 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["tool"]++[project]+name = "weather-tool"+version = "1.0.0"+description = "Weather tool for Atomic Agents (Open-Meteo, no API key required)"+readme = "README.md"+authors = [+ { name = "Kenny Vaneetvelde", email = "[email protected]" }+]+requires-python = ">=3.12"+dependencies = [+ "atomic-agents",+ "pydantic>=2.10.3,<3.0.0",+ "requests>=2.32.3,<3.0.0",+]++[dependency-groups]+dev = [+ "coverage>=7.6.1,<8.0.0",+ "pytest>=8.3.3,<9.0.0",+ "pytest-cov>=5.0.0,<6.0.0",+]++[tool.uv.sources]+atomic-agents = { workspace = true }diff --git a/atomic-forge/tools/weather/requirements.txt b/atomic-forge/tools/weather/requirements.txtnew file mode 100644index 0000000..b39dd01--- /dev/null+++ b/atomic-forge/tools/weather/requirements.txt@@ -0,0 +1,3 @@+atomic-agents>=2.0.0,<3.0.0+pydantic>=2.10.3,<3.0.0+requests>=2.32.3,<3.0.0diff --git a/atomic-forge/tools/weather/tests/test_weather.py b/atomic-forge/tools/weather/tests/test_weather.pynew file mode 100644index 0000000..063da91--- /dev/null+++ b/atomic-forge/tools/weather/tests/test_weather.py@@ -0,0 +1,181 @@+from unittest.mock import MagicMock, patch++import pytest++from tool.weather import (+ WeatherTool,+ WeatherToolConfig,+ WeatherToolInputSchema,+ WeatherToolOutputSchema,+ describe_weather_code,+)+++def tool():+ return WeatherTool(config=WeatherToolConfig())+++# ----------- helpers -----------+++def test_describe_weather_code_known():+ assert describe_weather_code(0) == "Clear sky"+ assert describe_weather_code(95) == "Thunderstorm"+++def test_describe_weather_code_unknown_falls_back():+ assert describe_weather_code(7777) == "Code 7777"+++def test_describe_weather_code_none():+ assert describe_weather_code(None) is None+++def test_parse_latlon_valid():+ assert WeatherTool.parse_latlon("48.85, 2.35") == (48.85, 2.35)+ assert WeatherTool.parse_latlon("-33.8688,151.2093") == (-33.8688, 151.2093)+++def test_parse_latlon_rejects_non_numeric():+ assert WeatherTool.parse_latlon("Brussels") is None+++def test_parse_latlon_rejects_out_of_range():+ assert WeatherTool.parse_latlon("100,200") is None+++# ----------- run() with mocked HTTP -----------+++SAMPLE_GEOCODE = {+ "name": "Brussels",+ "admin1": "Brussels Capital",+ "country": "Belgium",+ "latitude": 50.8505,+ "longitude": 4.3488,+}++SAMPLE_FORECAST = {+ "timezone": "Europe/Brussels",+ "current": {+ "time": "2026-04-29T15:00",+ "temperature_2m": 14.5,+ "apparent_temperature": 13.0,+ "relative_humidity_2m": 60,+ "wind_speed_10m": 11.3,+ "wind_direction_10m": 220,+ "precipitation": 0.0,+ "weather_code": 3,+ "is_day": 1,+ },+ "daily": {+ "time": ["2026-04-29", "2026-04-30", "2026-05-01"],+ "temperature_2m_max": [16.0, 17.5, 19.0],+ "temperature_2m_min": [9.0, 10.0, 11.5],+ "apparent_temperature_max": [15.0, 16.0, 18.0],+ "apparent_temperature_min": [8.0, 9.0, 10.0],+ "precipitation_sum": [1.2, 0.0, 3.5],+ "precipitation_probability_max": [60, 10, 80],+ "weather_code": [3, 2, 65],+ "sunrise": ["2026-04-29T06:30", "2026-04-30T06:28", "2026-05-01T06:26"],+ "sunset": ["2026-04-29T20:30", "2026-04-30T20:32", "2026-05-01T20:34"],+ "wind_speed_10m_max": [18.0, 12.0, 22.0],+ },+ "hourly": {+ "time": ["2026-04-29T15:00", "2026-04-29T16:00"],+ "temperature_2m": [14.5, 14.0],+ "precipitation_probability": [40, 50],+ "weather_code": [3, 61],+ },+}+++def _mock_response(payload: dict):+ response = MagicMock()+ response.raise_for_status = MagicMock()+ response.json = MagicMock(return_value=payload)+ return response+++def test_run_resolves_city_and_returns_full_payload(tool):+ geocode_response = _mock_response({"results": [SAMPLE_GEOCODE]})+ forecast_response = _mock_response(SAMPLE_FORECAST)+ with patch.object(tool._session, "get", side_effect=[geocode_response, forecast_response]) as mock_get:+ out = tool.run(WeatherToolInputSchema(location="Brussels", units="metric", forecast_days=3))++ assert isinstance(out, WeatherToolOutputSchema)+ assert out.error is None+ assert out.location_name == "Brussels, Brussels Capital"+ assert out.country == "Belgium"+ assert out.timezone == "Europe/Brussels"+ assert out.units["temperature"] == "°C"+ assert out.current.temperature == 14.5+ assert out.current.weather_description == "Overcast"+ assert len(out.daily) == 3+ assert out.daily[0].weather_description == "Overcast"+ assert out.daily[2].weather_description == "Heavy rain"+ # hourly only when requested+ assert out.hourly == []++ # Verify the forecast call asked for the right things+ forecast_call = mock_get.call_args_list[1]+ params = forecast_call.kwargs["params"]+ assert params["temperature_unit"] == "celsius"+ assert params["wind_speed_unit"] == "kmh"+ assert params["forecast_days"] == "3"+++def test_run_includes_hourly_when_requested(tool):+ with patch.object(+ tool._session,+ "get",+ side_effect=[_mock_response({"results": [SAMPLE_GEOCODE]}), _mock_response(SAMPLE_FORECAST)],+ ):+ out = tool.run(WeatherToolInputSchema(location="Brussels", include_hourly=True))+ assert len(out.hourly) == 2+ assert out.hourly[1].weather_description == "Slight rain"+++def test_run_imperial_units(tool):+ with patch.object(+ tool._session,+ "get",+ side_effect=[_mock_response({"results": [SAMPLE_GEOCODE]}), _mock_response(SAMPLE_FORECAST)],+ ) as mock_get:+ out = tool.run(WeatherToolInputSchema(location="Brussels", units="imperial"))+ params = mock_get.call_args_list[1].kwargs["params"]+ assert params["temperature_unit"] == "fahrenheit"+ assert params["wind_speed_unit"] == "mph"+ assert params["precipitation_unit"] == "inch"+ assert out.units["temperature"] == "°F"+++def test_run_with_lat_lon_skips_geocoding(tool):+ with patch.object(tool._session, "get", side_effect=[_mock_response(SAMPLE_FORECAST)]) as mock_get:+ out = tool.run(WeatherToolInputSchema(location="50.85,4.35"))+ # Only one HTTP call (the forecast) — no geocoding+ assert mock_get.call_count == 1+ assert out.latitude == 50.85+ assert out.longitude == 4.35+ assert out.country is None # no country lookup performed+++def test_run_unknown_location_returns_error(tool):+ with patch.object(tool._session, "get", side_effect=[_mock_response({"results": []})]):+ out = tool.run(WeatherToolInputSchema(location="Nowheresville XYZ"))+ assert out.error is not None+ assert "not found" in out.error.lower()+++def test_run_http_error_returns_error(tool):+ bad_response = MagicMock()+ bad_response.raise_for_status = MagicMock(side_effect=Exception("Server is sad"))+ with patch.object(tool._session, "get", return_value=bad_response):+ out = tool.run(WeatherToolInputSchema(location="Brussels"))+ assert out.error is not None+ assert "sad" in out.error.lower()+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/atomic-forge/tools/weather/tool/weather.py b/atomic-forge/tools/weather/tool/weather.pynew file mode 100644index 0000000..e539cd1--- /dev/null+++ b/atomic-forge/tools/weather/tool/weather.py@@ -0,0 +1,402 @@+import re+from typing import Dict, List, Literal, Optional, Tuple++import requests+from pydantic import Field++from atomic_agents import BaseIOSchema, BaseTool, BaseToolConfig+++# WMO weather interpretation codes — https://open-meteo.com/en/docs#weathervariables+_WEATHER_CODE_DESCRIPTIONS = {+ 0: "Clear sky",+ 1: "Mainly clear",+ 2: "Partly cloudy",+ 3: "Overcast",+ 45: "Fog",+ 48: "Depositing rime fog",+ 51: "Light drizzle",+ 53: "Moderate drizzle",+ 55: "Dense drizzle",+ 56: "Light freezing drizzle",+ 57: "Dense freezing drizzle",+ 61: "Slight rain",+ 63: "Moderate rain",+ 65: "Heavy rain",+ 66: "Light freezing rain",+ 67: "Heavy freezing rain",+ 71: "Slight snow",+ 73: "Moderate snow",+ 75: "Heavy snow",+ 77: "Snow grains",+ 80: "Slight rain showers",+ 81: "Moderate rain showers",+ 82: "Violent rain showers",+ 85: "Slight snow showers",+ 86: "Heavy snow showers",+ 95: "Thunderstorm",+ 96: "Thunderstorm with slight hail",+ 99: "Thunderstorm with heavy hail",+}+++def describe_weather_code(code: Optional[int]) -> Optional[str]:+ """Translate a WMO weather code into a human-readable description."""+ if code is None:+ return None+ return _WEATHER_CODE_DESCRIPTIONS.get(int(code), f"Code {code}")+++################+# INPUT SCHEMA #+################+class WeatherToolInputSchema(BaseIOSchema):+ """+ Get current conditions and a daily/hourly forecast for a location. The+ location can be a city name (`'Brussels'`, `'New York'`, `'San Francisco, CA'`)+ or a latitude/longitude pair as `'lat,lon'`. Powered by the free Open-Meteo+ API — no key required.+ """++ location: str = Field(+ ...,+ description=(+ "City name (e.g. 'Tokyo', 'Brussels'), city + admin (`'Springfield,"+ " IL'`), or a `lat,lon` pair (e.g. `'48.8566,2.3522'`)."+ ),+ )+ units: Literal["metric", "imperial"] = Field(+ default="metric",+ description="'metric' uses Celsius and km/h; 'imperial' uses Fahrenheit and mph.",+ )+ forecast_days: int = Field(default=3, ge=1, le=16, description="Number of forecast days to return (1-16).")+ include_hourly: bool = Field(default=False, description="Whether to include the hourly forecast.")+ language: str = Field(default="en", description="Geocoder language hint (ISO 639-1).")+++####################+# OUTPUT SCHEMA(S) #+####################+class WeatherCurrent(BaseIOSchema):+ """Current observed weather."""++ time: str = Field(..., description="Local timestamp of the observation (ISO 8601).")+ temperature: float = Field(..., description="Temperature in the requested unit.")+ apparent_temperature: Optional[float] = Field(None, description="'Feels like' temperature.")+ humidity: Optional[int] = Field(None, description="Relative humidity, in percent.")+ wind_speed: Optional[float] = Field(None, description="Wind speed in km/h or mph (matches `units`).")+ wind_direction: Optional[int] = Field(None, description="Wind direction in degrees (0-360).")+ precipitation: Optional[float] = Field(None, description="Precipitation amount, in mm (metric) or inches (imperial).")+ weather_code: Optional[int] = Field(None, description="WMO weather code.")+ weather_description: Optional[str] = Field(None, description="Human-readable description of the weather code.")+ is_day: Optional[bool] = Field(None, description="True when the sun is up at the location.")+++class WeatherDay(BaseIOSchema):+ """Daily forecast bucket."""++ date: str = Field(..., description="Local calendar date (YYYY-MM-DD).")+ temperature_max: Optional[float] = Field(None, description="Daily maximum temperature.")+ temperature_min: Optional[float] = Field(None, description="Daily minimum temperature.")+ apparent_temperature_max: Optional[float] = Field(None, description="Daily 'feels like' max.")+ apparent_temperature_min: Optional[float] = Field(None, description="Daily 'feels like' min.")+ precipitation_sum: Optional[float] = Field(None, description="Total precipitation for the day.")+ precipitation_probability_max: Optional[int] = Field(None, description="Max probability of precipitation, percent.")+ weather_code: Optional[int] = Field(None, description="WMO weather code (representative for the day).")+ weather_description: Optional[str] = Field(None, description="Human-readable description of the day's weather code.")+ sunrise: Optional[str] = Field(None, description="Local sunrise time (ISO 8601).")+ sunset: Optional[str] = Field(None, description="Local sunset time (ISO 8601).")+ wind_speed_max: Optional[float] = Field(None, description="Maximum wind speed.")+++class WeatherHour(BaseIOSchema):+ """Hourly forecast point (only populated when include_hourly=True)."""++ time: str = Field(..., description="Local timestamp (ISO 8601).")+ temperature: Optional[float] = Field(None, description="Temperature.")+ precipitation_probability: Optional[int] = Field(None, description="Probability of precipitation, percent.")+ weather_code: Optional[int] = Field(None, description="WMO weather code.")+ weather_description: Optional[str] = Field(None, description="Human-readable description of the weather code.")+++class WeatherToolOutputSchema(BaseIOSchema):+ """Output of the WeatherTool."""++ location_name: str = Field(..., description="Resolved location label.")+ country: Optional[str] = Field(None, description="Country of the resolved location.")+ latitude: float = Field(..., description="Latitude in degrees.")+ longitude: float = Field(..., description="Longitude in degrees.")+ timezone: Optional[str] = Field(None, description="IANA timezone of the location.")+ units: Dict[str, str] = Field(+ ...,+ description=(+ "Units used for the response, keyed by variable name. Example: "+ "{'temperature': '°C', 'wind_speed': 'km/h', 'precipitation': 'mm'}."+ ),+ )+ current: Optional[WeatherCurrent] = Field(None, description="Current conditions.")+ daily: List[WeatherDay] = Field(default_factory=list, description="Daily forecast buckets.")+ hourly: List[WeatherHour] = Field(default_factory=list, description="Hourly forecast points (when requested).")+ error: Optional[str] = Field(None, description="Error message when the operation failed.")+++#################+# CONFIGURATION #+#################+class WeatherToolConfig(BaseToolConfig):+ """Configuration for the WeatherTool."""++ geocoding_url: str = Field(+ default="https://geocoding-api.open-meteo.com/v1/search",+ description="Open-Meteo geocoding endpoint.",+ )+ forecast_url: str = Field(+ default="https://api.open-meteo.com/v1/forecast",+ description="Open-Meteo forecast endpoint.",+ )+ user_agent: str = Field(+ default="atomic-agents-weather-tool/1.0 (+https://github.com/BrainBlend-AI/atomic-agents)",+ description="User agent for HTTP requests.",+ )+ timeout: float = Field(default=15.0, ge=1.0, le=120.0, description="HTTP request timeout in seconds.")+++#####################+# MAIN TOOL & LOGIC #+#####################+class WeatherTool(BaseTool[WeatherToolInputSchema, WeatherToolOutputSchema]):+ """Weather tool backed by the free Open-Meteo APIs (geocoding + forecast)."""++ LATLON_RE = re.compile(r"^\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*$")++ def __init__(self, config: WeatherToolConfig = WeatherToolConfig()):+ super().__init__(config)+ self.geocoding_url = config.geocoding_url+ self.forecast_url = config.forecast_url+ self.user_agent = config.user_agent+ self.timeout = config.timeout+ self._session = requests.Session()+ self._session.headers.update({"User-Agent": self.user_agent, "Accept": "application/json"})++ @classmethod+ def parse_latlon(cls, value: str) -> Optional[Tuple[float, float]]:+ match = cls.LATLON_RE.match(value)+ if not match:+ return None+ lat, lon = float(match.group(1)), float(match.group(2))+ if not -90 <= lat <= 90 or not -180 <= lon <= 180:+ return None+ return lat, lon++ def _geocode(self, query: str, language: str) -> dict:+ params = {"name": query, "count": "1", "language": language, "format": "json"}+ response = self._session.get(self.geocoding_url, params=params, timeout=self.timeout)+ response.raise_for_status()+ data = response.json()+ results = data.get("results") or []+ if not results:+ raise ValueError(f"Location '{query}' not found.")+ return results[0]++ def _forecast(self, latitude: float, longitude: float, units: str, days: int, hourly: bool) -> dict:+ wind_unit = "kmh" if units == "metric" else "mph"+ params = {+ "latitude": str(latitude),+ "longitude": str(longitude),+ "timezone": "auto",+ "forecast_days": str(days),+ "temperature_unit": "celsius" if units == "metric" else "fahrenheit",+ "wind_speed_unit": wind_unit,+ "precipitation_unit": "mm" if units == "metric" else "inch",+ "current": ",".join(+ [+ "temperature_2m",+ "apparent_temperature",+ "relative_humidity_2m",+ "wind_speed_10m",+ "wind_direction_10m",+ "precipitation",+ "weather_code",+ "is_day",+ ]+ ),+ "daily": ",".join(+ [+ "temperature_2m_max",+ "temperature_2m_min",+ "apparent_temperature_max",+ "apparent_temperature_min",+ "precipitation_sum",+ "precipitation_probability_max",+ "weather_code",+ "sunrise",+ "sunset",+ "wind_speed_10m_max",+ ]+ ),+ }+ if hourly:+ params["hourly"] = ",".join(+ [+ "temperature_2m",+ "precipitation_probability",+ "weather_code",+ ]+ )+ response = self._session.get(self.forecast_url, params=params, timeout=self.timeout)+ response.raise_for_status()+ return response.json()++ @staticmethod+ def _build_current(data: dict) -> Optional[WeatherCurrent]:+ current = data.get("current")+ if not current:+ return None+ return WeatherCurrent(+ time=current.get("time", ""),+ temperature=current.get("temperature_2m"),+ apparent_temperature=current.get("apparent_temperature"),+ humidity=current.get("relative_humidity_2m"),+ wind_speed=current.get("wind_speed_10m"),+ wind_direction=current.get("wind_direction_10m"),+ precipitation=current.get("precipitation"),+ weather_code=current.get("weather_code"),+ weather_description=describe_weather_code(current.get("weather_code")),+ is_day=bool(current.get("is_day")) if current.get("is_day") is not None else None,+ )++ @staticmethod+ def _build_daily(data: dict) -> List[WeatherDay]:+ daily = data.get("daily") or {}+ dates = daily.get("time") or []+ out: List[WeatherDay] = []+ for index, date in enumerate(dates):++ def _at(key: str):+ values = daily.get(key)+ return values[index] if isinstance(values, list) and index < len(values) else None++ code = _at("weather_code")+ out.append(+ WeatherDay(+ date=date,+ temperature_max=_at("temperature_2m_max"),+ temperature_min=_at("temperature_2m_min"),+ apparent_temperature_max=_at("apparent_temperature_max"),+ apparent_temperature_min=_at("apparent_temperature_min"),+ precipitation_sum=_at("precipitation_sum"),+ precipitation_probability_max=_at("precipitation_probability_max"),+ weather_code=code,+ weather_description=describe_weather_code(code),+ sunrise=_at("sunrise"),+ sunset=_at("sunset"),+ wind_speed_max=_at("wind_speed_10m_max"),+ )+ )+ return out++ @staticmethod+ def _build_hourly(data: dict) -> List[WeatherHour]:+ hourly = data.get("hourly") or {}+ times = hourly.get("time") or []+ out: List[WeatherHour] = []+ for index, time in enumerate(times):++ def _at(key: str):+ values = hourly.get(key)+ return values[index] if isinstance(values, list) and index < len(values) else None++ code = _at("weather_code")+ out.append(+ WeatherHour(+ time=time,+ temperature=_at("temperature_2m"),+ precipitation_probability=_at("precipitation_probability"),+ weather_code=code,+ weather_description=describe_weather_code(code),+ )+ )+ return out++ def run(self, params: WeatherToolInputSchema) -> WeatherToolOutputSchema:+ try:+ latlon = self.parse_latlon(params.location)+ if latlon:+ latitude, longitude = latlon+ location_name = f"{latitude:.4f}, {longitude:.4f}"+ country = None+ else:+ geocoded = self._geocode(params.location, params.language)+ latitude = geocoded["latitude"]+ longitude = geocoded["longitude"]+ location_name = geocoded.get("name", params.location)+ if geocoded.get("admin1"):+ location_name = f"{location_name}, {geocoded['admin1']}"+ country = geocoded.get("country")++ data = self._forecast(latitude, longitude, params.units, params.forecast_days, params.include_hourly)+ units_map = {+ "temperature": "°C" if params.units == "metric" else "°F",+ "wind_speed": "km/h" if params.units == "metric" else "mph",+ "precipitation": "mm" if params.units == "metric" else "in",+ }++ return WeatherToolOutputSchema(+ location_name=location_name,+ country=country,+ latitude=latitude,+ longitude=longitude,+ timezone=data.get("timezone"),+ units=units_map,+ current=self._build_current(data),+ daily=self._build_daily(data),+ hourly=self._build_hourly(data) if params.include_hourly else [],+ )+ except Exception as e:+ return WeatherToolOutputSchema(+ location_name=params.location,+ country=None,+ latitude=0.0,+ longitude=0.0,+ timezone=None,+ units={},+ current=None,+ daily=[],+ hourly=[],+ error=str(e),+ )+++#################+# EXAMPLE USAGE #+#################+if __name__ == "__main__": # pragma: no cover+ from rich.console import Console+ from rich.table import Table++ console = Console()+ tool = WeatherTool()++ output = tool.run(WeatherToolInputSchema(location="Brussels", units="metric", forecast_days=3))+ if output.error:+ console.print(f"[red]Error:[/red] {output.error}")+ else:+ console.rule(f"[bold cyan]{output.location_name} ({output.country}) — {output.timezone}")+ if output.current:+ console.print(+ f"Current: {output.current.temperature}{output.units['temperature']} "+ f"({output.current.weather_description}) — feels {output.current.apparent_temperature}, "+ f"humidity {output.current.humidity}%, wind {output.current.wind_speed} {output.units['wind_speed']}"+ )+ table = Table(title="Daily forecast")+ for col in ("Date", "Min", "Max", "Precip", "Conditions"):+ table.add_column(col)+ for day in output.daily:+ table.add_row(+ day.date,+ f"{day.temperature_min}{output.units['temperature']}",+ f"{day.temperature_max}{output.units['temperature']}",+ f"{day.precipitation_sum}{output.units['precipitation']}",+ day.weather_description or "",+ )+ console.print(table)diff --git a/atomic-forge/tools/wikipedia_search/.coveragerc b/atomic-forge/tools/wikipedia_search/.coveragercnew file mode 100644index 0000000..c45136e--- /dev/null+++ b/atomic-forge/tools/wikipedia_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/wikipedia_search/README.md b/atomic-forge/tools/wikipedia_search/README.mdnew file mode 100644index 0000000..3f0c171--- /dev/null+++ b/atomic-forge/tools/wikipedia_search/README.md@@ -0,0 +1,48 @@+# Wikipedia Search Tool++## Overview+Searches Wikipedia and returns matching articles with titles, URLs, summaries, and (optionally) the full plain-text extract for the top hit. Uses Wikipedia's free public APIs (MediaWiki + REST) — no API key required. Supports any language edition (`en`, `fr`, `de`, `nl`, `ja`, …).++## Prerequisites and Dependencies+- Python 3.12 or later+- `atomic-agents`+- `pydantic`+- `aiohttp`++## Installation+1. Use the Atomic Assembler CLI: run `atomic` and pick `wikipedia_search`.+2. Or copy the `tool/` folder directly into your project.++## Input & Output Structure++### Input Schema+- `queries` (list[str]): one or more search queries — each is searched in parallel.+- `language` (str): Wikipedia language edition (default `en`).+- `max_results_per_query` (int): how many articles to return per query (1–20, default 3).+- `full_text` (bool): when true, the top result for each query also includes the full plain-text extract.++### Output Schema+- `results`: a list of `WikipediaArticle` items. Each item has `query`, `title`, `page_url`, `summary`, `description`, `full_text` (optional), and `thumbnail_url` (optional).++## Usage++```python+from tool.wikipedia_search import WikipediaSearchTool, WikipediaSearchToolInputSchema++tool = WikipediaSearchTool()+output = tool.run(WikipediaSearchToolInputSchema(+ queries=["Atomic Agents", "Pydantic"],+ language="en",+ max_results_per_query=2,+))++for article in output.results:+ print(article.title, "->", article.page_url)+ print(article.summary)+```++## Contributing+PRs welcome — see the main repo `CONTRIBUTING.md`.++## License+Same as the main Atomic Agents project.diff --git a/atomic-forge/tools/wikipedia_search/pyproject.toml b/atomic-forge/tools/wikipedia_search/pyproject.tomlnew file mode 100644index 0000000..1a4b594--- /dev/null+++ b/atomic-forge/tools/wikipedia_search/pyproject.toml@@ -0,0 +1,32 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["tool"]++[project]+name = "wikipedia-search"+version = "1.0.0"+description = "Wikipedia search tool for Atomic Agents (free, no API key required)"+readme = "README.md"+authors = [+ { name = "Kenny Vaneetvelde", 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",+]++[tool.uv.sources]+atomic-agents = { workspace = true }diff --git a/atomic-forge/tools/wikipedia_search/requirements.txt b/atomic-forge/tools/wikipedia_search/requirements.txtnew file mode 100644index 0000000..469c7e9--- /dev/null+++ b/atomic-forge/tools/wikipedia_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/wikipedia_search/tests/test_wikipedia_search.py b/atomic-forge/tools/wikipedia_search/tests/test_wikipedia_search.pynew file mode 100644index 0000000..2ef032b--- /dev/null+++ b/atomic-forge/tools/wikipedia_search/tests/test_wikipedia_search.py@@ -0,0 +1,137 @@+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from tool.wikipedia_search import (+ WikipediaSearchTool,+ WikipediaSearchToolConfig,+ WikipediaSearchToolInputSchema,+ WikipediaSearchToolOutputSchema,+)+++def tool():+ return WikipediaSearchTool(config=WikipediaSearchToolConfig())+++def test_input_schema_rejects_invalid_max_results():+ from pydantic import ValidationError++ with pytest.raises(ValidationError):+ WikipediaSearchToolInputSchema(queries=["x"], max_results_per_query=0)+ with pytest.raises(ValidationError):+ WikipediaSearchToolInputSchema(queries=["x"], max_results_per_query=21)+++async def test_run_async_returns_articles(tool):+ """Mock all three coroutines and assert the output schema is built correctly."""++ async def fake_search_titles(self, session, query, language, limit):+ return ["Atomic Agents", "Atomic Theory"]++ async def fake_fetch_summary(self, session, title, language):+ return {+ "title": title,+ "extract": f"Summary of {title}.",+ "description": f"desc {title}",+ "content_urls": {"desktop": {"page": f"https://{language}.wikipedia.org/wiki/{title.replace(' ', '_')}"}},+ "thumbnail": {"source": "https://example.com/thumb.png"},+ }++ async def fake_fetch_full_extract(self, session, title, language):+ return f"FULL: {title}"++ with (+ patch.object(WikipediaSearchTool, "_search_titles", fake_search_titles),+ patch.object(WikipediaSearchTool, "_fetch_summary", fake_fetch_summary),+ patch.object(WikipediaSearchTool, "_fetch_full_extract", fake_fetch_full_extract),+ ):+ result = await tool.run_async(+ WikipediaSearchToolInputSchema(queries=["Atomic"], full_text=True, max_results_per_query=2)+ )++ assert isinstance(result, WikipediaSearchToolOutputSchema)+ assert len(result.results) == 2+ assert result.results[0].title == "Atomic Agents"+ assert result.results[0].full_text == "FULL: Atomic Agents" # only top result has full_text+ assert result.results[1].full_text is None+ assert result.results[0].page_url.endswith("Atomic_Agents")+++async def test_run_async_skips_failing_query(tool):+ async def fake_search_titles(self, session, query, language, limit):+ if query == "good":+ return ["Page A"]+ raise Exception("boom")++ async def fake_fetch_summary(self, session, title, language):+ return {"title": title, "extract": "ok", "content_urls": {"desktop": {"page": "https://x"}}}++ with (+ patch.object(WikipediaSearchTool, "_search_titles", fake_search_titles),+ patch.object(WikipediaSearchTool, "_fetch_summary", fake_fetch_summary),+ ):+ out = await tool.run_async(WikipediaSearchToolInputSchema(queries=["good", "bad"]))++ assert len(out.results) == 1+ assert out.results[0].query == "good"+++async def test_run_async_skips_404_summaries(tool):+ async def fake_search_titles(self, session, query, language, limit):+ return ["Real Page", "Missing Page"]++ async def fake_fetch_summary(self, session, title, language):+ if title == "Missing Page":+ return None+ return {"title": title, "extract": "ok", "content_urls": {"desktop": {"page": "https://x"}}}++ with (+ patch.object(WikipediaSearchTool, "_search_titles", fake_search_titles),+ patch.object(WikipediaSearchTool, "_fetch_summary", fake_fetch_summary),+ ):+ out = await tool.run_async(WikipediaSearchToolInputSchema(queries=["q"], max_results_per_query=2))++ assert len(out.results) == 1+ assert out.results[0].title == "Real Page"+++def test_run_invokes_run_async_in_thread(tool):+ """run() should drive run_async in a worker thread and return its result."""+ sentinel = WikipediaSearchToolOutputSchema(results=[])+ fake_run_async = AsyncMock(return_value=sentinel)+ with patch.object(WikipediaSearchTool, "run_async", fake_run_async):+ out = tool.run(WikipediaSearchToolInputSchema(queries=["x"]))+ assert out is sentinel+++async def test_search_titles_raises_on_non_200(tool):+ """Direct test of _search_titles error path."""++ class Resp:+ status = 500+ reason = "boom"++ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return None++ async def json(self):+ return {}++ session = MagicMock()+ session.get = MagicMock(return_value=Resp())++ with pytest.raises(Exception, match="Wikipedia search failed"):+ await tool._search_titles(session, "q", "en", 1)+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/atomic-forge/tools/wikipedia_search/tool/wikipedia_search.py b/atomic-forge/tools/wikipedia_search/tool/wikipedia_search.pynew file mode 100644index 0000000..9cdebaa--- /dev/null+++ b/atomic-forge/tools/wikipedia_search/tool/wikipedia_search.py@@ -0,0 +1,234 @@+import asyncio+import logging+from concurrent.futures import ThreadPoolExecutor+from typing import List, Optional++import aiohttp+from pydantic import Field++from atomic_agents import BaseIOSchema, BaseTool, BaseToolConfig+++logger = logging.getLogger(__name__)+++################+# INPUT SCHEMA #+################+class WikipediaSearchToolInputSchema(BaseIOSchema):+ """+ Schema for searching Wikipedia. Returns matching articles with titles, URLs,+ and plain-text summaries. Use this whenever you need encyclopedic background on a+ person, place, concept, or event. Free public API; no key required.+ """++ queries: List[str] = Field(..., description="One or more search queries to look up on Wikipedia.")+ language: str = Field(+ default="en",+ description="Wikipedia language edition code (e.g. 'en', 'fr', 'de', 'nl', 'ja').",+ )+ max_results_per_query: int = Field(+ default=3,+ ge=1,+ le=20,+ description="Maximum number of articles to return per query.",+ )+ full_text: bool = Field(+ default=False,+ description=(+ "When true, fetch the full plain-text extract for the top result of each"+ " query in addition to the short summary. Costs an extra API call per"+ " query, so leave this off unless you need full article content."+ ),+ )+++####################+# OUTPUT SCHEMA(S) #+####################+class WikipediaArticle(BaseIOSchema):+ """A single Wikipedia article result."""++ query: str = Field(..., description="The query that produced this result.")+ title: str = Field(..., description="The article title.")+ page_url: str = Field(..., description="Canonical URL of the article on Wikipedia.")+ summary: str = Field(..., description="Plain-text lead summary of the article.")+ description: Optional[str] = Field(None, description="Short description (one-liner) for the article, when available.")+ full_text: Optional[str] = Field(+ None, description="Full plain-text article content, populated only when `full_text` was requested."+ )+ thumbnail_url: Optional[str] = Field(None, description="URL of a thumbnail image for the article, when available.")+++class WikipediaSearchToolOutputSchema(BaseIOSchema):+ """Output of the Wikipedia search tool."""++ results: List[WikipediaArticle] = Field(+ ..., description="Articles returned across all queries, in best-match order per query."+ )+++#################+# CONFIGURATION #+#################+class WikipediaSearchToolConfig(BaseToolConfig):+ """Configuration for the WikipediaSearchTool."""++ user_agent: str = Field(+ default="atomic-agents-wikipedia-tool/1.0 (+https://github.com/BrainBlend-AI/atomic-agents)",+ description="User agent for Wikipedia API requests. Wikipedia asks for a descriptive UA.",+ )+ timeout: float = Field(default=15.0, ge=1.0, le=120.0, description="HTTP request timeout in seconds.")+++#####################+# MAIN TOOL & LOGIC #+#####################+class WikipediaSearchTool(BaseTool[WikipediaSearchToolInputSchema, WikipediaSearchToolOutputSchema]):+ """Tool for searching Wikipedia articles via the public MediaWiki and REST APIs."""++ def __init__(self, config: WikipediaSearchToolConfig = WikipediaSearchToolConfig()):+ super().__init__(config)+ self.user_agent = config.user_agent+ self.timeout = config.timeout++ @staticmethod+ def _api_base(language: str) -> str:+ return f"https://{language}.wikipedia.org"++ async def _search_titles(self, session: aiohttp.ClientSession, query: str, language: str, limit: int) -> List[str]:+ """Call MediaWiki search API and return a list of matching article titles."""+ params = {+ "action": "query",+ "list": "search",+ "srsearch": query,+ "srlimit": str(limit),+ "format": "json",+ "utf8": "",+ }+ async with session.get(f"{self._api_base(language)}/w/api.php", params=params) as resp:+ if resp.status != 200:+ raise Exception(f"Wikipedia search failed for '{query}': {resp.status} {resp.reason}")+ data = await resp.json()+ return [hit["title"] for hit in data.get("query", {}).get("search", [])]++ async def _fetch_summary(self, session: aiohttp.ClientSession, title: str, language: str) -> Optional[dict]:+ """Fetch the page summary via the REST API. Returns None if not found."""+ url = f"{self._api_base(language)}/api/rest_v1/page/summary/{aiohttp.helpers.quote(title, safe='')}"+ async with session.get(url) as resp:+ if resp.status == 404:+ return None+ if resp.status != 200:+ raise Exception(f"Wikipedia summary failed for '{title}': {resp.status} {resp.reason}")+ return await resp.json()++ async def _fetch_full_extract(self, session: aiohttp.ClientSession, title: str, language: str) -> Optional[str]:+ """Fetch the full plain-text extract for an article."""+ params = {+ "action": "query",+ "prop": "extracts",+ "explaintext": "true",+ "titles": title,+ "format": "json",+ "redirects": "1",+ "utf8": "",+ }+ async with session.get(f"{self._api_base(language)}/w/api.php", params=params) as resp:+ if resp.status != 200:+ raise Exception(f"Wikipedia extract failed for '{title}': {resp.status} {resp.reason}")+ data = await resp.json()+ pages = data.get("query", {}).get("pages", {})+ for page in pages.values():+ extract = page.get("extract")+ if extract:+ return extract+ return None++ async def _process_query(+ self,+ session: aiohttp.ClientSession,+ query: str,+ language: str,+ limit: int,+ full_text: bool,+ ) -> List[WikipediaArticle]:+ titles = await self._search_titles(session, query, language, limit)+ articles: List[WikipediaArticle] = []+ for index, title in enumerate(titles):+ try:+ summary_data = await self._fetch_summary(session, title, language)+ except Exception as e:+ logger.warning("Failed to fetch summary for '%s': %s", title, e)+ continue+ if not summary_data:+ continue+ full = None+ if full_text and index == 0:+ try:+ full = await self._fetch_full_extract(session, title, language)+ except Exception as e:+ logger.warning("Failed to fetch full extract for '%s': %s", title, e)+ page_url = (+ summary_data.get("content_urls", {}).get("desktop", {}).get("page")+ or f"{self._api_base(language)}/wiki/{title.replace(' ', '_')}"+ )+ articles.append(+ WikipediaArticle(+ query=query,+ title=summary_data.get("title", title),+ page_url=page_url,+ summary=summary_data.get("extract", ""),+ description=summary_data.get("description"),+ full_text=full,+ thumbnail_url=(summary_data.get("thumbnail") or {}).get("source"),+ )+ )+ return articles++ async def run_async(self, params: WikipediaSearchToolInputSchema) -> WikipediaSearchToolOutputSchema:+ headers = {"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._process_query(session, q, params.language, params.max_results_per_query, params.full_text)+ for q in params.queries+ ]+ grouped = await asyncio.gather(*tasks, return_exceptions=True)++ results: List[WikipediaArticle] = []+ for query, group in zip(params.queries, grouped):+ if isinstance(group, Exception):+ logger.warning("Query '%s' failed: %s", query, group)+ continue+ results.extend(group)+ return WikipediaSearchToolOutputSchema(results=results)++ def run(self, params: WikipediaSearchToolInputSchema) -> WikipediaSearchToolOutputSchema:+ with ThreadPoolExecutor() as executor:+ return executor.submit(asyncio.run, self.run_async(params)).result()+++#################+# EXAMPLE USAGE #+#################+if __name__ == "__main__": # pragma: no cover+ from rich.console import Console++ console = Console()+ tool = WikipediaSearchTool()++ output = tool.run(+ WikipediaSearchToolInputSchema(+ queries=["Atomic Agents", "Pydantic"],+ language="en",+ max_results_per_query=2,+ full_text=False,+ )+ )++ for article in output.results:+ console.rule(f"[bold cyan]{article.query} -> {article.title}")+ console.print(f"[bold]URL:[/bold] {article.page_url}")+ if article.description:+ console.print(f"[bold]Description:[/bold] {article.description}")+ console.print(article.summary)diff --git a/claude-plugin/atomic-agents/skills/framework/references/tools.md b/claude-plugin/atomic-agents/skills/framework/references/tools.mdindex 7500a92..bf917be 100644--- a/claude-plugin/atomic-agents/skills/framework/references/tools.md+++ b/claude-plugin/atomic-agents/skills/framework/references/tools.md@@ -182,7 +182,7 @@ Full client-side example: `atomic-examples/mcp-agent/example-client/`. A matchin## Prebuilt tools (Atomic Forge)-The `atomic-forge` workspace ships production-ready tools: calculator, SearXNG, Tavily, Bocha, YouTube transcript scraper, webpage scraper, and more. Install into a project with:+The `atomic-forge` workspace ships production-ready tools: arXiv search, Bocha, calculator, datetime, Fía Signals, Hacker News search, PDF reader, SearXNG, Tavily, weather (Open-Meteo), webpage scraper, Wikipedia search, and YouTube transcript scraper. Install into a project with:```bashatomic download calculatordiff --git a/docs/guides/tools.md b/docs/guides/tools.mdindex 02a9ef8..93b052c 100644--- a/docs/guides/tools.md+++ b/docs/guides/tools.md@@ -145,13 +145,19 @@ Tools themselves are distributed via the **Atomic Forge** — a registry of stanThe Atomic Forge ships with several pre-built tools:+- **arXiv Search**: Search arXiv for academic papers (free public API)+- **BoCha Search**: Web search- **Calculator**: Perform mathematical calculations+- **DateTime**: Timezone-aware now / parse / convert / shift / diff (no key required)+- **Fía Signals**: Crypto market intelligence — market regime, trading signals, DeFi yields, gas prices, Solana trending tokens, and wallet risk scoring+- **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- **Tavily Search**: AI-powered web search-- **YouTube Transcript Scraper**: Extract transcripts from YouTube videos+- **Weather**: Current conditions and daily/hourly forecasts via Open-Meteo (no key required)- **Webpage Scraper**: Extract content from web pages-- **BoCha Search**: Web search-- **Fía Signals**: Crypto market intelligence — market regime, trading signals, DeFi yields, gas prices, Solana trending tokens, and wallet risk scoring+- **Wikipedia Search**: Search Wikipedia in any language edition (no key required)+- **YouTube Transcript Scraper**: Extract transcripts from YouTube videos### Downloading a tooldiff --git a/uv.lock b/uv.lockindex 5132d9f..6989d7d 100644--- a/uv.lock+++ b/uv.lock@@ -8,26 +8,33 @@ resolution-markers = [[manifest]members = [+ "arxiv-search","atomic-agents","basic-multimodal","basic-pdf-analysis","bocha-search","calculator",+ "datetime-tool","deep-research","dspy-integration","example-client","example-mcp-server","fastapi-memory",+ "fia-signals",+ "hackernews-search","hooks-example","nested-multimodal","orchestration-agent",+ "pdf-reader","progressive-disclosure","quickstart","rag-chatbot","searxng-search","tavily-search",+ "weather-tool","web-search-agent","webpage-scraper",+ "wikipedia-search","youtube-summarizer","youtube-to-recipe","youtube-transcript-scraper",@@ -180,6 +187,39 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/15/b3/9b1a8074496371342ec1e796a96f99c82c945a339cd81a8e73de28b4cf9e/anyio-4.11.0-py3-none-any.whl", hash = "sha256:0287e96f4d26d4149305414d4e3bc32f0dcd0862365a4bddea19d7a1ec38c4fc", size = 109097, upload-time = "2025-09-23T09:19:10.601Z" },]+[[package]]+name = "arxiv-search"+version = "1.0.0"+source = { editable = "atomic-forge/tools/arxiv_search" }+dependencies = [+ { name = "aiohttp" },+ { name = "atomic-agents" },+ { name = "pydantic" },+]++[package.dev-dependencies]+dev = [+ { name = "coverage" },+ { name = "pytest" },+ { name = "pytest-asyncio" },+ { name = "pytest-cov" },+]++[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" },+]+[[package]]name = "asyncer"version = "0.0.8"@@ -194,7 +234,7 @@ wheels = [[[package]]name = "atomic-agents"-version = "2.7.4"+version = "2.7.5"source = { editable = "." }dependencies = [{ name = "gitpython" },@@ -867,6 +907,37 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/87/22/f020c047ae1346613db9322638186468238bcfa8849b4668a22b97faad65/dateparser-1.2.2-py3-none-any.whl", hash = "sha256:5a5d7211a09013499867547023a2a0c91d5a27d15dd4dbcea676ea9fe66f2482", size = 315453, upload-time = "2025-06-26T09:29:21.412Z" },]+[[package]]+name = "datetime-tool"+version = "1.0.0"+source = { editable = "atomic-forge/tools/datetime_tool" }+dependencies = [+ { name = "atomic-agents" },+ { name = "pydantic" },+ { name = "tzdata" },+]++[package.dev-dependencies]+dev = [+ { name = "coverage" },+ { name = "pytest" },+ { name = "pytest-cov" },+]++[package.metadata]+requires-dist = [+ { name = "atomic-agents", editable = "." },+ { name = "pydantic", specifier = ">=2.10.3,<3.0.0" },+ { name = "tzdata", specifier = ">=2024.1" },+]++[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-cov", specifier = ">=5.0.0,<6.0.0" },+]+[[package]]name = "deep-research"version = "0.1.0"@@ -1208,6 +1279,45 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/22/1d/5573ef3624ceb7abf4a46073d3554e37191c868abc3aecd5289a72f9810a/fastuuid-0.14.0-cp313-cp313-win_amd64.whl", hash = "sha256:0df14e92e7ad3276327631c9e7cec09e32572ce82089c55cb1bb8df71cf394ed", size = 156539, upload-time = "2025-10-19T22:33:35.898Z" },]+[[package]]+name = "fia-signals"+version = "1.0.0"+source = { editable = "atomic-forge/tools/fia_signals" }+dependencies = [+ { name = "atomic-agents" },+ { name = "pydantic" },+ { name = "requests" },+]++[package.dev-dependencies]+dev = [+ { name = "coverage" },+ { name = "httpx" },+ { name = "pytest" },+ { name = "pytest-asyncio" },+ { name = "pytest-cov" },+ { name = "python-dotenv" },+ { name = "rich" },+]++[package.metadata]+requires-dist = [+ { name = "atomic-agents", editable = "." },+ { name = "pydantic", specifier = ">=2.10.3,<3.0.0" },+ { name = "requests", specifier = ">=2.28.0,<3.0.0" },+]++[package.metadata.requires-dev]+dev = [+ { name = "coverage", specifier = ">=7.6.1,<8.0.0" },+ { name = "httpx", specifier = ">=0.28.0,<1.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 = "filelock"version = "3.20.0"@@ -1518,6 +1628,39 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/69/b2/119f6e6dcbd96f9069ce9a2665e0146588dc9f88f29549711853645e736a/h2-4.3.0-py3-none-any.whl", hash = "sha256:c438f029a25f7945c69e0ccf0fb951dc3f73a5f6412981daee861431b70e2bdd", size = 61779, upload-time = "2025-08-23T18:12:17.779Z" },]+[[package]]+name = "hackernews-search"+version = "1.0.0"+source = { editable = "atomic-forge/tools/hackernews_search" }+dependencies = [+ { name = "aiohttp" },+ { name = "atomic-agents" },+ { name = "pydantic" },+]++[package.dev-dependencies]+dev = [+ { name = "coverage" },+ { name = "pytest" },+ { name = "pytest-asyncio" },+ { name = "pytest-cov" },+]++[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" },+]+[[package]]name = "hf-xet"version = "1.2.0"@@ -2730,6 +2873,41 @@ dependencies = [[package.metadata]requires-dist = [{ name = "fastmcp", specifier = ">=2.0.0" }]+[[package]]+name = "pdf-reader"+version = "1.0.0"+source = { editable = "atomic-forge/tools/pdf_reader" }+dependencies = [+ { name = "atomic-agents" },+ { name = "pydantic" },+ { name = "pypdf" },+ { name = "requests" },+]++[package.dev-dependencies]+dev = [+ { name = "coverage" },+ { name = "pytest" },+ { name = "pytest-cov" },+ { name = "reportlab" },+]++[package.metadata]+requires-dist = [+ { name = "atomic-agents", editable = "." },+ { name = "pydantic", specifier = ">=2.10.3,<3.0.0" },+ { name = "pypdf", specifier = ">=5.1.0,<7.0.0" },+ { name = "requests", specifier = ">=2.32.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-cov", specifier = ">=5.0.0,<6.0.0" },+ { name = "reportlab", specifier = ">=4.0.0,<5.0.0" },+]+[[package]]name = "pdoc3"version = "0.11.6"@@ -3256,6 +3434,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/10/5e/1aa9a93198c6b64513c9d7752de7422c06402de6600a8767da1524f9570b/pyparsing-3.2.5-py3-none-any.whl", hash = "sha256:e38a4f02064cf41fe6593d328d0512495ad1f3d8a91c4f73fc401b3079a59a5e", size = 113890, upload-time = "2025-09-21T04:11:04.117Z" },]+[[package]]+name = "pypdf"+version = "6.10.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/7b/3f/9f2167401c2e94833ca3b69535bad89e533b5de75fefe4197a2c224baec2/pypdf-6.10.2.tar.gz", hash = "sha256:7d09ce108eff6bf67465d461b6ef352dcb8d84f7a91befc02f904455c6eea11d", size = 5315679, upload-time = "2026-04-15T16:37:36.978Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/0c/d6/1d5c60cc17bbdf37c1552d9c03862fc6d32c5836732a0415b2d637edc2d0/pypdf-6.10.2-py3-none-any.whl", hash = "sha256:aa53be9826655b51c96741e5d7983ca224d898ac0a77896e64636810517624aa", size = 336308, upload-time = "2026-04-15T16:37:34.851Z" },+]+[[package]]name = "pyperclip"version = "1.11.0"@@ -3554,6 +3741,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/8d/d0/2afc6f8e94e2b64bfb738a7c2b6387ac1699f09f032d363ed9447fd2bb57/regex-2025.11.3-cp313-cp313t-win_arm64.whl", hash = "sha256:df9eb838c44f570283712e7cff14c16329a9f0fb19ca492d21d4b7528ee6821e", size = 271469, upload-time = "2025-11-03T21:32:48.026Z" },]+[[package]]+name = "reportlab"+version = "4.4.10"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "charset-normalizer" },+ { name = "pillow" },+]+sdist = { url = "https://files.pythonhosted.org/packages/48/57/28bfbf0a775b618b6e4d854ef8dd3f5c8988e5d614d8898703502a35f61c/reportlab-4.4.10.tar.gz", hash = "sha256:5cbbb34ac3546039d0086deb2938cdec06b12da3cdb836e813258eb33cd28487", size = 3714962, upload-time = "2026-02-12T10:45:21.325Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/8a/2e/e1798b8b248e1517e74c6cdf10dd6edd485044e7edf46b5f11ffcc5a0add/reportlab-4.4.10-py3-none-any.whl", hash = "sha256:5abc815746ae2bc44e7ff25db96814f921349ca814c992c7eac3c26029bf7c24", size = 1955400, upload-time = "2026-02-12T10:45:18.828Z" },+]+[[package]]name = "requests"version = "2.32.5"@@ -4351,6 +4551,37 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/28/9a/a785356fccf9fae84c0cc90570f11702ae9571036fb25932f1242c82191c/watchfiles-1.1.1-cp313-cp313t-musllinux_1_1_x86_64.whl", hash = "sha256:f9a2ae5c91cecc9edd47e041a930490c31c3afb1f5e6d71de3dc671bfaca02bf", size = 622208, upload-time = "2025-10-14T15:05:25.45Z" },]+[[package]]+name = "weather-tool"+version = "1.0.0"+source = { editable = "atomic-forge/tools/weather" }+dependencies = [+ { name = "atomic-agents" },+ { name = "pydantic" },+ { name = "requests" },+]++[package.dev-dependencies]+dev = [+ { name = "coverage" },+ { name = "pytest" },+ { name = "pytest-cov" },+]++[package.metadata]+requires-dist = [+ { name = "atomic-agents", editable = "." },+ { name = "pydantic", specifier = ">=2.10.3,<3.0.0" },+ { name = "requests", specifier = ">=2.32.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-cov", specifier = ">=5.0.0,<6.0.0" },+]+[[package]]name = "web-search-agent"version = "1.0.0"@@ -4459,6 +4690,39 @@ version = "3.2"source = { registry = "https://pypi.org/simple" }sdist = { url = "https://files.pythonhosted.org/packages/47/6a/62e288da7bcda82b935ff0c6cfe542970f04e29c756b0e147251b2fb251f/wget-3.2.zip", hash = "sha256:35e630eca2aa50ce998b9b1a127bb26b30dfee573702782aa982f875e3f16061", size = 10857, upload-time = "2015-10-22T15:26:37.51Z" }+[[package]]+name = "wikipedia-search"+version = "1.0.0"+source = { editable = "atomic-forge/tools/wikipedia_search" }+dependencies = [+ { name = "aiohttp" },+ { name = "atomic-agents" },+ { name = "pydantic" },+]++[package.dev-dependencies]+dev = [+ { name = "coverage" },+ { name = "pytest" },+ { name = "pytest-asyncio" },+ { name = "pytest-cov" },+]++[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" },+]+[[package]]name = "xmltodict"version = "1.0.4"