Building AI agents, atomically
Get rid of the Config class boilerplate and use docstrings and the classname instead
KennyVaneetvelde92acab1c4ccc
diff --git a/atomic_agents/agents/base_agent.py b/atomic_agents/agents/base_agent.pyindex c67e883..d62f310 100644--- a/atomic_agents/agents/base_agent.py+++ b/atomic_agents/agents/base_agent.py@@ -26,17 +26,10 @@ class BaseIOSchema(BaseModel):@classmethoddef _validate_description(cls):description = cls.__doc__-- if not description and cls.__module__ == 'instructor.function_calls':- return-- if not description or not description.strip():- raise ValueError(f"{cls.__name__} must have a non-empty docstring to serve as its description")- # Add the description to the schema- # if not hasattr(cls, "__pydantic_core_schema__"):- # cls.__pydantic_core_schema__ = {}- # cls.__pydantic_core_schema__["description"] = inspect.cleandoc(description)+ if not description or not description.strip():+ if cls.__module__ != "instructor.function_calls":+ raise ValueError(f"{cls.__name__} must have a non-empty docstring to serve as its description")@classmethoddef model_json_schema(cls, *args, **kwargs):diff --git a/atomic_agents/agents/tool_interface_agent.py b/atomic_agents/agents/tool_interface_agent.pyindex d4c6d12..c9501cd 100644--- a/atomic_agents/agents/tool_interface_agent.py+++ b/atomic_agents/agents/tool_interface_agent.py@@ -36,25 +36,21 @@ class ToolInterfaceAgent(BaseAgent):# Create a new model with the updated schemaself.input_schema = create_model(- self.tool_instance.tool_name,+ self.tool_instance.__class__.__name__,tool_input=(str,Field(...,- description=f"{self.tool_instance.tool_name} tool input. Presented as a single question or instruction",- alias=f"tool_input_{self.tool_instance.tool_name}",+ description=f"{self.tool_instance.__class__.__name__} tool input. Presented as a single question or instruction",+ alias=f"tool_input_{self.tool_instance.__class__.__name__}",),),__base__=BaseIOSchema,+ __doc__=self.tool_instance.tool_description,)- # Manually set the configuration attributes- self.input_schema.model_config["title"] = self.tool_instance.tool_name- self.input_schema.model_config["description"] = self.tool_instance.tool_description- self.input_schema.model_config["json_schema_extra"] = {- "title": self.tool_instance.tool_name,- "description": self.tool_instance.tool_description,- }+ # Set the __name__ attribute of the new model+ self.input_schema.__name__ = self.tool_instance.__class__.__name__output_instructions = ["Make sure the tool call will maximize the utility of the tool in the context of the user input.",@@ -75,13 +71,16 @@ class ToolInterfaceAgent(BaseAgent):output_instructions=output_instructions,)- def get_response(self):+ def get_response(self, response_model=None):"""Handles obtaining and processing the response from the tool.This method gets the response from the tool, formats the tool input, adds it to memory,runs the tool, processes the tool output, and returns the processed response.+ Args:+ response_model: Ignored in this implementation, but included for compatibility with BaseAgent.+Returns:BaseModel: The processed response."""@@ -96,7 +95,7 @@ class ToolInterfaceAgent(BaseAgent):"assistant","I will now formulate a response for the user based on the tool output.",)- response = super().get_response(response_model=self.output_schema)+ response = super().get_response(response_model=response_model or self.output_schema)return responsediff --git a/atomic_agents/lib/models/web_document.py b/atomic_agents/lib/models/web_document.pyindex f21c1e9..3486201 100644--- a/atomic_agents/lib/models/web_document.py+++ b/atomic_agents/lib/models/web_document.py@@ -1,9 +1,11 @@-from pydantic import BaseModel, Field+from pydantic import Fieldfrom atomic_agents.agents.base_agent import BaseIOSchema-class WebDocumentMetadata(BaseModel):+class WebDocumentMetadata(BaseIOSchema):+ """Schema that describes the metadata of a web document."""+url: strtitle: str = Field(default="")description: str = Field(default="")@@ -12,5 +14,7 @@ class WebDocumentMetadata(BaseModel):class WebDocument(BaseIOSchema):+ """Schema that represents the content and metadata of a web document."""+content: strmetadata: WebDocumentMetadata = Field(default_factory=lambda: WebDocumentMetadata(url=""))diff --git a/atomic_agents/lib/tools/calculator_tool.py b/atomic_agents/lib/tools/calculator_tool.pyindex a87c072..cc6b3cb 100644--- a/atomic_agents/lib/tools/calculator_tool.py+++ b/atomic_agents/lib/tools/calculator_tool.py@@ -10,23 +10,22 @@ from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfig# INPUT SCHEMA #################class CalculatorToolInputSchema(BaseIOSchema):- expression: str = Field(..., description="Mathematical expression to evaluate. For example, '2 + 2'.")+ """+ 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.+ """- class Config:- title = "CalculatorTool"- description = (- "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."- )- json_schema_extra = {"title": title, "description": description}+ 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.")diff --git a/atomic_agents/lib/tools/content_scraping_tool.py b/atomic_agents/lib/tools/content_scraping_tool.pyindex 8aa17cc..e60389f 100644--- a/atomic_agents/lib/tools/content_scraping_tool.py+++ b/atomic_agents/lib/tools/content_scraping_tool.py@@ -19,15 +19,12 @@ from atomic_agents.lib.utils.scraping.url_to_markdown import UrlToMarkdownConverclass ContentScrapingToolInputSchema(BaseIOSchema):- url: str = Field(..., description="URL of the web page or PDF to scrape.")+ """+ Tool for scraping web pages or PDFs and converting content to markdown+ in order to extract information or summarize the content.+ """- class Config:- title = "ContentScrapingTool"- description = (- "Tool for scraping web pages or PDFs and converting content to markdown "- "in order to extract information or summarize the content."- )- json_schema_extra = {"title": title, "description": description}+ url: str = Field(..., description="URL of the web page or PDF to scrape.")####################@@ -36,6 +33,8 @@ class ContentScrapingToolInputSchema(BaseIOSchema):class ContentScrapingToolOutputSchema(BaseIOSchema):+ """This schema defines the output of the ContentScrapingTool."""+content: strmetadata: Optional[dict] = Nonediff --git a/atomic_agents/lib/tools/search/serper_tool.py b/atomic_agents/lib/tools/search/serper_tool.pyindex 43df555..5f93401 100644--- a/atomic_agents/lib/tools/search/serper_tool.py+++ b/atomic_agents/lib/tools/search/serper_tool.py@@ -9,28 +9,22 @@ from rich.console import Consolefrom atomic_agents.agents.base_agent import BaseIOSchemafrom 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.+ """--class SerperToolSchema(BaseIOSchema):queries: List[str] = Field(..., description="List of search queries.")- class Config:- title = "SerperTool"- description = (- "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."- )- json_schema_extra = {"title": title, "description": description}-##################### OUTPUT SCHEMA(S) #####################--class SerperResultSchema(BaseIOSchema):url: strtitle: str@@ -45,8 +39,6 @@ class SerperToolOutputSchema(BaseIOSchema):############### TOOL LOGIC ###############--class SerperToolConfig(BaseToolConfig):api_key: str = ""max_results: int = 10@@ -57,13 +49,13 @@ class SerperTool(BaseTool):Tool for performing searches using the Serper API based on the provided queries.Attributes:- input_schema (SerperToolSchema): The schema for the input data.+ 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 = SerperToolSchema+ input_schema = SerperToolInputSchemaoutput_schema = SerperToolOutputSchemadef __init__(self, config: SerperToolConfig = SerperToolConfig()):@@ -78,12 +70,12 @@ class SerperTool(BaseTool):self.api_key = config.api_keyself.max_results = config.max_results- def run(self, params: SerperToolSchema, max_results: Optional[int] = None) -> SerperToolOutputSchema:+ def run(self, params: SerperToolInputSchema, max_results: Optional[int] = None) -> SerperToolOutputSchema:"""Runs the SerperTool with the given parameters.Args:- params (SerperToolSchema): The input parameters for the tool, adhering to the input schema.+ 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:diff --git a/atomic_agents/lib/tools/yelp_restaurant_finder_tool.py b/atomic_agents/lib/tools/yelp_restaurant_finder_tool.pyindex 3f9a3be..b7dd39e 100644--- a/atomic_agents/lib/tools/yelp_restaurant_finder_tool.py+++ b/atomic_agents/lib/tools/yelp_restaurant_finder_tool.py@@ -44,6 +44,11 @@ class PriceRange(Enum):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').")@@ -61,21 +66,13 @@ class YelpSearchToolInputSchema(BaseIOSchema):)limit: Optional[int] = Field(10, description="Number of results to return.")- class Config:- title = "YelpSearchTool"- description = (- "Tool for searching for food using the Yelp API. "- "Returns a list of businesses with details such as name, rating, and address."- )- json_schema_extra = {"title": title, "description": description}-##################### OUTPUT SCHEMA(S) #####################--class YelpSearchResultSchema(BaseIOSchema):+ """This schema represents a single result from the Yelp API."""+name: strurl: strrating: float@@ -86,22 +83,14 @@ class YelpSearchResultSchema(BaseIOSchema):class YelpSearchToolOutputSchema(BaseIOSchema):- results: List[YelpSearchResultSchema]+ """Output schema for the YelpSearchTool, containing a list of search results with details such as name, rating, and address."""- class Config:- title = "YelpSearchToolOutput"- description = (- "Output schema for the YelpSearchTool, containing a list of search results with details"- "such as name, rating, and address."- )- json_schema_extra = {"title": title, "description": description}+ results: List[YelpSearchResultSchema]############### TOOL LOGIC ###############--class YelpSearchToolConfig(BaseToolConfig):api_key: str = ""max_results: int = 10diff --git a/atomic_agents/lib/tools/yt_transcript_scraper_tool.py b/atomic_agents/lib/tools/yt_transcript_scraper_tool.pyindex 6410a5f..085837b 100644--- a/atomic_agents/lib/tools/yt_transcript_scraper_tool.py+++ b/atomic_agents/lib/tools/yt_transcript_scraper_tool.py@@ -9,42 +9,31 @@ from youtube_transcript_api import NoTranscriptFound, TranscriptsDisabled, YouTufrom atomic_agents.agents.base_agent import BaseIOSchemafrom 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).")- class Config:- title = "YouTubeTranscriptTool"- description = (- "Tool for fetching the transcript of a YouTube video using the YouTube Transcript API. "- "Returns the transcript with text, start time, and duration."- )- json_schema_extra = {"title": title, "description": description}-##################### OUTPUT SCHEMA(S) #####################--class YouTubeTranscriptToolOutputSchema(BaseIOSchema):+ """Output schema for the YouTubeTranscriptTool. Contains the transcript text, duration, comments, and metadata."""+transcript: strduration: floatcomments: List[str]metadata: dict- class Config:- title = "YouTubeTranscriptToolOutput"- description = (- "Output schema for the YouTubeTranscriptTool. " "Contains the transcript text, duration, comments, and metadata."- )- json_schema_extra = {"title": title, "description": description}-############### TOOL LOGIC #diff --git a/atomic_agents/lib/utils/format_tool_message.py b/atomic_agents/lib/utils/format_tool_message.pyindex 357930f..ae8ada2 100644--- a/atomic_agents/lib/utils/format_tool_message.py+++ b/atomic_agents/lib/utils/format_tool_message.py@@ -19,11 +19,12 @@ def format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = Nonif tool_id is None:tool_id = str(uuid.uuid4())+ # Get the tool name from the Config.title if available, otherwise use the class namereturn {"id": tool_id,"type": "function","function": {- "name": tool_call.model_config["title"],+ "name": tool_call.__class__.__name__,"arguments": json.dumps(tool_call.model_dump(), separators=(", ", ": ")),},}diff --git a/docs/guides/creating_a_new_tool.md b/docs/guides/creating_a_new_tool.mdindex 9185371..f985016 100644--- a/docs/guides/creating_a_new_tool.md+++ b/docs/guides/creating_a_new_tool.md@@ -24,16 +24,10 @@ from pydantic import Fieldfrom atomic_agents.agents.base_agent import BaseIOSchemaclass MyToolInputSchema(BaseIOSchema):+ """Describe the tool / input schema here, this docstring is used in the LLM's prompt"""+parameter: str = Field(..., description="Description of the parameter.")list_param: list[str] = Field(..., description="A list of strings.")-- class Config:- title = "MyTool"- description = "Description of what MyTool does."- json_schema_extra = {- "title": title,- "description": description- }```#### 2. Define the Output Schema@@ -113,17 +107,11 @@ from rich.console import Console# Input Schemaclass MyToolInputSchema(BaseIOSchema):+ """Input schema for the MyTool tool."""+parameter: str = Field(..., description="Description of the parameter.")list_param: list[str] = Field(..., description="A list of strings.")- class Config:- title = "MyTool"- description = "Description of what MyTool does."- json_schema_extra = {- "title": title,- "description": description- }-# Output Schemaclass MyToolOutputSchema(BaseIOSchema):result: str = Field(..., description="Result of the tool's operation.")diff --git a/examples/deep_article_writer_pipelines/outline_generation_pipeline/agents/outline_gen_agent.py b/examples/deep_article_writer_pipelines/outline_generation_pipeline/agents/outline_gen_agent.pynew file mode 100644index 0000000..289b430--- /dev/null+++ b/examples/deep_article_writer_pipelines/outline_generation_pipeline/agents/outline_gen_agent.py@@ -0,0 +1,56 @@+# outline_gen_agent.py+from pydantic import Field+from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator+import instructor+import openai+++class OutlineAgentInputSchema(BaseIOSchema):+ """+ Input schema for the Outline Generation Agent.+ This schema defines the input structure for generating an article outline.+ """++ instruction: str = Field(..., description="The main topic or instruction for the article.")+ search_results: list = Field(..., description="A list of search results to use as reference for creating the outline.")+++class OutlineAgentOutputSchema(BaseIOSchema):+ """+ Output schema for the Outline Generation Agent.+ This schema defines the structure of the generated article outline.+ """++ reasoning_and_analysis: list[str] = Field(..., description="A list of reasoning and analysis steps for the outline.")+ article_title: str = Field(..., description="The title of the article.")+ section_titles: list[str] = Field(+ ..., description="A list of sections for the article, excluding introduction and conclusion."+ )+++outline_gen_agent = BaseAgent(+ BaseAgentConfig(+ client=instructor.from_openai(openai.OpenAI()),+ model="gpt-4o-mini",+ system_prompt_generator=SystemPromptGenerator(+ background=[+ "You are an expert article outline generator.",+ "Your task is to create a comprehensive outline for an article based on a given topic and search results.",+ ],+ steps=[+ "Analyze the given instruction and search results.",+ "Generate a catchy and informative article title.",+ "Generate 3-5 sections, excluding introduction and concluding sections.",+ ],+ output_instructions=[+ "Provide an article title that accurately reflects the main topic.",+ "Ensure the section titles are clear, concise, and logically ordered.",+ "Do NOT include an introduction or conclusion in the section titles.",+ "Provide a list of reasoning and analysis steps that led to your outline decisions.",+ ],+ ),+ input_schema=OutlineAgentInputSchema,+ output_schema=OutlineAgentOutputSchema,+ )+)diff --git a/examples/deep_article_writer_pipelines/outline_generation_pipeline/agents/query_gen_agent.py b/examples/deep_article_writer_pipelines/outline_generation_pipeline/agents/query_gen_agent.pynew file mode 100644index 0000000..bbdf64a--- /dev/null+++ b/examples/deep_article_writer_pipelines/outline_generation_pipeline/agents/query_gen_agent.py@@ -0,0 +1,41 @@+import instructor+import openai+from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator+from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool+++class QueryAgentInputSchema(BaseIOSchema):+ """+ Input schema for the Query Generation Agent.+ This schema defines the input structure for generating research queries.+ """++ instruction: str = "A detailed instruction or request to generate deep research queries for."+ num_queries: int = "The number of queries to generate."+++# Create the query agent+query_gen_agent = BaseAgent(+ BaseAgentConfig(+ client=instructor.from_openai(openai.OpenAI()),+ model="gpt-4o-mini",+ system_prompt_generator=SystemPromptGenerator(+ background=[+ "You are an intelligent query generation expert.",+ "Your task is to generate a specified number of diverse and highly relevant queries based on a given instruction or request.",+ "The queries should cover different aspects of the instruction to ensure comprehensive exploration.",+ ],+ steps=[+ "You will receive a detailed instruction or request and the number of queries to generate.",+ "Generate the requested number of queries in a JSON format.",+ ],+ output_instructions=[+ "Ensure clarity and conciseness in each query.",+ "Ensure each query is unique and as diverse as possible while remaining relevant to the instruction.",+ ],+ ),+ input_schema=QueryAgentInputSchema,+ output_schema=SearxNGTool.input_schema,+ )+)diff --git a/examples/deep_article_writer_pipelines/outline_generation_pipeline/pipeline.py b/examples/deep_article_writer_pipelines/outline_generation_pipeline/pipeline.pynew file mode 100644index 0000000..e3f783c--- /dev/null+++ b/examples/deep_article_writer_pipelines/outline_generation_pipeline/pipeline.py@@ -0,0 +1,46 @@+import os+from agents.query_gen_agent import query_gen_agent, QueryAgentInputSchema+from agents.outline_gen_agent import outline_gen_agent, OutlineAgentInputSchema+from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig++# Initialize the SearxNG tool+searxng_tool = SearxNGTool(config=SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=5))+++def run_pipeline(instruction: str):+ # Step 1: Generate queries using the query_gen_agent+ query_input = QueryAgentInputSchema(instruction=instruction, num_queries=3)+ generated_queries = query_gen_agent.run(query_input)++ print("Generated queries:")+ for i, query in enumerate(generated_queries.queries, 1):+ print(f"{i}. {query}")++ # Step 2: Use the generated queries with the SearxNG tool+ search_input = SearxNGTool.input_schema(queries=generated_queries.queries, category="general")+ search_results = searxng_tool.run(search_input)++ print("\nSearch results:")+ for i, result in enumerate(search_results.results, 1):+ print(f"\n{i}. {result.title}")+ print(f" URL: {result.url}")+ print(f" Content: {result.content[:100]}...") # Print first 100 characters of content++ # Step 3: Generate article outline+ outline_input = OutlineAgentInputSchema(instruction=instruction, search_results=search_results.results)+ outline = outline_gen_agent.run(outline_input)++ print("\nArticle Outline:")+ print(f"Title: {outline.article_title}")+ print("Sections:")+ for i, section in enumerate(outline.section_titles, 1):+ print(f"{i}. {section}")++ print("\nReasoning and Analysis:")+ for i, step in enumerate(outline.reasoning_and_analysis, 1):+ print(f"{i}. {step}")+++if __name__ == "__main__":+ instruction = "Explain the impact of artificial intelligence on modern healthcare"+ run_pipeline(instruction)diff --git a/examples/minimal_multi_agent_tool_use.py b/examples/minimal_multi_agent_tool_use.pyindex 0098c08..623077b 100644--- a/examples/minimal_multi_agent_tool_use.py+++ b/examples/minimal_multi_agent_tool_use.py@@ -9,6 +9,12 @@ from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInfrom atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfigfrom atomic_agents.lib.tools.calculator_tool import CalculatorTool, CalculatorToolConfig+import logging++# Configure logging+logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")+logger = logging.getLogger(__name__)+console = Console()client = instructor.from_openai(openai.OpenAI())searxng_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=10))@@ -24,13 +30,17 @@ searx_agent = ToolInterfaceAgent(config=search_agent_config)calc_agent = ToolInterfaceAgent(config=calculator_agent_config)UnionResponse = create_model(- "UnionResponse", __base__=BaseIOSchema, response=(Union[searx_agent.input_schema, calc_agent.input_schema], ...)+ "UnionResponse",+ __base__=BaseIOSchema,+ response=(Union[searx_agent.input_schema, calc_agent.input_schema], ...),+ __doc__="This schema represents the output of the orchestration agent, which can be any of the provided agents.",)orchestration_agent = BaseAgent(config=BaseAgentConfig(client=client, model="gpt-4o-mini", output_schema=UnionResponse))while True:- user_input = input("You: ")+ # user_input = input("You: ")+ user_input = "5log(10)-69"if user_input.lower() in ["exit", "quit"]:print("Exiting chat...")breakdiff --git a/examples/notebooks/what_is_atomic_agents.ipynb b/examples/notebooks/what_is_atomic_agents.ipynbindex c6823be..8f169fe 100644--- a/examples/notebooks/what_is_atomic_agents.ipynb+++ b/examples/notebooks/what_is_atomic_agents.ipynb@@ -309,34 +309,22 @@" return JSON(json_str)\n"," \n","class BaseAgentInputSchema(BaseIOSchema):\n",+ " \"\"\"This schema represents the user input message exchanged between the user and the chat agent.\"\"\"\n",+ " \n"," chat_message: str = Field(\n"," ...,\n"," description='The chat message exchanged between the user and the chat agent. '\n"," 'This represents the message sent by the user.'\n"," )\n","\n",- " class Config:\n",- " title = 'BaseAgentInputSchema'\n",- " description = 'This schema represents the user input message exchanged between the user and the chat agent.'\n",- " json_schema_extra = {\n",- " \"title\": title,\n",- " \"description\": description,\n",- " }\n",- "\n","class BaseAgentOutputSchema(BaseIOSchema):\n",+ " \"\"\"This schema represents the response message exchanged between the user and the chat agent.\"\"\"\n",+ " \n"," chat_message: str = Field(\n"," ...,\n"," description='The chat message exchanged between the user and the chat agent. '\n"," 'This contains the markdown-enabled response generated by the chat agent.'\n",- " )\n",- "\n",- " class Config:\n",- " title = 'BaseAgentOutputSchema'\n",- " description = 'This schema represents the response message exchanged between the user and the chat agent.'\n",- " json_schema_extra = {\n",- " \"title\": title,\n",- " \"description\": description,\n",- " }"+ " )"]},{@@ -433,20 +421,14 @@" FOUR = \"4\"\n","\n","class YelpSearchToolInputSchema(BaseIOSchema):\n",+ " \"\"\"This schema represents a single result from the Yelp API.\"\"\"\n",+ " \n"," location: str = Field(..., description=\"Location to search for food.\")\n"," term: Optional[str] = Field(None, description=\"Search term (e.g., 'pizza', 'sushi').\")\n"," categories: Optional[List[YelpCategory]] = Field(None, description=\"Categories to filter by (e.g., 'italian, mexican').\")\n"," 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.\")\n"," open_now: Optional[bool] = Field(False, description=\"Filter for businesses that are open now.\")\n",- " limit: Optional[int] = Field(10, description=\"Number of results to return.\")\n",- "\n",- " class Config:\n",- " title = \"YelpSearchTool\"\n",- " description = \"Tool for searching for food using the Yelp API. Returns a list of businesses with details such as name, rating, and address.\"\n",- " json_schema_extra = {\n",- " \"title\": title,\n",- " \"description\": description\n",- " }"+ " limit: Optional[int] = Field(10, description=\"Number of results to return.\")"]},{@@ -484,15 +466,10 @@" return_raw_output: bool = False\n","\n","class ToolInputModel(BaseIOSchema):\n",+ " \"\"\"This model is used to define the input schema for the tool interface agent.\"\"\"\n",+ " \n"," tool_input: str = Field(..., description=\"Tool input. Presented as a single question or instruction\")\n","\n",- " class Config:\n",- " title = \"Default Tool\"\n",- " description = \"Default tool description\"\n",- " json_schema_extra = {\n",- " \"title\": \"Default Tool\",\n",- " \"description\": \"Default tool description\"\n",- " }\n","\n","class ToolInterfaceAgent(BaseAgent):\n"," \"\"\"\n",diff --git a/examples/notebooks/yelp_agent.ipynb b/examples/notebooks/yelp_agent.ipynbindex 1c75c9a..0cf2902 100644--- a/examples/notebooks/yelp_agent.ipynb+++ b/examples/notebooks/yelp_agent.ipynb@@ -191,15 +191,9 @@"source": ["# Define a custom response schema that can handle both chat responses and Yelp search tool responses\n","class ResponseSchema(BaseModel):\n",- " chosen_schema: Union[BaseAgentOutputSchema, YelpSearchToolInputSchema] = Field(..., description='The response from the chat agent.')\n",- "\n",- " class Config:\n",- " title = 'OutputSchema'\n",- " description = 'The response schema for the chat agent.'\n",- " json_schema_extra = {\n",- " 'title': title,\n",- " 'description': description,\n",- " }"+ " \"\"\"The response schema for the chat agent. The output will either be a chat response, or an API call to the yelp search tool.\"\"\"\n",+ " \n",+ " chosen_schema: Union[BaseAgentOutputSchema, YelpSearchToolInputSchema] = Field(..., description='The response from the chat agent.')"]},{diff --git a/examples/product_finder.py b/examples/product_finder.pyindex 59db91f..05bfacb 100644--- a/examples/product_finder.py+++ b/examples/product_finder.py@@ -56,16 +56,14 @@ searxng_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_UR# Define a custom response schemaclass OutputSchema(BaseIOSchema):+ """Output schema for the agent."""+internal_reasoning: List[str] = Field(..., description="The internal reasoning behind the response.")chosen_schema: Union[BaseAgentOutputSchema, SearxNGToolInputSchema] = Field(...,description="The response from the chat agent. Every response must use chosen_schema to indicate the type of response (A chat message, or a search request)",)- class Config:- title = "OutputSchema"- description = "The response schema for the chat agent."-# Create a config for the chat agentagent_config = BaseAgentConfig(diff --git a/examples/yelp_restaurant_finder.py b/examples/yelp_restaurant_finder.pyindex afea64f..acf5790 100644--- a/examples/yelp_restaurant_finder.py+++ b/examples/yelp_restaurant_finder.py@@ -53,18 +53,12 @@ yelp_tool = YelpSearchTool(YelpSearchToolConfig(api_key=os.getenv("YELP_API_KEY"# Define a custom response schema that can handle both chat responses and Yelp search tool responsesclass OutputSchema(BaseModel):+ """The output schema for the agent."""+chosen_schema: Union[BaseAgentOutputSchema, YelpSearchToolInputSchema] = Field(..., description="The response from the chat agent.")- class Config:- title = "OutputSchema"- description = "The response schema for the chat agent."- json_schema_extra = {- "title": title,- "description": description,- }-# Create a config for the chat agentagent_config = BaseAgentConfig(diff --git a/tests/agents/test_base_agent.py b/tests/agents/test_base_agent.pyindex c3ce128..c16a37b 100644--- a/tests/agents/test_base_agent.py+++ b/tests/agents/test_base_agent.py@@ -1,7 +1,8 @@import pytest-from unittest.mock import Mock, call+from unittest.mock import Mock, call, patchfrom pydantic import BaseModelimport instructor+import inspectfrom atomic_agents.agents.base_agent import (BaseIOSchema,BaseAgent,@@ -10,15 +11,17 @@ from atomic_agents.agents.base_agent import (BaseAgentOutputSchema,SystemPromptGenerator,AgentMemory,- SystemPromptContextProviderBase+ SystemPromptContextProviderBase,)+@pytest.fixturedef mock_instructor():mock = Mock(spec=instructor.Instructor)mock.chat.completions.create = Mock()return mock+@pytest.fixturedef mock_memory():mock = Mock(spec=AgentMemory)@@ -27,6 +30,7 @@ def mock_memory():mock.copy = Mock(return_value=Mock(spec=AgentMemory))return mock+@pytest.fixturedef mock_system_prompt_generator():mock = Mock(spec=SystemPromptGenerator)@@ -34,19 +38,19 @@ def mock_system_prompt_generator():mock.context_providers = {}return mock+@pytest.fixturedef agent_config(mock_instructor, mock_memory, mock_system_prompt_generator):return BaseAgentConfig(- client=mock_instructor,- model="gpt-4o-mini",- memory=mock_memory,- system_prompt_generator=mock_system_prompt_generator+ client=mock_instructor, model="gpt-4o-mini", memory=mock_memory, system_prompt_generator=mock_system_prompt_generator)+@pytest.fixturedef agent(agent_config):return BaseAgent(agent_config)+def test_initialization(agent, mock_instructor, mock_memory, mock_system_prompt_generator):assert agent.client == mock_instructorassert agent.model == "gpt-4o-mini"@@ -55,79 +59,79 @@ def test_initialization(agent, mock_instructor, mock_memory, mock_system_prompt_assert agent.input_schema == BaseAgentInputSchemaassert agent.output_schema == BaseAgentOutputSchema+def test_reset_memory(agent, mock_memory):initial_memory = agent.initial_memoryagent.reset_memory()assert agent.memory != initial_memorymock_memory.copy.assert_called_once()+def test_get_response(agent, mock_instructor, mock_memory, mock_system_prompt_generator):- mock_memory.get_history.return_value = [{'role': 'user', 'content': 'Hello'}]+ mock_memory.get_history.return_value = [{"role": "user", "content": "Hello"}]mock_system_prompt_generator.generate_prompt.return_value = "System prompt"-+mock_response = Mock(spec=BaseAgentOutputSchema)mock_instructor.chat.completions.create.return_value = mock_response-+response = agent.get_response()-+assert response == mock_response-+mock_instructor.chat.completions.create.assert_called_once_with(model="gpt-4o-mini",- messages=[- {'role': 'system', 'content': 'System prompt'},- {'role': 'user', 'content': 'Hello'}- ],- response_model=BaseAgentOutputSchema+ messages=[{"role": "system", "content": "System prompt"}, {"role": "user", "content": "Hello"}],+ response_model=BaseAgentOutputSchema,)+def test_run(agent):mock_input = BaseAgentInputSchema(chat_message="Test input")mock_output = BaseAgentOutputSchema(chat_message="Test output")-+agent._init_run = Mock()agent._pre_run = Mock()agent._post_run = Mock()agent.get_response = Mock(return_value=mock_output)-+result = agent.run(mock_input)-+assert result == mock_outputagent._init_run.assert_called_once_with(mock_input)agent._pre_run.assert_called_once()agent.get_response.assert_called_once()agent._post_run.assert_called_once_with(mock_output)+def test_get_context_provider(agent, mock_system_prompt_generator):mock_provider = Mock(spec=SystemPromptContextProviderBase)- mock_system_prompt_generator.context_providers = {- 'test_provider': mock_provider- }-- result = agent.get_context_provider('test_provider')+ mock_system_prompt_generator.context_providers = {"test_provider": mock_provider}++ result = agent.get_context_provider("test_provider")assert result == mock_provider-+with pytest.raises(KeyError):- agent.get_context_provider('non_existent_provider')+ agent.get_context_provider("non_existent_provider")+def test_register_context_provider(agent, mock_system_prompt_generator):mock_provider = Mock(spec=SystemPromptContextProviderBase)- agent.register_context_provider('new_provider', mock_provider)-- assert 'new_provider' in mock_system_prompt_generator.context_providers- assert mock_system_prompt_generator.context_providers['new_provider'] == mock_provider+ agent.register_context_provider("new_provider", mock_provider)++ assert "new_provider" in mock_system_prompt_generator.context_providers+ assert mock_system_prompt_generator.context_providers["new_provider"] == mock_provider+def test_unregister_context_provider(agent, mock_system_prompt_generator):mock_provider = Mock(spec=SystemPromptContextProviderBase)- mock_system_prompt_generator.context_providers = {- 'test_provider': mock_provider- }-- agent.unregister_context_provider('test_provider')- assert 'test_provider' not in mock_system_prompt_generator.context_providers-+ mock_system_prompt_generator.context_providers = {"test_provider": mock_provider}++ agent.unregister_context_provider("test_provider")+ assert "test_provider" not in mock_system_prompt_generator.context_providers+with pytest.raises(KeyError):- agent.unregister_context_provider('non_existent_provider')+ agent.unregister_context_provider("non_existent_provider")+def test_custom_input_output_schemas(mock_instructor):class CustomInputSchema(BaseModel):@@ -137,49 +141,59 @@ def test_custom_input_output_schemas(mock_instructor):result: strcustom_config = BaseAgentConfig(- client=mock_instructor,- model="gpt-4o-mini",- input_schema=CustomInputSchema,- output_schema=CustomOutputSchema+ client=mock_instructor, model="gpt-4o-mini", input_schema=CustomInputSchema, output_schema=CustomOutputSchema)-+custom_agent = BaseAgent(custom_config)-+assert custom_agent.input_schema == CustomInputSchemaassert custom_agent.output_schema == CustomOutputSchema-+def test_base_agent_io_str_and_rich():class TestIO(BaseIOSchema):+ """TestIO docstring"""+field: strtest_io = TestIO(field="test")assert str(test_io) == '{"field":"test"}'assert test_io.__rich__() is not None # Just check if it returns something, as we can't easily compare Rich objects-def test_base_agent_input_output_schema_config():- assert BaseAgentInputSchema.Config.title == "BaseAgentInputSchema"- assert "description" in BaseAgentInputSchema.Config.json_schema_extra-- assert BaseAgentOutputSchema.Config.title == "BaseAgentOutputSchema"- assert "description" in BaseAgentOutputSchema.Config.json_schema_extra# Update the existing test_run function to use the actual methods instead of mocksdef test_run(agent, mock_memory):mock_input = BaseAgentInputSchema(chat_message="Test input")mock_output = BaseAgentOutputSchema(chat_message="Test output")-+agent.get_response = Mock(return_value=mock_output)-+result = agent.run(mock_input)-+assert result == mock_outputassert agent.current_user_input == mock_input-- mock_memory.add_message.assert_has_calls([- call("user", str(mock_input)),- call("assistant", str(mock_output))- ])--if __name__ == '__main__':- pytest.main()++ mock_memory.add_message.assert_has_calls([call("user", str(mock_input)), call("assistant", str(mock_output))])+++def test_base_io_schema_empty_docstring():+ with pytest.raises(ValueError, match="must have a non-empty docstring"):++ class EmptyDocStringSchema(BaseIOSchema):+ """"""++ pass+++def test_base_io_schema_model_json_schema_no_description():+ class TestSchema(BaseIOSchema):+ """Test schema docstring."""++ field: str++ # Mock the superclass model_json_schema to return a schema without a description+ with patch("pydantic.BaseModel.model_json_schema", return_value={}):+ schema = TestSchema.model_json_schema()++ assert "description" in schema+ assert schema["description"] == "Test schema docstring."diff --git a/tests/agents/test_tool_interface_agent.py b/tests/agents/test_tool_interface_agent.pyindex d912ae8..d6a69da 100644--- a/tests/agents/test_tool_interface_agent.py+++ b/tests/agents/test_tool_interface_agent.py@@ -7,15 +7,16 @@ from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInfrom atomic_agents.lib.tools.base_tool import BaseToolfrom atomic_agents.agents.base_agent import BaseIOSchema, BaseAgentOutputSchema+class MockTool(BaseTool):class InputSchema(BaseIOSchema):- query: str = Field(..., description="The query to process")+ """Mock input schema"""- class Config:- title = "MockTool"- description = "A mock tool for testing"+ query: str = Field(..., description="The query to process")class OutputSchema(BaseIOSchema):+ """Mock output schema"""+result: str = Field(..., description="The result of the tool operation")input_schema = InputSchema@@ -24,49 +25,51 @@ class MockTool(BaseTool):def run(self, params: InputSchema) -> OutputSchema:return self.OutputSchema(result=f"Processed: {params.query}")+@pytest.fixturedef mock_tool():return MockTool()+@pytest.fixturedef mock_instructor():mock = Mock(spec=instructor.Instructor)mock.chat.completions.create = Mock()return mock+@pytest.fixturedef tool_interface_agent(mock_tool, mock_instructor):- config = ToolInterfaceAgentConfig(- client=mock_instructor,- model="gpt-4o-mini",- tool_instance=mock_tool,- return_raw_output=False- )+ config = ToolInterfaceAgentConfig(client=mock_instructor, model="gpt-4o-mini", tool_instance=mock_tool)return ToolInterfaceAgent(config)+def test_tool_interface_agent_initialization(tool_interface_agent, mock_tool):assert tool_interface_agent.tool_instance == mock_tool- assert tool_interface_agent.return_raw_output == Falseassert tool_interface_agent.input_schema.__name__ == "MockTool"assert issubclass(tool_interface_agent.input_schema, BaseIOSchema)assert tool_interface_agent.output_schema == BaseAgentOutputSchema+def test_tool_interface_agent_input_schema(tool_interface_agent):- assert 'tool_input' in tool_interface_agent.input_schema.model_fields- assert tool_interface_agent.input_schema.model_fields['tool_input'].alias == 'tool_input_MockTool'- assert tool_interface_agent.input_schema.model_config['title'] == "MockTool"- assert "A mock tool for testing" in tool_interface_agent.input_schema.model_config['description']--@patch('atomic_agents.agents.base_agent.BaseAgent.get_response')-@patch('atomic_agents.lib.utils.format_tool_message.format_tool_message')-def test_tool_interface_agent_get_response_without_raw_output(mock_format_tool_message, mock_get_response, tool_interface_agent):+ assert "tool_input" in tool_interface_agent.input_schema.model_fields+ assert tool_interface_agent.input_schema.model_fields["tool_input"].alias == "tool_input_MockTool"+++@patch("atomic_agents.agents.base_agent.BaseAgent.get_response")+@patch("atomic_agents.lib.utils.format_tool_message.format_tool_message")+def test_tool_interface_agent_get_response(mock_format_tool_message, mock_get_response, tool_interface_agent):mock_tool_input = tool_interface_agent.input_schema(tool_input_MockTool="Test query")mock_tool_output = MockTool.OutputSchema(result="Mocked result")mock_final_response = Mock()mock_get_response.side_effect = [mock_tool_input, mock_final_response]tool_interface_agent.tool_instance.run = Mock(return_value=mock_tool_output)- mock_format_tool_message.return_value = {"id": "test_id", "type": "function", "function": {"name": "MockTool", "arguments": "{}"}}+ mock_format_tool_message.return_value = {+ "id": "test_id",+ "type": "function",+ "function": {"name": "MockTool", "arguments": "{}"},+ }response = tool_interface_agent.get_response()@@ -74,32 +77,9 @@ def test_tool_interface_agent_get_response_without_raw_output(mock_format_tool_massert mock_get_response.call_count == 2assert response == mock_final_response-@patch('atomic_agents.agents.base_agent.BaseAgent.get_response')-@patch('atomic_agents.lib.utils.format_tool_message.format_tool_message')-def test_tool_interface_agent_get_response_with_raw_output(mock_format_tool_message, mock_get_response, mock_tool, mock_instructor):- config = ToolInterfaceAgentConfig(- client=mock_instructor,- model="gpt-4o-mini",- tool_instance=mock_tool,- return_raw_output=True- )- agent = ToolInterfaceAgent(config)-- mock_tool_input = agent.input_schema(tool_input_MockTool="Test query")- mock_tool_output = MockTool.OutputSchema(result="Mocked result")-- mock_get_response.return_value = mock_tool_input- agent.tool_instance.run = Mock(return_value=mock_tool_output)- mock_format_tool_message.return_value = {"id": "test_id", "type": "function", "function": {"name": "MockTool", "arguments": "{}"}}-- response = agent.get_response()-- agent.tool_instance.run.assert_called_once_with(mock_tool_input)- assert mock_get_response.call_count == 1- assert response == mock_tool_output-@patch('atomic_agents.agents.base_agent.BaseAgent.get_response')-@patch('atomic_agents.lib.utils.format_tool_message.format_tool_message')+@patch("atomic_agents.agents.base_agent.BaseAgent.get_response")+@patch("atomic_agents.lib.utils.format_tool_message.format_tool_message")def test_tool_interface_agent_memory_updates(mock_format_tool_message, mock_get_response, tool_interface_agent):mock_input = tool_interface_agent.input_schema(tool_input_MockTool="Test query")mock_tool_output = MockTool.OutputSchema(result="Mocked result")@@ -107,20 +87,24 @@ def test_tool_interface_agent_memory_updates(mock_format_tool_message, mock_get_mock_get_response.side_effect = [mock_input, mock_final_response]tool_interface_agent.tool_instance.run = Mock(return_value=mock_tool_output)- mock_format_tool_message.return_value = {"id": "test_id", "type": "function", "function": {"name": "MockTool", "arguments": "{}"}}+ mock_format_tool_message.return_value = {+ "id": "test_id",+ "type": "function",+ "function": {"name": "MockTool", "arguments": "{}"},+ }tool_interface_agent.run(mock_input)history = tool_interface_agent.memory.get_history()-+# Check for TOOL CALL messageassert any("TOOL CALL:" in msg.content for msg in history if isinstance(msg.content, str))-+# Check for TOOL RESPONSE messageassert any("TOOL RESPONSE:" in msg.content for msg in history if isinstance(msg.content, str))-+# Check if the mocked result is in the memoryassert any("Mocked result" in msg.content for msg in history if isinstance(msg.content, str))-+# Assert that at least 3 messages were added (TOOL CALL, TOOL RESPONSE, and possibly the final response)assert len(history) >= 3diff --git a/tests/lib/tools/test_base_tool.py b/tests/lib/tools/test_base_tool.pyindex fed8103..8f07e12 100644--- a/tests/lib/tools/test_base_tool.py+++ b/tests/lib/tools/test_base_tool.py@@ -3,15 +3,20 @@ from pydantic import BaseModelfrom atomic_agents.lib.tools.base_tool import BaseToolConfig, BaseToolfrom atomic_agents.agents.base_agent import BaseIOSchema+# Mock classes for testingclass MockInputSchema(BaseIOSchema):- class Config:- title = "Mock Input"- description = "Mock input description"+ """Mock input schema for testing"""++ query: str+class MockOutputSchema(BaseIOSchema):+ """Mock output schema for testing"""+result: str+class MockTool(BaseTool):input_schema = MockInputSchemaoutput_schema = MockOutputSchema@@ -19,20 +24,24 @@ class MockTool(BaseTool):def run(self, params: MockInputSchema) -> MockOutputSchema:return MockOutputSchema(result="Mock result")+def test_base_tool_config_creation():config = BaseToolConfig()assert config.title is Noneassert config.description is None+def test_base_tool_config_with_values():config = BaseToolConfig(title="Test Tool", description="Test description")assert config.title == "Test Tool"assert config.description == "Test description"+def test_base_tool_initialization():tool = MockTool()- assert tool.tool_name == "Mock Input"- assert tool.tool_description == "Mock input description"+ assert tool.tool_name == "MockInputSchema"+ assert tool.tool_description == "Mock input schema for testing"+def test_base_tool_with_config():config = BaseToolConfig(title="Custom Title", description="Custom description")@@ -40,6 +49,14 @@ def test_base_tool_with_config():assert tool.tool_name == "Custom Title"assert tool.tool_description == "Custom description"++def test_base_tool_with_custom_title():+ config = BaseToolConfig(title="Custom Tool Name")+ tool = MockTool(config=config)+ assert tool.tool_name == "Custom Tool Name"+ assert tool.tool_description == "Mock input schema for testing"++def test_base_tool_run_not_implemented():class UnimplementedTool(BaseTool):input_schema = MockInputSchema@@ -47,30 +64,36 @@ def test_base_tool_run_not_implemented():tool = UnimplementedTool()with pytest.raises(NotImplementedError):- tool.run(MockInputSchema())+ tool.run(MockInputSchema(query="mock query"))+def test_mock_tool_run():tool = MockTool()- result = tool.run(MockInputSchema())+ result = tool.run(MockInputSchema(query="mock query"))assert isinstance(result, MockOutputSchema)assert result.result == "Mock result"+def test_base_tool_input_schema():tool = MockTool()assert tool.input_schema == MockInputSchema+def test_base_tool_output_schema():tool = MockTool()assert tool.output_schema == MockOutputSchema+def test_base_tool_inheritance():tool = MockTool()assert isinstance(tool, BaseTool)+def test_base_tool_config_is_pydantic_model():assert issubclass(BaseToolConfig, BaseModel)+def test_base_tool_config_optional_fields():config = BaseToolConfig()- assert hasattr(config, 'title')- assert hasattr(config, 'description')\ No newline at end of file+ assert hasattr(config, "title")+ assert hasattr(config, "description")diff --git a/tests/lib/tools/test_calculator_tool.py b/tests/lib/tools/test_calculator_tool.pyindex 9290dc0..e232ac3 100644--- a/tests/lib/tools/test_calculator_tool.py+++ b/tests/lib/tools/test_calculator_tool.py@@ -1,41 +1,55 @@import pytest-from atomic_agents.lib.tools.calculator_tool import CalculatorTool, CalculatorToolInputSchema, CalculatorToolOutputSchema, CalculatorToolConfig+from atomic_agents.lib.tools.calculator_tool import (+ CalculatorTool,+ CalculatorToolInputSchema,+ CalculatorToolOutputSchema,+ CalculatorToolConfig,+)from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfig+def test_calculator_tool_initialization():tool = CalculatorTool()assert isinstance(tool, BaseTool)- assert tool.tool_name == "CalculatorTool"+ assert tool.tool_name == "CalculatorToolInputSchema"assert "Tool for performing calculations" in tool.tool_description+def test_calculator_tool_with_custom_config():config = CalculatorToolConfig(title="Custom Calculator", description="Custom description")tool = CalculatorTool(config=config)assert tool.tool_name == "Custom Calculator"assert tool.tool_description == "Custom description"+def test_calculator_tool_input_schema():tool = CalculatorTool()assert tool.input_schema == CalculatorToolInputSchema+def test_calculator_tool_output_schema():tool = CalculatorTool()assert tool.output_schema == CalculatorToolOutputSchema[email protected]("expression, expected_result", [- ("2 + 2", "4.00000000000000"),- ("3 * 4", "12.0000000000000"),- ("10 / 2", "5.00000000000000"),- ("2 ** 3", "8.00000000000000"),- ("sin(pi/2)", "1.00000000000000"),- ("log(E)", "1.00000000000000"), # Changed from "log(e)" to "log(E)"-])++ "expression, expected_result",+ [+ ("2 + 2", "4.00000000000000"),+ ("3 * 4", "12.0000000000000"),+ ("10 / 2", "5.00000000000000"),+ ("2 ** 3", "8.00000000000000"),+ ("sin(pi/2)", "1.00000000000000"),+ ("log(E)", "1.00000000000000"), # Changed from "log(e)" to "log(E)"+ ],+)def test_calculator_tool_run_valid_expressions(expression, expected_result):tool = CalculatorTool()result = tool.run(CalculatorToolInputSchema(expression=expression))assert isinstance(result, CalculatorToolOutputSchema)assert result.result == expected_result+def test_calculator_tool_run_complex_expression():tool = CalculatorTool()expression = "sqrt(3**2 + 4**2)"@@ -43,12 +57,14 @@ def test_calculator_tool_run_complex_expression():assert isinstance(result, CalculatorToolOutputSchema)assert result.result == "5.00000000000000"+def test_calculator_tool_run_invalid_expression():tool = CalculatorTool()invalid_expression = "invalid + expression"result = tool.run(CalculatorToolInputSchema(expression=invalid_expression))assert isinstance(result, CalculatorToolOutputSchema)- assert set(result.result.split(' + ')) == set(invalid_expression.split(' + '))+ assert set(result.result.split(" + ")) == set(invalid_expression.split(" + "))+def test_calculator_tool_run_division_by_zero():tool = CalculatorTool()@@ -56,17 +72,19 @@ def test_calculator_tool_run_division_by_zero():assert isinstance(result, CalculatorToolOutputSchema)assert result.result == "zoo" # SymPy returns "zoo" for complex infinity+def test_calculator_tool_run_with_variables():tool = CalculatorTool()result = tool.run(CalculatorToolInputSchema(expression="x + y"))assert isinstance(result, CalculatorToolOutputSchema)assert result.result == "x + y" # The tool doesn't evaluate expressions with variables+def test_calculator_tool_config_is_pydantic_model():assert issubclass(CalculatorToolConfig, BaseToolConfig)+def test_calculator_tool_config_optional_fields():config = CalculatorToolConfig()- assert hasattr(config, 'title')- assert hasattr(config, 'description')-+ assert hasattr(config, "title")+ assert hasattr(config, "description")diff --git a/tests/lib/tools/test_content_scraping_tool.py b/tests/lib/tools/test_content_scraping_tool.pyindex bef15c0..b12f171 100644--- a/tests/lib/tools/test_content_scraping_tool.py+++ b/tests/lib/tools/test_content_scraping_tool.py@@ -10,30 +10,38 @@ from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfigfrom atomic_agents.lib.utils.scraping.pdf_to_markdown import PdfToMarkdownConverterfrom atomic_agents.lib.utils.scraping.url_to_markdown import UrlToMarkdownConverter+def test_content_scraping_tool_initialization():tool = ContentScrapingTool()assert isinstance(tool, BaseTool)- assert tool.tool_name == "ContentScrapingTool"+ assert tool.tool_name == "ContentScrapingToolInputSchema"assert "Tool for scraping web pages or PDFs" in tool.tool_description+def test_content_scraping_tool_with_custom_config():config = ContentScrapingToolConfig(title="Custom Scraper", description="Custom description")tool = ContentScrapingTool(config=config)assert tool.tool_name == "Custom Scraper"assert tool.tool_description == "Custom description"+def test_content_scraping_tool_input_schema():tool = ContentScrapingTool()assert tool.input_schema == ContentScrapingToolInputSchema+def test_content_scraping_tool_output_schema():tool = ContentScrapingTool()assert tool.output_schema == ContentScrapingToolOutputSchema[email protected]("content_type, expected_converter", [- ("application/pdf", PdfToMarkdownConverter),- ("text/html", UrlToMarkdownConverter),-])++ "content_type, expected_converter",+ [+ ("application/pdf", PdfToMarkdownConverter),+ ("text/html", UrlToMarkdownConverter),+ ],+)@patch("atomic_agents.lib.tools.content_scraping_tool.requests.head")def test_content_scraping_tool_run(mock_head, content_type, expected_converter):mock_response = MagicMock()@@ -52,6 +60,7 @@ def test_content_scraping_tool_run(mock_head, content_type, expected_converter):assert result.content == "Mocked content"assert result.metadata == {"key": "value"}+@patch("atomic_agents.lib.tools.content_scraping_tool.requests.head")def test_content_scraping_tool_run_unknown_content_type(mock_head):mock_response = MagicMock()@@ -70,19 +79,23 @@ def test_content_scraping_tool_run_unknown_content_type(mock_head):assert result.content == "Mocked content"assert result.metadata == {"key": "value"}+def test_content_scraping_tool_schema_fields():schema = ContentScrapingToolInputSchema(url="https://example.com")assert schema.url == "https://example.com"+def test_content_scraping_tool_output_schema_fields():output = ContentScrapingToolOutputSchema(content="Test content", metadata={"key": "value"})assert output.content == "Test content"assert output.metadata == {"key": "value"}+def test_content_scraping_tool_config_is_pydantic_model():assert issubclass(ContentScrapingToolConfig, BaseToolConfig)+def test_content_scraping_tool_config_optional_fields():config = ContentScrapingToolConfig()- assert hasattr(config, 'title')- assert hasattr(config, 'description')\ No newline at end of file+ assert hasattr(config, "title")+ assert hasattr(config, "description")diff --git a/tests/lib/utils/test_format_tool_message.py b/tests/lib/utils/test_format_tool_message.pyindex 36bccce..fd624ce 100644--- a/tests/lib/utils/test_format_tool_message.py+++ b/tests/lib/utils/test_format_tool_message.py@@ -1,91 +1,94 @@import uuidfrom pydantic import BaseModelimport pytest+from atomic_agents.agents.base_agent import BaseIOSchemafrom atomic_agents.lib.utils.format_tool_message import format_tool_message+# Mock classes for testingclass MockToolCall(BaseModel):+ """Mock class for testing"""+param1: strparam2: int- class Config:- title = "MockTool"def test_format_tool_message_with_provided_tool_id():tool_call = MockToolCall(param1="test", param2=42)tool_id = "test-tool-id"-+result = format_tool_message(tool_call, tool_id)-+assert result == {"id": "test-tool-id","type": "function",- "function": {- "name": "MockTool",- "arguments": '{"param1": "test", "param2": 42}'- }+ "function": {"name": "MockToolCall", "arguments": '{"param1": "test", "param2": 42}'},}+def test_format_tool_message_without_tool_id():tool_call = MockToolCall(param1="test", param2=42)-+result = format_tool_message(tool_call)-+assert isinstance(result["id"], str)assert len(result["id"]) == 36 # UUID lengthassert result["type"] == "function"- assert result["function"]["name"] == "MockTool"+ assert result["function"]["name"] == "MockToolCall"assert result["function"]["arguments"] == '{"param1": "test", "param2": 42}'+def test_format_tool_message_with_different_tool():class AnotherToolCall(BaseModel):+ """Another tool schema"""+field1: boolfield2: float- class Config:- title = "AnotherTool"-tool_call = AnotherToolCall(field1=True, field2=3.14)-+result = format_tool_message(tool_call)-+assert result["type"] == "function"- assert result["function"]["name"] == "AnotherTool"+ assert result["function"]["name"] == "AnotherToolCall"assert result["function"]["arguments"] == '{"field1": true, "field2": 3.14}'+def test_format_tool_message_id_is_valid_uuid():tool_call = MockToolCall(param1="test", param2=42)-+result = format_tool_message(tool_call)-+try:uuid.UUID(result["id"])except ValueError:pytest.fail("The generated tool_id is not a valid UUID")+def test_format_tool_message_consistent_output():tool_call = MockToolCall(param1="test", param2=42)tool_id = "fixed-id"-+result1 = format_tool_message(tool_call, tool_id)result2 = format_tool_message(tool_call, tool_id)-+assert result1 == result2+def test_format_tool_message_with_complex_model():- class ComplexToolCall(BaseModel):+ class ComplexToolCall(BaseIOSchema):+ """Mock complex tool call schema"""+nested: dictlist_field: list- class Config:- title = "ComplexTool"+ tool_call = ComplexToolCall(nested={"key": "value"}, list_field=[1, 2, 3])- tool_call = ComplexToolCall(- nested={"key": "value"},- list_field=[1, 2, 3]- )-result = format_tool_message(tool_call)-- assert result["function"]["name"] == "ComplexTool"- assert result["function"]["arguments"] == '{"nested": {"key": "value"}, "list_field": [1, 2, 3]}'\ No newline at end of file++ assert result["function"]["name"] == "ComplexToolCall"+ assert result["function"]["arguments"] == '{"nested": {"key": "value"}, "list_field": [1, 2, 3]}'+++if __name__ == "__main__":+ pytest.main()