Building AI agents, atomically
Move tools, remove old tools (they will be re-added later), update tool structure guide
KennyVaneetvelde944c5804f075
diff --git a/atomic-agents/atomic_agents/lib/tools/__init__.py b/atomic-agents/atomic_agents/lib/tools/__init__.pydeleted file mode 100644index e69de29..0000000diff --git a/atomic-agents/atomic_agents/lib/tools/calculator_tool.py b/atomic-agents/atomic_agents/lib/tools/calculator_tool.pydeleted file mode 100644index cc6b3cb..0000000--- a/atomic-agents/atomic_agents/lib/tools/calculator_tool.py+++ /dev/null@@ -1,82 +0,0 @@-from pydantic import Field-from rich.console import Console-from sympy import sympify--from atomic_agents.agents.base_agent import BaseIOSchema-from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfig---################-# INPUT SCHEMA #-################-class CalculatorToolInputSchema(BaseIOSchema):- """- Tool for performing calculations. Supports basic arithmetic operations- like addition, subtraction, multiplication, and division, but also more- complex operations like exponentiation and trigonometric functions.- Use this tool to evaluate mathematical expressions.- """-- expression: str = Field(..., description="Mathematical expression to evaluate. For example, '2 + 2'.")---####################-# OUTPUT SCHEMA(S) #-####################-class CalculatorToolOutputSchema(BaseIOSchema):- """This schema defines the output of the CalculatorTool."""-- result: str = Field(..., description="Result of the calculation.")---##############-# TOOL LOGIC #-##############-class CalculatorToolConfig(BaseToolConfig):- pass---class CalculatorTool(BaseTool):- """- Tool for performing calculations based on the provided mathematical expression.-- Attributes:- input_schema (CalculatorToolInputSchema): The schema for the input data.- output_schema (CalculatorToolOutputSchema): The schema for the output data.- """-- input_schema = CalculatorToolInputSchema- output_schema = CalculatorToolOutputSchema-- def __init__(self, config: CalculatorToolConfig = CalculatorToolConfig()):- """- Initializes the CalculatorTool.-- Args:- config (CalculatorToolConfig): Configuration for the tool.- """- super().__init__(config)-- def run(self, params: CalculatorToolInputSchema) -> CalculatorToolOutputSchema:- """- Runs the CalculatorTool with the given parameters.-- Args:- params (CalculatorToolInputSchema): The input parameters for the tool, adhering to the input schema.-- Returns:- CalculatorToolOutputSchema: The output of the tool, adhering to the output schema.- """- # Explicitly convert the string form of the expression- parsed_expr = sympify(str(params.expression))- # Evaluate the expression numerically- result = parsed_expr.evalf()- return CalculatorToolOutputSchema(result=str(result))---#################-# EXAMPLE USAGE #-#################-if __name__ == "__main__":- rich_console = Console()- rich_console.print(CalculatorTool().run(CalculatorToolInputSchema(expression="2 + 2")))diff --git a/atomic-agents/atomic_agents/lib/tools/content_scraping_tool.py b/atomic-agents/atomic_agents/lib/tools/content_scraping_tool.pydeleted file mode 100644index e60389f..0000000--- a/atomic-agents/atomic_agents/lib/tools/content_scraping_tool.py+++ /dev/null@@ -1,132 +0,0 @@-import os-from typing import Optional--import instructor-import openai-import requests-from pydantic import Field-from rich.console import Console-from rich.markdown import Markdown--from atomic_agents.agents.base_agent import BaseIOSchema-from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfig-from atomic_agents.lib.utils.scraping.pdf_to_markdown import PdfToMarkdownConverter-from atomic_agents.lib.utils.scraping.url_to_markdown import UrlToMarkdownConverter--################-# INPUT SCHEMA #-################---class ContentScrapingToolInputSchema(BaseIOSchema):- """- Tool for scraping web pages or PDFs and converting content to markdown- in order to extract information or summarize the content.- """-- url: str = Field(..., description="URL of the web page or PDF to scrape.")---####################-# OUTPUT SCHEMA(S) #-####################---class ContentScrapingToolOutputSchema(BaseIOSchema):- """This schema defines the output of the ContentScrapingTool."""-- content: str- metadata: Optional[dict] = None---##############-# TOOL LOGIC #-##############-class ContentScrapingToolConfig(BaseToolConfig):- pass---class ContentScrapingTool(BaseTool):- """- Tool for scraping web pages or PDFs and converting content to markdown.-- Attributes:- input_schema (ContentScrapingToolInputSchema): The schema for the input data.- output_schema (ContentScrapingToolOutputSchema): The schema for the output data.- """-- input_schema = ContentScrapingToolInputSchema- output_schema = ContentScrapingToolOutputSchema-- def __init__(self, config: ContentScrapingToolConfig = ContentScrapingToolConfig()):- """- Initializes the ContentScrapingTool.-- Args:- config (ContentScrapingToolConfig): Configuration for the tool.- """- super().__init__(config)-- def run(self, params: ContentScrapingToolInputSchema) -> ContentScrapingToolOutputSchema:- """- Runs the ContentScrapingTool with the given parameters.-- Args:- params (ContentScrapingToolInputSchema): The input parameters for the tool, adhering to the input schema.-- Returns:- ContentScrapingToolOutputSchema: The output of the tool, adhering to the output schema.- """- url = params.url- response = requests.head(url)- content_type = response.headers.get("Content-Type", "")-- if "application/pdf" in content_type:- document = PdfToMarkdownConverter.convert(url=url)- else:- document = UrlToMarkdownConverter.convert(url=url)-- return ContentScrapingToolOutputSchema(content=document.content, metadata=document.metadata.model_dump())---#################-# EXAMPLE USAGE #-#################-if __name__ == "__main__":- rich_console = Console()-- client = instructor.from_openai(openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_BASE_URL")))-- #################- # TEST WEB PAGE #- #################- result = client.chat.completions.create(- model="gpt-4o-mini",- response_model=ContentScrapingTool.input_schema,- messages=[- {- "role": "user",- "content": "Scrape the content of https://brainblendai.com",- }- ],- )-- output = ContentScrapingTool().run(result)- rich_console.print(Markdown(output.content))-- ################- # TEST PDF URL #- ################- result = client.chat.completions.create(- model="gpt-4o-mini",- response_model=ContentScrapingTool.input_schema,- messages=[- {- "role": "user",- "content": "Scrape the content of https://pdfobject.com/pdf/sample.pdf",- }- ],- )-- output = ContentScrapingTool().run(result)- rich_console.print(Markdown(output.content))diff --git a/atomic-agents/atomic_agents/lib/tools/search/searxng_tool.py b/atomic-agents/atomic_agents/lib/tools/search/searxng_tool.pydeleted file mode 100644index 137fbc5..0000000--- a/atomic-agents/atomic_agents/lib/tools/search/searxng_tool.py+++ /dev/null@@ -1,211 +0,0 @@-import os-from typing import List, Literal, Optional-import asyncio-from concurrent.futures import ThreadPoolExecutor--import aiohttp-from pydantic import Field-from rich.console import Console--from atomic_agents.agents.base_agent import BaseIOSchema-from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfig---################-# INPUT SCHEMA #-################-class SearxNGToolInputSchema(BaseIOSchema):- """- Schema for input to a tool for searching for information, news, references, and other content using SearxNG.- Returns a list of search results with a short description or content snippet and URLs for further exploration- """-- queries: List[str] = Field(..., description="List of search queries.")- category: Optional[Literal["general", "news", "social_media"]] = Field(- "general", description="Category of the search queries."- )---####################-# OUTPUT SCHEMA(S) #-####################-class SearxNGSearchResultItemSchema(BaseIOSchema):- """This schema represents a single search result item"""-- url: str = Field(..., description="The URL of the search result")- title: str = Field(..., description="The title of the search result")- content: Optional[str] = Field(None, description="The content snippet of the search result")- query: str = Field(..., description="The query used to obtain this search result")---class SearxNGToolOutputSchema(BaseIOSchema):- """This schema represents the output of the SearxNG search tool."""-- results: List[SearxNGSearchResultItemSchema] = Field(..., description="List of search result items")- category: Optional[str] = Field(None, description="The category of the search results")---##############-# TOOL LOGIC #-##############-class SearxNGToolConfig(BaseToolConfig):- base_url: str = ""- max_results: int = 10---class SearxNGTool(BaseTool):- """- Tool for performing searches on SearxNG based on the provided queries and category.-- Attributes:- input_schema (SearxNGToolInputSchema): The schema for the input data.- output_schema (SearxNGToolOutputSchema): The schema for the output data.- max_results (int): The maximum number of search results to return.- base_url (str): The base URL for the SearxNG instance to use.- """-- input_schema = SearxNGToolInputSchema- output_schema = SearxNGToolOutputSchema-- def __init__(self, config: SearxNGToolConfig = SearxNGToolConfig()):- """- Initializes the SearxNGTool.-- Args:- config (SearxNGToolConfig):- Configuration for the tool, including base URL, max results, and optional title and description overrides.- """- super().__init__(config)- self.base_url = config.base_url- self.max_results = config.max_results-- async def _fetch_search_results(self, session: aiohttp.ClientSession, query: str, category: Optional[str]) -> List[dict]:- """- Fetches search results for a single query asynchronously.-- Args:- session (aiohttp.ClientSession): The aiohttp session to use for the request.- query (str): The search query.- category (Optional[str]): The category of the search query.-- Returns:- List[dict]: A list of search result dictionaries.-- Raises:- Exception: If the request to SearxNG fails.- """- query_params = {- "q": query,- "safesearch": "0",- "format": "json",- "language": "en",- "engines": "bing,duckduckgo,google,startpage,yandex",- }-- if category:- query_params["categories"] = category-- async with session.get(f"{self.base_url}/search", params=query_params) as response:- if response.status != 200:- raise Exception(f"Failed to fetch search results for query '{query}': {response.status} {response.reason}")- data = await response.json()- results = data.get("results", [])-- # Add the query to each result- for result in results:- result["query"] = query-- return results-- async def run_async(self, params: SearxNGToolInputSchema, max_results: Optional[int] = None) -> SearxNGToolOutputSchema:- """- Runs the SearxNGTool asynchronously with the given parameters.-- Args:- params (SearxNGToolInputSchema): The input parameters for the tool, adhering to the input schema.- max_results (Optional[int]): The maximum number of search results to return.-- Returns:- SearxNGToolOutputSchema: The output of the tool, adhering to the output schema.-- Raises:- ValueError: If the base URL is not provided.- Exception: If the request to SearxNG fails.- """- async with aiohttp.ClientSession() as session:- tasks = [self._fetch_search_results(session, query, params.category) for query in params.queries]- results = await asyncio.gather(*tasks)-- all_results = [item for sublist in results for item in sublist]-- # Sort the combined results by score in descending order- sorted_results = sorted(all_results, key=lambda x: x.get("score", 0), reverse=True)-- # Remove duplicates while preserving order- seen_urls = set()- unique_results = []- for result in sorted_results:- if "content" not in result or "title" not in result or "url" not in result or "query" not in result:- continue- if result["url"] not in seen_urls:- unique_results.append(result)- if "metadata" in result:- result["title"] = f"{result['title']} - (Published {result['metadata']})"- if "publishedDate" in result and result["publishedDate"]:- result["title"] = f"{result['title']} - (Published {result['publishedDate']})"- seen_urls.add(result["url"])-- # Filter results to include only those with the correct category if it is set- if params.category:- filtered_results = [result for result in unique_results if result.get("category") == params.category]- else:- filtered_results = unique_results-- filtered_results = filtered_results[: max_results or self.max_results]-- return SearxNGToolOutputSchema(- results=[- SearxNGSearchResultItemSchema(- url=result["url"], title=result["title"], content=result.get("content"), query=result["query"]- )- for result in filtered_results- ],- category=params.category,- )-- def run(self, params: SearxNGToolInputSchema, max_results: Optional[int] = None) -> SearxNGToolOutputSchema:- """- Runs the SearxNGTool synchronously with the given parameters.-- This method creates an event loop in a separate thread to run the asynchronous operations.-- Args:- params (SearxNGToolInputSchema): The input parameters for the tool, adhering to the input schema.- max_results (Optional[int]): The maximum number of search results to return.-- Returns:- SearxNGToolOutputSchema: The output of the tool, adhering to the output schema.-- Raises:- ValueError: If the base URL is not provided.- Exception: If the request to SearxNG fails.- """- with ThreadPoolExecutor() as executor:- return executor.submit(asyncio.run, self.run_async(params, max_results)).result()---#################-# EXAMPLE USAGE #-#################-if __name__ == "__main__":- rich_console = Console()- search_tool_instance = SearxNGTool(config=SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=5))-- search_input = SearxNGTool.input_schema(- queries=["Python programming", "Machine learning", "Artificial intelligence"],- category="news",- )-- output = search_tool_instance.run(search_input)-- rich_console.print(output)diff --git a/atomic-agents/atomic_agents/lib/tools/search/serper_tool.py b/atomic-agents/atomic_agents/lib/tools/search/serper_tool.pydeleted file mode 100644index 5f93401..0000000--- a/atomic-agents/atomic_agents/lib/tools/search/serper_tool.py+++ /dev/null@@ -1,147 +0,0 @@-import json-import os-from typing import List, Optional--import requests-from pydantic import Field-from rich.console import Console--from atomic_agents.agents.base_agent import BaseIOSchema-from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfig---################-# INPUT SCHEMA #-################-class SerperToolInputSchema(BaseIOSchema):- """- Tool for searching for information, news, references, and other content using the Serper API.- Returns a list of search results with a short description or content snippet and URLs for further exploration.- """-- queries: List[str] = Field(..., description="List of search queries.")---####################-# OUTPUT SCHEMA(S) #-####################-class SerperResultSchema(BaseIOSchema):- url: str- title: str- content: Optional[str] = None- position: Optional[int] = None---class SerperToolOutputSchema(BaseIOSchema):- results: List[SerperResultSchema]---##############-# TOOL LOGIC #-##############-class SerperToolConfig(BaseToolConfig):- api_key: str = ""- max_results: int = 10---class SerperTool(BaseTool):- """- Tool for performing searches using the Serper API based on the provided queries.-- Attributes:- input_schema (SerperToolInputSchema): The schema for the input data.- output_schema (SerperToolOutputSchema): The schema for the output data.- api_key (str): The API key for the Serper API.- max_results (int): The maximum number of search results to return.- """-- input_schema = SerperToolInputSchema- output_schema = SerperToolOutputSchema-- def __init__(self, config: SerperToolConfig = SerperToolConfig()):- """- Initializes the SerperTool.-- Args:- config (SerperToolConfig):- Configuration for the tool, including API key, max results, and optional title and description overrides.- """- super().__init__(config)- self.api_key = config.api_key- self.max_results = config.max_results-- def run(self, params: SerperToolInputSchema, max_results: Optional[int] = None) -> SerperToolOutputSchema:- """- Runs the SerperTool with the given parameters.-- Args:- params (SerperToolInputSchema): The input parameters for the tool, adhering to the input schema.- max_results (Optional[int]): The maximum number of search results to return.-- Returns:- SerperToolOutputSchema: The output of the tool, adhering to the output schema.-- Raises:- ValueError: If the API key is not provided.- Exception: If the request to Serper API fails.- """- all_results = []-- for query in params.queries:- # Prepare the query payload- payload = json.dumps({"q": query})-- # Make the POST request- headers = {"X-API-KEY": self.api_key, "Content-Type": "application/json"}- response = requests.post("https://google.serper.dev/search", headers=headers, data=payload)-- # Check if the request was successful- if response.status_code != 200:- raise Exception(- f"Failed to fetch search results for query '{query}': {response.status_code} {response.reason}"- )-- results = response.json().get("organic", [])- all_results.extend(results)-- # Sort the combined results by position in ascending order- sorted_results = sorted(all_results, key=lambda x: x.get("position", float("inf")))-- # Remove duplicates while preserving order- seen_urls = set()- unique_results = []- for result in sorted_results:- if "snippet" not in result or "title" not in result or "link" not in result:- continue- if result["link"] not in seen_urls:- unique_results.append(result)- seen_urls.add(result["link"])-- filtered_results = unique_results[: max_results or self.max_results]-- # Convert to output schema format- output_results = [- SerperResultSchema(- url=result["link"],- title=result["title"],- content=result.get("snippet"),- position=result.get("position"),- )- for result in filtered_results- ]-- return SerperToolOutputSchema(results=output_results)---#################-# EXAMPLE USAGE #-#################-if __name__ == "__main__":- rich_console = Console()- search_tool_instance = SerperTool(config=SerperToolConfig(api_key=os.getenv("SERPER_API_KEY"), max_results=5))-- search_input = SerperTool.input_schema(queries=["Python programming", "Machine learning", "Quantum computing"])-- output = search_tool_instance.run(search_input)-- rich_console.print(output)diff --git a/atomic-agents/atomic_agents/lib/tools/yelp_restaurant_finder_tool.py b/atomic-agents/atomic_agents/lib/tools/yelp_restaurant_finder_tool.pydeleted file mode 100644index 8eff828..0000000--- a/atomic-agents/atomic_agents/lib/tools/yelp_restaurant_finder_tool.py+++ /dev/null@@ -1,204 +0,0 @@-import os-from enum import Enum-from typing import List, Optional--import requests-from pydantic import Field-from rich.console import Console--from atomic_agents.agents.base_agent import BaseIOSchema-from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfig---################-# INPUT SCHEMA #-################-class YelpCategory(Enum):- ITALIAN = "italian"- MEXICAN = "mexican"- PIZZA = "pizza"- SUSHI = "sushi"- CHINESE = "chinese"- INDIAN = "indian"- THAI = "thai"- FRENCH = "french"- GREEK = "greek"- JAPANESE = "japanese"- KOREAN = "korean"- VIETNAMESE = "vietnamese"- AMERICAN = "american"- BBQ = "bbq"- BURGERS = "burgers"- SEAFOOD = "seafood"- STEAKHOUSES = "steakhouses"- VEGAN = "vegan"- VEGETARIAN = "vegetarian"---class PriceRange(Enum):- ONE = "1"- TWO = "2"- THREE = "3"- FOUR = "4"---class YelpSearchToolInputSchema(BaseIOSchema):- """- Tool for searching for food using the Yelp API.- Returns a list of businesses with details such as name, rating, and address.- """-- location: str = Field(..., description="Location to search for food.")- term: Optional[str] = Field(None, description="Search term (e.g., 'pizza', 'sushi').")- categories: Optional[List[YelpCategory]] = Field(None, description="Categories to filter by (e.g., 'italian, mexican').")- price: Optional[List[PriceRange]] = Field(- None,- description=(- "Price range to filter by (e.g., '1', '2', '3', '4'). "- "Can be multiple. 1 is cheap. 2 and 3 are mid-range. 4 is the most high-end."- ),- )- open_now: Optional[bool] = Field(False, description="Filter for businesses that are open now.")- sort_by: Optional[str] = Field(- "best_match",- description="Sort by criteria (e.g., 'best_match', 'rating', 'review_count', 'distance').",- )- limit: Optional[int] = Field(10, description="Number of results to return.")---####################-# OUTPUT SCHEMA(S) #-####################-class YelpSearchResultSchema(BaseIOSchema):- """This schema represents a single result from the Yelp API."""-- name: str- url: str- rating: float- review_count: int- address: str- phone: Optional[str] = None- categories: List[str]---class YelpSearchToolOutputSchema(BaseIOSchema):- """- Output schema for the YelpSearchTool,- containing a list of search results with details such as name, rating, and address.- """-- results: List[YelpSearchResultSchema]---##############-# TOOL LOGIC #-##############-class YelpSearchToolConfig(BaseToolConfig):- api_key: str = ""- max_results: int = 10---class YelpSearchTool(BaseTool):- """- Tool for performing searches using the Yelp API based on the provided queries.-- Attributes:- input_schema (YelpSearchToolInputSchema): The schema for the input data.- output_schema (YelpSearchToolOutputSchema): The schema for the output data.- api_key (str): The API key for the Yelp API.- max_results (int): The maximum number of search results to return.- """-- input_schema = YelpSearchToolInputSchema- output_schema = YelpSearchToolOutputSchema-- def __init__(self, config: YelpSearchToolConfig = YelpSearchToolConfig()):- """- Initializes the YelpSearchTool.-- Args:- config (YelpSearchToolConfig):- Configuration for the tool, including API key, max results, and optional title and description overrides.- """- super().__init__(config)- self.api_key = config.api_key- self.max_results = config.max_results-- def run(self, params: YelpSearchToolInputSchema) -> YelpSearchToolOutputSchema:- """- Runs the YelpSearchTool with the given parameters.-- Args:- params (YelpSearchToolInputSchema): The input parameters for the tool, adhering to the input schema.- max_results (Optional[int]): The maximum number of search results to return.-- Returns:- YelpSearchToolOutputSchema: The output of the tool, adhering to the output schema.-- Raises:- ValueError: If the API key is not provided.- Exception: If the request to Yelp API fails.- """- if not self.api_key:- raise ValueError("API key is required to use the Yelp API.")-- # Prepare the query parameters- query_params = {- "location": params.location,- "term": params.term,- "categories": (",".join([category.value for category in params.categories]) if params.categories else None),- "price": (",".join([price.value for price in params.price]) if params.price else None),- "sort_by": params.sort_by,- "limit": self.max_results,- "open_now": params.open_now,- }-- # Make the GET request- headers = {"Authorization": f"Bearer {self.api_key}"}- response = requests.get(- "https://api.yelp.com/v3/businesses/search",- headers=headers,- params=query_params,- )-- # Check if the request was successful- if response.status_code != 200:- raise Exception(f"Failed to fetch search results: {response.status_code} {response.reason}")-- results = response.json().get("businesses", [])-- # Convert to output schema format- output_results = [- YelpSearchResultSchema(- name=result["name"],- url=result["url"].split("?")[0],- rating=result["rating"],- review_count=result["review_count"],- address=", ".join(result["location"]["display_address"]),- phone=result.get("display_phone"),- categories=[category["title"] for category in result["categories"]],- )- for result in results- ]-- return YelpSearchToolOutputSchema(results=output_results)---#################-# EXAMPLE USAGE #-#################-if __name__ == "__main__":- rich_console = Console()- search_tool_instance = YelpSearchTool(config=YelpSearchToolConfig(api_key=os.getenv("YELP_API_KEY"), max_results=10))-- search_input = YelpSearchTool.input_schema(- location="Diepenbeek, Belgium",- term="",- categories=[YelpCategory.PIZZA],- price=[PriceRange.ONE, PriceRange.TWO, PriceRange.THREE, PriceRange.FOUR],- sort_by="best_match",- )-- output = search_tool_instance.run(search_input)-- rich_console.print(output)diff --git a/atomic-agents/atomic_agents/lib/tools/yt_transcript_scraper_tool.py b/atomic-agents/atomic_agents/lib/tools/yt_transcript_scraper_tool.pydeleted file mode 100644index 085837b..0000000--- a/atomic-agents/atomic_agents/lib/tools/yt_transcript_scraper_tool.py+++ /dev/null@@ -1,155 +0,0 @@-import os-from typing import List, Optional--from googleapiclient.discovery import build-from pydantic import Field-from rich.console import Console-from youtube_transcript_api import NoTranscriptFound, TranscriptsDisabled, YouTubeTranscriptApi--from atomic_agents.agents.base_agent import BaseIOSchema-from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfig---################-# INPUT SCHEMA #-################-class YouTubeTranscriptToolInputSchema(BaseIOSchema):- """- Tool for fetching the transcript of a YouTube video using the YouTube Transcript API.- Returns the transcript with text, start time, and duration.- """-- video_url: str = Field(..., description="URL of the YouTube video to fetch the transcript for.")- language: Optional[str] = Field(None, description="Language code for the transcript (e.g., 'en' for English).")---####################-# OUTPUT SCHEMA(S) #-####################-class YouTubeTranscriptToolOutputSchema(BaseIOSchema):- """Output schema for the YouTubeTranscriptTool. Contains the transcript text, duration, comments, and metadata."""-- transcript: str- duration: float- comments: List[str]- metadata: dict---##############-# TOOL LOGIC #-##############-class YouTubeTranscriptToolConfig(BaseToolConfig):- api_key: str = Field(- description="YouTube API key for fetching video metadata.",- default=os.getenv("YOUTUBE_API_KEY"),- )---class YouTubeTranscriptTool(BaseTool):- """- Tool for fetching the transcript of a YouTube video using the YouTube Transcript API.-- Attributes:- input_schema (YouTubeTranscriptToolInputSchema): The schema for the input data.- output_schema (YouTubeTranscriptToolOutputSchema): The schema for the output data.- """-- input_schema = YouTubeTranscriptToolInputSchema- output_schema = YouTubeTranscriptToolOutputSchema-- def __init__(self, config: YouTubeTranscriptToolConfig):- """- Initializes the YouTubeTranscriptTool.-- Args:- config (YouTubeTranscriptToolConfig): Configuration for the tool.- """- super().__init__(config)- self.api_key = config.api_key-- def run(self, params: YouTubeTranscriptToolInputSchema) -> YouTubeTranscriptToolOutputSchema:- """- Runs the YouTubeTranscriptTool with the given parameters.-- Args:- params (YouTubeTranscriptToolInputSchema): The input parameters for the tool, adhering to the input schema.-- Returns:- YouTubeTranscriptToolOutputSchema: The output of the tool, adhering to the output schema.-- Raises:- Exception: If fetching the transcript fails.- """- video_id = self.extract_video_id(params.video_url)- try:- if params.language:- transcripts = YouTubeTranscriptApi.get_transcript(video_id, languages=[params.language])- else:- transcripts = YouTubeTranscriptApi.get_transcript(video_id)- except (NoTranscriptFound, TranscriptsDisabled) as e:- raise Exception(f"Failed to fetch transcript for video '{video_id}': {str(e)}")-- transcript_text = " ".join([transcript["text"] for transcript in transcripts])- total_duration = sum([transcript["duration"] for transcript in transcripts])-- metadata = self.fetch_video_metadata(video_id)-- return YouTubeTranscriptToolOutputSchema(- transcript=transcript_text,- duration=total_duration,- comments=[],- metadata=metadata,- )-- @staticmethod- def extract_video_id(url: str) -> str:- """- Extracts the video ID from a YouTube URL.-- Args:- url (str): The YouTube video URL.-- Returns:- str: The extracted video ID.- """- return url.split("v=")[-1].split("&")[0]-- def fetch_video_metadata(self, video_id: str) -> dict:- """- Fetches metadata for a YouTube video.-- Args:- video_id (str): The YouTube video ID.-- Returns:- dict: The metadata of the video.- """- youtube = build("youtube", "v3", developerKey=self.api_key)- request = youtube.videos().list(part="snippet", id=video_id)- response = request.execute()-- if not response["items"]:- raise Exception(f"No metadata found for video '{video_id}'")-- video_info = response["items"][0]["snippet"]- metadata = {- "id": video_id,- "title": video_info["title"],- "channel": video_info["channelTitle"],- "published_at": video_info["publishedAt"],- }- return metadata---#################-# EXAMPLE USAGE #-#################-if __name__ == "__main__":- rich_console = Console()- api_key = os.getenv("YOUTUBE_API_KEY")- search_tool_instance = YouTubeTranscriptTool(config=YouTubeTranscriptToolConfig(api_key=api_key))-- search_input = YouTubeTranscriptTool.input_schema(video_url="https://www.youtube.com/watch?v=t1e8gqXLbsU", language="en")-- output = search_tool_instance.run(search_input)- rich_console.print(output)diff --git a/atomic-forge/atomic_tools/calculator/tool/calculator.py b/atomic-forge/atomic_tools/calculator/tool/calculator.pyindex d7ab8c1..6eda8e8 100644--- a/atomic-forge/atomic_tools/calculator/tool/calculator.py+++ b/atomic-forge/atomic_tools/calculator/tool/calculator.py@@ -21,22 +21,31 @@ class CalculatorToolInputSchema(BaseIOSchema):)-####################-# OUTPUT SCHEMA(S) #-####################+#################+# OUTPUT SCHEMA #+#################class CalculatorToolOutputSchema(BaseIOSchema):- """This schema defines the output of the CalculatorTool."""+ """+ Schema for the output of the CalculatorTool.+ """result: str = Field(..., description="Result of the calculation.")-##############-# TOOL LOGIC #-##############+#################+# CONFIGURATION #+#################class CalculatorToolConfig(BaseToolConfig):+ """+ Configuration for the CalculatorTool.+ """+pass+#####################+# MAIN TOOL & LOGIC #+#####################class CalculatorTool(BaseTool):"""Tool for performing calculations based on the provided mathematical expression.diff --git a/atomic-forge/atomic_tools/youtube_transcript_scraper/tool/youtube_transcript_scraper.py b/atomic-forge/atomic_tools/youtube_transcript_scraper/tool/youtube_transcript_scraper.pyindex a37998a..2d248c7 100644--- a/atomic-forge/atomic_tools/youtube_transcript_scraper/tool/youtube_transcript_scraper.py+++ b/atomic-forge/atomic_tools/youtube_transcript_scraper/tool/youtube_transcript_scraper.py@@ -30,21 +30,23 @@ class YouTubeTranscriptToolInputSchema(BaseIOSchema):)-####################-# OUTPUT SCHEMA(S) #-####################+#################+# OUTPUT SCHEMA #+#################class YouTubeTranscriptToolOutputSchema(BaseIOSchema):- """Output schema for the YouTubeTranscriptTool. Contains the transcript text, duration, comments, and metadata."""+ """+ Output schema for the YouTubeTranscriptTool. Contains the transcript text, duration, comments, and metadata.+ """- transcript: str- duration: float- comments: List[str]- metadata: dict+ transcript: str = Field(..., description="Transcript of the YouTube video.")+ duration: float = Field(..., description="Duration of the YouTube video.")+ comments: List[str] = Field(..., description="Comments on the YouTube video.")+ metadata: dict = Field(..., description="Metadata of the YouTube video.")-##############-# TOOL LOGIC #-##############+#################+# CONFIGURATION #+#################class YouTubeTranscriptToolConfig(BaseToolConfig):api_key: str = Field(description="YouTube API key for fetching video metadata.",@@ -52,6 +54,9 @@ class YouTubeTranscriptToolConfig(BaseToolConfig):)+#####################+# MAIN TOOL & LOGIC #+#####################class YouTubeTranscriptTool(BaseTool):"""Tool for fetching the transcript of a YouTube video using the YouTube Transcript API.diff --git a/atomic-forge/docs/tool_structure.md b/atomic-forge/docs/tool_structure.mdindex 9d83b89..2a5a2ef 100644--- a/atomic-forge/docs/tool_structure.md+++ b/atomic-forge/docs/tool_structure.md@@ -1,254 +1,628 @@-# Anatomy of a Tool in Atomic Agents+# Creating Your Own Atomic Tool: A Comprehensive Guide## Introduction-The **Atomic Agents** framework enables developers to create modular, extensible, and efficient AI tools. This guide outlines the core anatomy of a tool within the Atomic Agents ecosystem, providing a structured approach to building new tools that seamlessly integrate into the framework.+Welcome to this (hopefully) comprehensive (enough) guide on creating your own **Atomic Tool** within the **Atomic Agents** framework. This guide is designed to be a step-by-step tutorial, walking you through the entire process of building an Atomic Tool—from understanding the fundamental concepts to implementing and testing your tool.-## Components of a Tool+## The Principles-Each tool in Atomic Agents is constructed using a standardized architecture to ensure consistency and ease of integration. The primary components include:+An **Atomic Tool** is a self-contained, modular component within the Atomic Agents framework. It encapsulates a specific piece of functionality, for example a calculator, a youtube transcript scraper, or a twitter search tool, allowing for easy integration, maintenance, and extension. Each tool is designed to perform a single task and can be combined with other tools to build more complex applications.++**Key Characteristics of an Atomic Tool:**++- **Single Responsibility:** Focuses on one specific task.+- **Modular and Reusable:** Can be easily integrated into different agents or applications.+- **Self-Contained:** Includes all necessary components to function independently.+- **Clear Interfaces:** Defines explicit input and output schemas for consistent data handling.+- **Configurable:** Allows customization through configuration settings.+- **Executable Independently:** Can run on its own or as part of an Atomic Agent.++## Principles of Atomic Tool Design++### Modularity++Each tool should be an independent module that can function on its own. Modularity ensures that tools can be developed, tested, and debugged in isolation, leading to more reliable and maintainable code.++### Reusability++Design tools with reusability in mind. Avoid hardcoding values or making assumptions that limit where and how the tool can be used.++### Single Responsibility Principle++Adhere to the Single Responsibility Principle by ensuring that each tool does one thing and does it well. This makes your tools easier to understand, test, and maintain.++### Clear Interfaces++Define explicit input and output schemas using Pydantic models. This ensures consistent data handling and makes your tools predictable and reliable.++### Configurability++Provide configuration options to allow users to customize the tool's behavior without modifying the code. Use default values where appropriate to make tools easy to use out of the box.++## Anatomy of an Atomic Tool++An Atomic Tool in the Atomic Agents framework follows a highly standardized structure. This consistency is crucial for maintainability, interoperability, and ease of understanding.++**The structure of an Atomic Tool includes the following sections, in this specific order:**1. **Input Schema**-2. **Output Schema**-3. **Tool Logic**-4. **Configuration**+2. **Output Schema(s)**+3. **Configuration**+4. **Main Tool & Logic**5. **Example Usage**+The input and output schemas must always extend from `BaseIOSchema` and the main tool class must always extend from `BaseTool`.++**Note:** Each section should be clearly delineated with a comment block that includes the section's name. For example:++```python+################+# Input Schema #+################+```++Let's explore each of these sections in detail.+### 1. Input Schema-The Input Schema defines the structure and validation rules for the data the tool expects. Utilizing Pydantic's `BaseModel`, it ensures that all inputs meet the required criteria before processing.+The **Input Schema** defines the structure and validation rules for the data your tool accepts. It uses Pydantic models to enforce data types, provide default values, and include descriptions.++**Guidelines:**++- Use `BaseIOSchema` as the base class.+- Define all input fields with appropriate types and descriptions.+- Use `Field(..., description="...")` to make a field required and to provide a description.+- Include a docstring that briefly explains the purpose of the input schema.-**Example: `CalculatorToolInputSchema`**+**Example:**-```python:atomic_tools/calculator/tool/calculator.py-class CalculatorToolInputSchema(BaseIOSchema):+```python+################+# Input Schema #+################++class MyToolInputSchema(BaseIOSchema):"""- Tool for performing calculations. Supports basic arithmetic operations- like addition, subtraction, multiplication, and division, as well as more- complex operations like exponentiation and trigonometric functions.- Use this tool to evaluate mathematical expressions.+ Captures input data required for MyTool."""-- expression: str = Field(- ..., description="Mathematical expression to evaluate. For example, '2 + 2'."- )+ input_field1: str = Field(..., description="Description of input_field1.")+ input_field2: int = Field(42, description="Description of input_field2 with a default value.")```-### 2. Output Schema+### 2. Output Schema(s)-The Output Schema defines the structure and validation rules for the data the tool returns after execution. It ensures that the output adheres to a consistent format, facilitating seamless integration with other components.+The **Output Schema(s)** define the structure of the data your tool outputs. You can have multiple output schemas if your tool produces different types of outputs.-**Example: `CalculatorToolOutputSchema`**+**Guidelines:**-```python:atomic_tools/calculator/tool/calculator.py-class CalculatorToolOutputSchema(BaseIOSchema):- """This schema defines the output of the CalculatorTool."""+- Use `BaseIOSchema` as the base class.+- Define all output fields with appropriate types and descriptions.+- Include a docstring that briefly explains the purpose of the output schema.- result: str = Field(..., description="Result of the calculation.")+**Example:**++```python+#################+# Output Schema #+#################++class MyToolOutputSchema(BaseIOSchema):+ """+ Contains the results produced by MyTool.+ """+ output_field1: str = Field(..., description="Description of output_field1.")```-### 3. Tool Logic+### 3. Configuration++The **Configuration** section allows you to define settings that can customize the tool's behavior. This is where you include API keys, endpoints, or any other parameters that might change between environments or use cases.++**Guidelines:**-The Tool Logic encapsulates the core functionality of the tool, detailing how inputs are processed to produce outputs. It inherits from a base tool class and implements the `run` method, which orchestrates the tool's operations.+- Inherit from `BaseToolConfig`.+- Define configuration parameters with default values and descriptions.+- Use environment variables where appropriate to avoid hardcoding sensitive information.+- Include a docstring that explains the purpose of the configuration class.-**Example: `CalculatorTool`**+**Example:**-```python:atomic_tools/calculator/tool/calculator.py-class CalculatorTool(BaseTool):+```python+#################+# Configuration #+#################++class MyToolConfig(BaseToolConfig):+ """+ Configuration settings for MyTool."""- Tool for performing calculations based on the provided mathematical expression.+ api_endpoint: str = Field(+ default="https://api.example.com/v1",+ description="API endpoint for MyTool."+ )+ api_key: str = Field(+ default=os.getenv("MY_TOOL_API_KEY"),+ description="API key for authenticating with the service."+ )+```++### 4. Main Tool & Logic++This is the core of your tool, where you implement the main functionality.++**Guidelines:**- Attributes:- input_schema (CalculatorToolInputSchema): The schema for the input data.- output_schema (CalculatorToolOutputSchema): The schema for the output data.+- Inherit from `BaseTool`.+- Set `input_schema` and `output_schema` as class variables.+- Implement the `run` method, which takes an instance of the input schema and returns an instance of the output schema.+- Include a docstring that explains what the tool does.+- Use helper methods to break down complex logic.+- Handle exceptions gracefully, providing meaningful error messages.++**Example:**++```python+#####################+# Main Tool & Logic #+#####################++class MyTool(BaseTool):+ """+ Performs the main functionality of MyTool."""- input_schema = CalculatorToolInputSchema- output_schema = CalculatorToolOutputSchema+ input_schema = MyToolInputSchema+ output_schema = MyToolOutputSchema- def __init__(self, config: CalculatorToolConfig = CalculatorToolConfig()):+ def __init__(self, config: MyToolConfig = MyToolConfig()):"""- Initializes the CalculatorTool.-- Args:- config (CalculatorToolConfig): Configuration for the tool.+ Initializes MyTool with the provided configuration."""super().__init__(config)+ self.api_endpoint = config.api_endpoint+ self.api_key = config.api_key- def run(self, params: CalculatorToolInputSchema) -> CalculatorToolOutputSchema:+ def run(self, params: MyToolInputSchema) -> MyToolOutputSchema:"""- Executes the CalculatorTool with the given parameters.-- Args:- params (CalculatorToolInputSchema): The input parameters for the tool.+ Executes the tool's main logic.+ """+ # Implement the logic here+ result = self.perform_action(params.input_field1, params.input_field2)+ return MyToolOutputSchema(output_field1=result)- Returns:- CalculatorToolOutputSchema: The result of the calculation.+ def perform_action(self, field1: str, field2: int) -> str:+ """+ Helper method to perform a specific action."""- # Convert the expression string to a symbolic expression- parsed_expr = sympify(params.expression)+ # Example logic+ return f"Processed {field1} with value {field2}"+```++### 5. Example Usage- # Evaluate the expression numerically- result = parsed_expr.evalf()- return CalculatorToolOutputSchema(result=str(result))+The **Example Usage** section demonstrates how to instantiate and run your tool. This is invaluable for testing and serves as documentation for users.++**Guidelines:**++- Include a `__main__` guard to prevent code from running on import.+- Use `rich.console` for formatted output.+- Provide sample input data.+- Print or log the output in a readable format.++**Example:**++```python+#################+# Example Usage #+#################++if __name__ == "__main__":+ from rich.console import Console++ console = Console()+ tool = MyTool()++ input_data = MyToolInputSchema(+ input_field1="Sample Input",+ input_field2=123+ )++ output = tool.run(input_data)+ console.print(output)```-### 4. Configuration+## Step-by-Step Guide to Creating an Atomic Tool++Now that we've covered the structure, let's go through the steps to create your own Atomic Tool.++### Step 1: Define the Purpose of Your Tool++Before writing any code, clearly define what your tool will do.++- **Example:** "I want to create a tool that fetches the current weather for a given city."++### Step 2: Design the Input Schema++Identify what inputs your tool requires.++- **Example Input Fields:**+ - `city_name`: Name of the city.+ - `units`: Units of measurement (e.g., metric or imperial).-Configuration handles the settings required by the tool, such as API keys or environment variables. It ensures that sensitive information is managed securely and can be easily modified without altering the tool's core logic.+Implement the input schema:-**Example: `YouTubeTranscriptToolConfig`**+```python+################+# Input Schema #+################-```python:atomic_tools/youtube_transcript_scraper/tool/youtube_transcript_scraper.py-class YouTubeTranscriptToolConfig(BaseToolConfig):+class WeatherToolInputSchema(BaseIOSchema):+ """+ Input data required to fetch the weather.+ """+ city_name: str = Field(..., description="Name of the city to fetch the weather for.")+ units: str = Field('metric', description="Units of measurement (metric or imperial).")+```++### Step 3: Design the Output Schema++Determine what outputs your tool will produce.++- **Example Output Fields:**+ - `temperature`: Current temperature.+ - `description`: Weather description (e.g., sunny, cloudy).++Implement the output schema:++```python+####################+# Output Schema(s) #+####################++class WeatherToolOutputSchema(BaseIOSchema):+ """+ Weather data for the specified city.+ """+ temperature: float = Field(..., description="Current temperature in the specified units.")+ description: str = Field(..., description="Weather description.")+```++### Step 4: Set Up Configuration++Identify any configuration parameters, such as API keys or endpoints.++Implement the configuration class:++```python+#################+# Configuration #+#################++class WeatherToolConfig(BaseToolConfig):+ """+ Configuration for the WeatherTool.+ """api_key: str = Field(- description="YouTube API key for fetching video metadata.",- default=os.getenv("YOUTUBE_API_KEY"),+ default=os.getenv("WEATHER_API_KEY"),+ description="API key for the weather service."+ )+ api_endpoint: str = Field(+ default="https://api.openweathermap.org/data/2.5/weather",+ description="API endpoint for fetching weather data.")```-### 5. Example Usage+### Step 5: Implement the Main Tool & Logic++Create the tool class and implement the logic.-Example Usage demonstrates how to instantiate and utilize the tool within an application. It provides a practical reference for developers to integrate the tool into their workflows effectively.+```python+#####################+# Main Tool & Logic #+#####################-**Example Usage: `CalculatorTool`**+class WeatherTool(BaseTool):+ """+ Fetches the current weather for a specified city.+ """++ input_schema = WeatherToolInputSchema+ output_schema = WeatherToolOutputSchema++ def __init__(self, config: WeatherToolConfig = WeatherToolConfig()):+ super().__init__(config)+ self.api_key = config.api_key+ self.api_endpoint = config.api_endpoint++ def run(self, params: WeatherToolInputSchema) -> WeatherToolOutputSchema:+ response = self.fetch_weather(params.city_name, params.units)+ temperature = response['main']['temp']+ description = response['weather'][0]['description']+ return WeatherToolOutputSchema(+ temperature=temperature,+ description=description+ )++ def fetch_weather(self, city_name: str, units: str) -> dict:+ import requests+ params = {+ 'q': city_name,+ 'units': units,+ 'appid': self.api_key+ }+ response = requests.get(self.api_endpoint, params=params)+ if response.status_code != 200:+ raise Exception(f"Error fetching weather data: {response.text}")+ return response.json()+```++**Notes:**++- **Error Handling:** We check the response status code and raise an exception if the request fails.+- **Helper Methods:** `fetch_weather` is a helper method that encapsulates the API call.++### Step 6: Test Your Tool++Write an example usage to test the tool.++```python+#################+# Example Usage #+#################-```python:atomic_tools/calculator/tool/calculator.pyif __name__ == "__main__":- calculator = CalculatorTool()- result = calculator.run(- CalculatorToolInputSchema(expression="sin(pi/2) + cos(pi/4)")+ from rich.console import Console++ console = Console()+ tool = WeatherTool()++ input_data = WeatherToolInputSchema(+ city_name="New York",+ units="metric")- print(result) # Expected output: {"result":"1.70710678118655"}-```--## Creating a New Tool--To create a new tool within the Atomic Agents framework, follow these steps:--1. **Define the Input Schema:**- Specify the input parameters the tool will accept using a Pydantic `BaseModel`.-- **Example:**- ```python:your_tool/tool/your_tool.py- class YourToolInputSchema(BaseIOSchema):- """- Description of your tool's input parameters.- """- param1: str = Field(..., description="Description of param1.")- param2: int = Field(..., description="Description of param2.")- ```--2. **Define the Output Schema:**- Specify the structure of the data the tool will return after execution.-- **Example:**- ```python:your_tool/tool/your_tool.py- class YourToolOutputSchema(BaseIOSchema):- """- Description of the tool's output.- """- result: str = Field(..., description="Description of the result.")- ```--3. **Implement the Tool Logic:**- Create a class that inherits from `BaseTool`, set the `input_schema` and `output_schema`, and implement the `run` method with the tool's functionality.-- **Example:**- ```python:your_tool/tool/your_tool.py- class YourTool(BaseTool):- """- Tool for [brief description of what your tool does].-- Attributes:- input_schema (YourToolInputSchema): The schema for the input data.- output_schema (YourToolOutputSchema): The schema for the output data.- """-- input_schema = YourToolInputSchema- output_schema = YourToolOutputSchema-- def __init__(self, config: YourToolConfig = YourToolConfig()):- """- Initializes the YourTool.-- Args:- config (YourToolConfig): Configuration for the tool.- """- super().__init__(config)-- def run(self, params: YourToolInputSchema) -> YourToolOutputSchema:- """- Executes the YourTool with the given parameters.-- Args:- params (YourToolInputSchema): The input parameters for the tool.-- Returns:- YourToolOutputSchema: The result of the tool's execution.- """- # Implement your tool's logic here- result = "your_result_based_on_params"- return YourToolOutputSchema(result=result)- ```--4. **Configure the Tool:**- Create a configuration class inheriting from `BaseToolConfig` to manage any necessary settings or environment variables.-- **Example:**- ```python:your_tool/tool/your_tool.py- class YourToolConfig(BaseToolConfig):- """- Configuration for YourTool.-- Attributes:- setting1 (str): Description of setting1.- setting2 (int): Description of setting2.- """- setting1: str = Field(..., description="Description of setting1.")- setting2: int = Field(..., description="Description of setting2.")- ```--5. **Provide Example Usage:**- Add examples demonstrating how to use the tool, aiding developers in integration.-- **Example Usage:**- ```python:your_tool/tool/your_tool.py- if __name__ == "__main__":- tool = YourTool()- input_data = YourToolInputSchema(param1="value1", param2=42)- output = tool.run(input_data)- print(output) # Expected output: {"result":"expected_result"}- ```--6. **Write Tests:**- Develop test cases to validate the tool's functionality, ensuring it behaves as expected.-- **Example Test:**- ```python:your_tool/tests/test_your_tool.py- import pytest- from your_tool.tool.your_tool import YourTool, YourToolInputSchema, YourToolOutputSchema, YourToolConfig-- def test_your_tool():- config = YourToolConfig(setting1="value1", setting2=2)- tool = YourTool(config=config)- input_data = YourToolInputSchema(param1="test", param2=10)- result = tool.run(input_data)- assert isinstance(result, YourToolOutputSchema)- assert result.result == "expected_result_based_on_input"- ```--## Best Practices--- **Modularity:** Design tools to perform single, well-defined tasks to enhance reusability and maintainability.-- **Validation:** Utilize Pydantic schemas for rigorous input and output validation, ensuring data integrity.-- **Error Handling:** Implement comprehensive error checks to manage unexpected scenarios gracefully.-- **Configuration Management:** Securely handle sensitive information like API keys using environment variables and configuration classes.-- **Documentation:** Provide clear docstrings and usage examples to aid developers in understanding and utilizing the tools effectively.-- **Testing:** Develop thorough test cases to validate the tool's functionality and reliability across different scenarios.--## Conclusion--Mastering the anatomy of a tool within the Atomic Agents framework enables the creation of robust and efficient AI-driven applications. By adhering to the structured approach outlined in this guide, developers can ensure consistency, reliability, and scalability in their tool development endeavors.--For more detailed information and advanced configurations, refer to the [Atomic Agents Documentation](https://github.com/BrainBlend-AI/atomic-agents).++ try:+ output = tool.run(input_data)+ console.print(output)+ except Exception as e:+ console.print(f"[red]Error:[/red] {e}")+```++**Testing Tips:**++- Test with valid and invalid inputs.+- Check how the tool handles exceptions.+- Ensure the output matches the expected schema.++## Best Practices and Guidelines++### Do's++- **Follow the Standard Structure:** Adhere to the prescribed order and format for consistency.+- **Use Clear and Descriptive Names:** Make your code self-explanatory.+- **Document Your Code:** Include docstrings and comments to explain the purpose and functionality.+- **Validate Inputs Thoroughly:** Use Pydantic's features to enforce data integrity.+- **Handle Errors Gracefully:** Provide informative error messages and handle exceptions where appropriate.+- **Keep Functions Small and Focused:** Break down complex logic into helper methods.+- **Test Extensively:** Use the example usage section to test various scenarios.++### Don'ts++- **Don't Hardcode Values:** Use configuration parameters or environment variables instead.+- **Avoid Global Variables:** Keep the state within your tool's scope.+- **Don't Overcomplicate:** Stick to the tool's single responsibility; avoid adding unrelated features.+- **Don't Ignore Security:** Be cautious with sensitive information like API keys; use environment variables.+- **Don't Neglect Performance:** Optimize your code, especially when dealing with large datasets or external API calls.+- **Don't Skip Input Validation:** Never assume inputs are valid; always validate.++## Example: Pizza Ordering Tool++To illustrate the concepts, let's revisit the **Pizza Ordering Tool** example, explaining each section in detail.++### Input Schema++We need to capture customer details and order specifics.++```python+################+# Input Schema #+################++class PizzaOrderInputSchema(BaseIOSchema):+ """+ Captures customer details and order specifics for placing a pizza order.+ """+ customer_name: str = Field(..., description="Name of the customer placing the order.")+ pizza_type: str = Field(..., description="Type of pizza to order (e.g., Margherita, Pepperoni).")+ size: str = Field(..., description="Size of the pizza (e.g., Small, Medium, Large).")+ quantity: int = Field(..., description="Number of pizzas to order.")+```++**Explanation:**++- All fields are required, indicated by `...`.+- Each field has a descriptive message.+- The schema is clear and self-explanatory.++### Output Schemas++We have two outputs: order confirmation and payment details.++```python+####################+# Output Schemas #+####################++class OrderConfirmationSchema(BaseIOSchema):+ """+ Confirmation details of the placed order.+ """+ order_id: str = Field(..., description="Unique identifier for the order.")+ estimated_delivery_time: str = Field(..., description="Estimated time for order delivery.")++class PaymentDetailsSchema(BaseIOSchema):+ """+ Payment information for the order.+ """+ amount: float = Field(..., description="Total amount to be paid.")+ payment_status: str = Field(..., description="Status of the payment (e.g., Paid, Pending).")+```++**Explanation:**++- Separate schemas for different types of outputs.+- Clear and descriptive fields.++### Configuration++Defines API endpoints and supported pizzas.++```python+#################+# Configuration #+#################++class PizzaOrderingToolConfig(BaseToolConfig):+ """+ Configuration for the PizzaOrderingTool.+ """+ api_endpoint: str = Field(+ default="https://api.pizzaorders.com/v1/orders",+ description="API endpoint for processing pizza orders."+ )+ supported_pizzas: List[str] = Field(+ default=["Margherita", "Pepperoni", "Veggie", "Hawaiian"],+ description="List of supported pizza types."+ )+```++**Explanation:**++- Allows the tool to be customized without changing the code.+- Uses defaults that can be overridden if necessary.++### Main Tool & Logic++Implements the tool's functionality.++```python+#####################+# Main Tool & Logic #+#####################++class PizzaOrderingTool(BaseTool):+ """+ Tool for placing pizza orders through the Pizza Orders API.+ """++ input_schema = PizzaOrderInputSchema+ output_schemas = {+ "confirmation": OrderConfirmationSchema,+ "payment": PaymentDetailsSchema+ }++ def __init__(self, config: PizzaOrderingToolConfig = PizzaOrderingToolConfig()):+ super().__init__(config)+ self.api_endpoint = config.api_endpoint+ self.supported_pizzas = config.supported_pizzas++ def run(self, params: PizzaOrderInputSchema) -> Dict[str, BaseIOSchema]:+ # Validate pizza type+ if params.pizza_type not in self.supported_pizzas:+ raise ValueError(f"Pizza type '{params.pizza_type}' is not supported.")++ # Simulate placing the order+ order_id = self.place_order(params)+ estimated_time = self.get_estimated_delivery_time(order_id)+ amount = self.calculate_payment(params)+ payment_status = self.process_payment(order_id, amount)++ # Prepare outputs+ confirmation = OrderConfirmationSchema(+ order_id=order_id,+ estimated_delivery_time=estimated_time+ )+ payment = PaymentDetailsSchema(+ amount=amount,+ payment_status=payment_status+ )++ return {+ "confirmation": confirmation,+ "payment": payment+ }++ def place_order(self, params: PizzaOrderInputSchema) -> str:+ """+ Simulates placing an order and returns an order ID.+ """+ # Placeholder logic; in reality, this would involve an API call.+ return "ORD123456"++ def get_estimated_delivery_time(self, order_id: str) -> str:+ """+ Simulates retrieving the estimated delivery time.+ """+ # Placeholder logic.+ return "30 minutes"++ def calculate_payment(self, params: PizzaOrderInputSchema) -> float:+ """+ Calculates the total amount to be paid.+ """+ price_per_pizza = {+ "Margherita": 8.99,+ "Pepperoni": 9.99,+ "Veggie": 10.99,+ "Hawaiian": 9.49+ }+ return price_per_pizza[params.pizza_type] * params.quantity++ def process_payment(self, order_id: str, amount: float) -> str:+ """+ Simulates payment processing.+ """+ # Placeholder logic.+ return "Paid"+```++**Explanation:**++- **Validation:** Checks if the pizza type is supported.+- **Modularity:** Uses helper methods for each step.+- **Error Handling:** Raises exceptions for invalid inputs.+- **Output Preparation:** Constructs output schemas to return.++### Example Usage++Testing the tool.++```python+#################+# Example Usage #+#################++if __name__ == "__main__":+ from rich.console import Console++ console = Console()+ pizza_tool = PizzaOrderingTool()++ order_input = PizzaOrderInputSchema(+ customer_name="Jane Smith",+ pizza_type="Veggie",+ size="Medium",+ quantity=1+ )++ try:+ outputs = pizza_tool.run(order_input)+ console.print(outputs)+ except Exception as e:+ console.print(f"[red]Error:[/red] {e}")+```++**Remember:** The goal of the Atomic Agents framework is to build powerful applications by composing small, well-defined tools and agents. Your contributions help make the framework more robust and versatile.++---++By following this guide and adhering to the best practices outlined, you'll be well on your way to creating effective and reusable Atomic Tools that can be combined to build powerful AI applications. Happy coding!