Skip to content

Building AI agents, atomically

Adopted type parameters, modified files in atomic-examples accordingly

Koichi KAWAMURA7a9c2e163de0
diff --git a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
index d5f07c4..29c7245 100644
--- a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
+++ b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
@@ -3,6 +3,7 @@ import logging
from typing import Any, List, Type, Optional, Union, Tuple, cast
from contextlib import AsyncExitStack
import shlex
+import types
from pydantic import create_model, Field, BaseModel
@@ -193,23 +194,30 @@ class MCPToolFactory:
logger.error(f"Error executing MCP tool '{bound_tool_name}': {e}", exc_info=True)
raise RuntimeError(f"Failed to execute MCP tool '{bound_tool_name}': {e}") from e
- # Create the tool class
- tool_class = type(
+ # Create the tool class using types.new_class() instead of type()
+ attrs = {
+ "run": run_tool_sync,
+ "__doc__": tool_description,
+ "mcp_tool_name": tool_name,
+ "mcp_endpoint": self.mcp_endpoint,
+ "use_stdio": self.use_stdio,
+ "_client_session": self.client_session,
+ "_event_loop": self.event_loop,
+ "working_directory": self.working_directory,
+ }
+
+ # Create the class using new_class() for proper generic type support
+ tool_class = types.new_class(
tool_name,
- (BaseTool,),
- {
- "input_schema": InputSchema,
- "output_schema": OutputSchema,
- "run": run_tool_sync,
- "__doc__": tool_description,
- "mcp_tool_name": tool_name,
- "mcp_endpoint": self.mcp_endpoint,
- "use_stdio": self.use_stdio,
- "_client_session": self.client_session,
- "_event_loop": self.event_loop,
- "working_directory": self.working_directory,
- },
+ (BaseTool[InputSchema, OutputSchema],),
+ {},
+ lambda ns: ns.update(attrs)
)
+
+ # Add the input_schema and output_schema class attributes explicitly
+ # since they might not be properly inherited with types.new_class
+ setattr(tool_class, "input_schema", InputSchema)
+ setattr(tool_class, "output_schema", OutputSchema)
generated_tools.append(tool_class)
diff --git a/atomic-examples/deep-research/deep_research/main.py b/atomic-examples/deep-research/deep_research/main.py
index f4877e1..8e8198d 100644
--- a/atomic-examples/deep-research/deep_research/main.py
+++ b/atomic-examples/deep-research/deep_research/main.py
@@ -173,7 +173,7 @@ def chat_loop() -> None:
while True:
user_message = console.input("\n[bold blue]Your question:[/bold blue] ").strip()
- if user_message.lower() == "exit":
+ if user_message.lower() in ["/exit", "/quit"]:
console.print("\n[bold]πŸ‘‹ Goodbye! Thanks for using Deep Research.[/bold]")
break
diff --git a/atomic-examples/deep-research/poetry.lock b/atomic-examples/deep-research/poetry.lock
index 23e1a7b..54ef2d6 100644
--- a/atomic-examples/deep-research/poetry.lock
+++ b/atomic-examples/deep-research/poetry.lock
@@ -160,7 +160,7 @@ trio = ["trio (>=0.26.1)"]
[[package]]
name = "atomic-agents"
-version = "1.0.16"
+version = "1.1.0"
description = "A versatile framework for creating and managing intelligent agents."
optional = false
python-versions = ">=3.12,<4.0"
@@ -2173,6 +2173,52 @@ files = [
{file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"},
]
+[[package]]
+name = "typing-inspection"
+version = "0.4.0"
+description = "Runtime typing introspection tools"
+optional = false
+python-versions = ">=3.9"
+groups = ["main"]
+files = [
+ {file = "typing_inspection-0.4.0-py3-none-any.whl", hash = "sha256:50e72559fcd2a6367a19f7a7e610e6afcb9fac940c650290eed893d61386832f"},
+ {file = "typing_inspection-0.4.0.tar.gz", hash = "sha256:9765c87de36671694a67904bf2c96e395be9c6439bb6c87b5142569dcdd65122"},
+]
+
+[package.dependencies]
+typing-extensions = ">=4.12.0"
+
+[[package]]
+name = "tzdata"
+version = "2025.2"
+description = "Provider of IANA time zone data"
+optional = false
+python-versions = ">=2"
+groups = ["main"]
+markers = "platform_system == \"Windows\""
+files = [
+ {file = "tzdata-2025.2-py2.py3-none-any.whl", hash = "sha256:1a403fada01ff9221ca8044d701868fa132215d84beb92242d9acd2147f667a8"},
+ {file = "tzdata-2025.2.tar.gz", hash = "sha256:b60a638fcc0daffadf82fe0f57e53d06bdec2f36c4df66280ae79bce6bd6f2b9"},
+]
+
+[[package]]
+name = "tzlocal"
+version = "5.3.1"
+description = "tzinfo object for the local timezone"
+optional = false
+python-versions = ">=3.9"
+groups = ["main"]
+files = [
+ {file = "tzlocal-5.3.1-py3-none-any.whl", hash = "sha256:eb1a66c3ef5847adf7a834f1be0800581b683b5608e74f86ecbcef8ab91bb85d"},
+ {file = "tzlocal-5.3.1.tar.gz", hash = "sha256:cceffc7edecefea1f595541dbd6e990cb1ea3d19bf01b2809f362a03dd7921fd"},
+]
+
+[package.dependencies]
+tzdata = {version = "*", markers = "platform_system == \"Windows\""}
+
+[package.extras]
+devenv = ["check-manifest", "pytest (>=4.3)", "pytest-cov", "pytest-mock (>=3.3)", "zest.releaser"]
+
[[package]]
name = "uc-micro-py"
version = "1.0.3"
@@ -2223,7 +2269,7 @@ click = ">=7.0"
h11 = ">=0.8"
[package.extras]
-standard = ["colorama (>=0.4)", "httptools (>=0.6.3)", "python-dotenv (>=0.13)", "pyyaml (>=5.1)", "uvloop (>=0.14.0,!=0.15.0,!=0.15.1)", "watchfiles (>=0.13)", "websockets (>=10.4)"]
+standard = ["colorama (>=0.4) ; sys_platform == \"win32\"", "httptools (>=0.6.3)", "python-dotenv (>=0.13)", "pyyaml (>=5.1)", "uvloop (>=0.14.0,!=0.15.0,!=0.15.1) ; sys_platform != \"win32\" and sys_platform != \"cygwin\" and platform_python_implementation != \"PyPy\"", "watchfiles (>=0.13)", "websockets (>=10.4)"]
[[package]]
name = "yarl"
@@ -2324,5 +2370,5 @@ propcache = ">=0.2.0"
[metadata]
lock-version = "2.1"
-python-versions = "^3.11"
-content-hash = "607c2bbc0001117884749bc7dbfb468be318090b45daff5d6caee92233a4d43e"
+python-versions = ">=3.12,<4.0"
+content-hash = "b22ee4c1dccfd4866fb4a28c565790ecb8f78cb00a85692a189dc6ac0c591e17"
diff --git a/atomic-examples/mcp-agent/README.md b/atomic-examples/mcp-agent/README.md
index 1a5216b..5342c37 100644
--- a/atomic-examples/mcp-agent/README.md
+++ b/atomic-examples/mcp-agent/README.md
@@ -9,6 +9,7 @@ This example consists of two main components:
### 1. Example Client (`example-client/`)
An interactive agent that:
+
- Connects to MCP servers using either STDIO or SSE transport
- Dynamically discovers available tools
- Processes natural language queries
@@ -21,6 +22,7 @@ An interactive agent that:
### 2. Example MCP Server (`example-mcp-server/`)
A server that:
+
- Provides MCP tools and resources
- Supports both STDIO and SSE (HTTP) transport methods
- Includes example tools for demonstration
@@ -50,18 +52,21 @@ This example shows the flexibility of the MCP architecture with two distinct tra
## Getting Started
1. Clone the repository:
+
```bash
git clone https://github.com/BrainBlend-AI/atomic-agents
cd atomic-agents/atomic-examples/mcp-agent
```
2. Set up the server:
+
```bash
cd example-mcp-server
poetry install
```
3. Set up the client:
+
```bash
cd ../example-client
poetry install
@@ -70,22 +75,26 @@ This example shows the flexibility of the MCP architecture with two distinct tra
4. Run the example:
**Using STDIO transport (default):**
+
```bash
cd example-client
poetry run python -m example_client.main
```
**Using SSE transport:**
+
```bash
# First terminal: Start the server
cd example-mcp-server
- poetry run example-mcp-server --mode=sse
+ poetry run example-mcp-server/server.py --mode=sse
- # Second terminal: Run the client
+ # Second terminal: Run the client with SSE transport
cd example-client
poetry run python -m example_client.main --transport sse
```
+ **Note:** When using SSE transport, make sure the server is running before starting the client. The server runs on port 6969 by default.
+
## Example Queries
The example includes a set of basic arithmetic tools that demonstrate the agent's capability to break down and solve complex mathematical expressions:
@@ -122,6 +131,7 @@ For more complex expressions like `((4**3)-10)/100)**2`, the agent:
5. Uses `MultiplyNumbers` again for the final squaring operation
Each step in the conversation shows:
+
- The tool being executed
- The parameters being used
- The intermediate result
diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_sse.py b/atomic-examples/mcp-agent/example-client/example_client/main_sse.py
index c37889b..d743fa2 100644
--- a/atomic-examples/mcp-agent/example-client/example_client/main_sse.py
+++ b/atomic-examples/mcp-agent/example-client/example_client/main_sse.py
@@ -2,6 +2,7 @@
from atomic_agents.lib.factories.mcp_tool_factory import fetch_mcp_tools
from rich.console import Console
from rich.table import Table
+from rich.markdown import Markdown
import openai
import os
import instructor
@@ -11,6 +12,7 @@ from atomic_agents.lib.components.system_prompt_generator import SystemPromptGen
from atomic_agents.lib.components.agent_memory import AgentMemory
from typing import Union, Type, Dict
from dataclasses import dataclass
+import re
# 1. Configuration and environment setup
@@ -81,6 +83,34 @@ class OrchestratorOutputSchema(BaseIOSchema):
action: ActionUnion = Field( # type: ignore[reportInvalidTypeForm]
..., description="The chosen action: either a tool's input schema instance or a final response schema instance."
)
+
+ model_config = {"arbitrary_types_allowed": True}
+
+
+# Helper function to format mathematical expressions for better terminal readability
+def format_math_expressions(text):
+ """
+ Format LaTeX-style math expressions for better readability in the terminal.
+
+ Args:
+ text (str): Text containing LaTeX-style math expressions
+
+ Returns:
+ str: Text with formatted math expressions
+ """
+ # Replace \( and \) with formatted brackets
+ text = re.sub(r'\\[\(\)]', '', text)
+
+ # Replace LaTeX multiplication symbol with a plain x
+ text = text.replace('\\times', 'Γ—')
+
+ # Format other common LaTeX symbols
+ text = text.replace('\\cdot', 'Β·')
+ text = text.replace('\\div', 'Γ·')
+ text = text.replace('\\sqrt', '√')
+ text = text.replace('\\pi', 'Ο€')
+
+ return text
# 3. Main logic and script entry point
@@ -93,13 +123,25 @@ def main():
table.add_column("Input Schema", style="yellow")
table.add_column("Description", style="magenta")
for ToolClass in tools:
- schema_name = ToolClass.input_schema.__name__ if hasattr(ToolClass, "input_schema") else "N/A"
+ # Fix to handle when input_schema is a property or doesn't have __name__
+ if hasattr(ToolClass, "input_schema"):
+ if hasattr(ToolClass.input_schema, "__name__"):
+ schema_name = ToolClass.input_schema.__name__
+ else:
+ # If it's a property, try to get the type name of the actual class
+ try:
+ schema_instance = ToolClass.input_schema
+ schema_name = schema_instance.__class__.__name__
+ except Exception:
+ schema_name = "Unknown Schema"
+ else:
+ schema_name = "N/A"
table.add_row(ToolClass.mcp_tool_name, schema_name, ToolClass.__doc__ or "")
console.print(table)
# Create and initialize orchestrator agent
console.print("[dim]β€’ Creating orchestrator agent...[/dim]")
memory = AgentMemory()
- orchestrator_agent = BaseAgent(
+ orchestrator_agent = BaseAgent[MCPOrchestratorInputSchema, OrchestratorOutputSchema](
BaseAgentConfig(
client=client,
model=config.openai_model,
@@ -124,9 +166,7 @@ def main():
"4. Maintain a professional and helpful tone in all responses.",
"5. Break down complex queries into sequential tool calls before giving the final answer via `FinalResponseSchema`.",
],
- ),
- input_schema=MCPOrchestratorInputSchema,
- output_schema=OrchestratorOutputSchema,
+ )
)
)
console.print("[green]Successfully created orchestrator agent.[/green]")
@@ -142,16 +182,158 @@ def main():
try:
# Initial run with user query
orchestrator_output = orchestrator_agent.run(MCPOrchestratorInputSchema(query=query))
- action_instance = orchestrator_output.action
- reasoning = orchestrator_output.reasoning
+
+ # Debug output to see what's actually in the output
+ console.print(f"[dim]Debug - orchestrator_output type: {type(orchestrator_output)}, fields: {orchestrator_output.model_dump()}")
+
+ # The model is returning a BaseAgentOutputSchema instead of OrchestratorOutputSchema
+ # We need to handle this case by creating a FinalResponseSchema directly
+ if hasattr(orchestrator_output, 'chat_message') and not hasattr(orchestrator_output, 'action'):
+ console.print("[yellow]Note: Converting BaseAgentOutputSchema to FinalResponseSchema[/yellow]")
+ action_instance = FinalResponseSchema(response_text=orchestrator_output.chat_message)
+ reasoning = "Response generated directly from chat model"
+ # Handle the original expected format if it exists
+ elif hasattr(orchestrator_output, 'action'):
+ action_instance = orchestrator_output.action
+ reasoning = orchestrator_output.reasoning if hasattr(orchestrator_output, 'reasoning') else "No reasoning provided"
+ else:
+ console.print("[yellow]Warning: Unexpected response format. Unable to process.[/yellow]")
+ continue
+
console.print(f"[cyan]Orchestrator reasoning:[/cyan] {reasoning}")
# Keep executing until we get a final response
while not isinstance(action_instance, FinalResponseSchema):
+ # Handle the case where action_instance is a dictionary
+ if isinstance(action_instance, dict):
+ console.print("[yellow]Warning: Received dictionary instead of schema object. Attempting to convert...[/yellow]")
+ console.print(f"[dim]Dictionary contents: {action_instance}[/dim]")
+
+ # Special handling for function-call format {"recipient_name": "functions.toolname", "parameters": {...}}
+ if "recipient_name" in action_instance and "parameters" in action_instance:
+ console.print("[yellow]Detected function call format with recipient_name and parameters[/yellow]")
+ recipient = action_instance.get("recipient_name", "")
+ parameters = action_instance.get("parameters", {})
+
+ # Extract tool name from recipient (format might be "functions.toolname")
+ tool_parts = recipient.split(".")
+ if len(tool_parts) > 1:
+ tool_name = tool_parts[-1] # Take last part after the dot
+ console.print(f"[yellow]Extracted tool name '{tool_name}' from recipient '{recipient}'[/yellow]")
+
+ # Special case for calculator
+ if tool_name.lower() == "calculate":
+ tool_name = "Calculator"
+ console.print(f"[yellow]Mapped 'calculate' to 'Calculator' tool[/yellow]")
+
+ # Try to find a matching tool class by name
+ matching_tool = next((t for t in tools if t.mcp_tool_name.lower() == tool_name.lower()), None)
+
+ if matching_tool:
+ try:
+ # Create an instance using the parameters
+ action_instance = matching_tool.input_schema(**parameters)
+ console.print(f"[green]Successfully created {matching_tool.input_schema.__name__} from function call format[/green]")
+ continue
+ except Exception as e:
+ console.print(f"[red]Error creating schema from function parameters: {e}[/red]")
+
+ # Try to find a tool_name in the dictionary (original approach)
+ tool_name = action_instance.get("tool_name")
+
+ # If tool_name is not found, try alternative approaches to identify the tool
+ if not tool_name:
+ # Approach 1: Look for a field that might contain a tool name
+ for key in action_instance.keys():
+ if "tool" in key.lower():
+ tool_name = action_instance.get(key)
+ if tool_name:
+ console.print(f"[yellow]Found potential tool name '{tool_name}' in field '{key}'[/yellow]")
+ break
+
+ # Approach 2: Try to match dictionary fields with tool schemas
+ if not tool_name:
+ console.print("[yellow]Trying to match dictionary fields with available tools...[/yellow]")
+ best_match = None
+ best_match_score = 0
+
+ for ToolClass in tools:
+ if not hasattr(ToolClass, "input_schema"):
+ continue
+
+ # Try to create a sample instance to get field names
+ try:
+ schema_fields = set(ToolClass.input_schema.__annotations__.keys() if hasattr(ToolClass.input_schema, "__annotations__") else [])
+ dict_fields = set(action_instance.keys())
+
+ # Count matching fields
+ matching_fields = len(schema_fields.intersection(dict_fields))
+ if matching_fields > best_match_score and matching_fields > 0:
+ best_match_score = matching_fields
+ best_match = ToolClass
+ console.print(f"[dim]Found {matching_fields} matching fields with {ToolClass.mcp_tool_name}[/dim]")
+ except Exception as e:
+ console.print(f"[dim]Error checking {getattr(ToolClass, 'mcp_tool_name', 'unknown tool')}: {str(e)}[/dim]")
+
+ if best_match:
+ tool_name = best_match.mcp_tool_name
+ console.print(f"[yellow]Best matching tool: {tool_name} with {best_match_score} matching fields[/yellow]")
+
+ if not tool_name:
+ # Final fallback: Check if this might be a final response
+ if any(key in action_instance for key in ["response_text", "text", "response", "message", "content"]):
+ response_content = action_instance.get("response_text") or action_instance.get("text") or action_instance.get("response") or action_instance.get("message") or action_instance.get("content") or "No message content found"
+ console.print("[yellow]Appears to be a final response. Converting directly.[/yellow]")
+ action_instance = FinalResponseSchema(response_text=response_content)
+ continue
+
+ console.print("[red]Error: Could not determine tool type from dictionary[/red]")
+ # Create a final response with an error message
+ action_instance = FinalResponseSchema(
+ response_text="I encountered an internal error. The tool could not be determined from the response. Please try rephrasing your question."
+ )
+ break
+
+ # Try to find a matching tool class by name
+ matching_tool = next((t for t in tools if t.mcp_tool_name == tool_name), None)
+ if not matching_tool:
+ console.print(f"[red]Error: No tool found with name {tool_name}[/red]")
+ # Create a final response with an error message
+ action_instance = FinalResponseSchema(
+ response_text=f"I encountered an internal error. Could not find tool named '{tool_name}'."
+ )
+ break
+
+ # Create an instance of the input schema with the dictionary data
+ try:
+ # Remove tool_name if it's not a field in the schema
+ params = {}
+ has_annotations = hasattr(matching_tool.input_schema, "__annotations__")
+
+ for k, v in action_instance.items():
+ # Include the key-value pair if it's not "tool_name" or if it's a valid field in the schema
+ if k not in ["tool_name"] or (has_annotations and k in matching_tool.input_schema.__annotations__.keys()):
+ params[k] = v
+
+ action_instance = matching_tool.input_schema(**params)
+ console.print(f"[green]Successfully converted dictionary to {matching_tool.input_schema.__name__}[/green]")
+ except Exception as e:
+ console.print(f"[red]Error creating schema instance: {e}[/red]")
+ # Create a final response with an error message
+ action_instance = FinalResponseSchema(
+ response_text=f"I encountered an internal error when trying to use the {tool_name} tool: {str(e)}"
+ )
+ break
+
schema_type = type(action_instance)
ToolClass = tool_schema_to_class_map.get(schema_type)
if not ToolClass:
- raise ValueError(f"Unknown schema type '" f"{schema_type.__name__}" f"' returned by orchestrator")
+ console.print(f"[red]Unknown schema type '{schema_type.__name__}' returned by orchestrator[/red]")
+ # Create a final response with an error message
+ action_instance = FinalResponseSchema(
+ response_text="I encountered an internal error. The tool type could not be recognized."
+ )
+ break
tool_name = ToolClass.mcp_tool_name
console.print(f"[blue]Executing tool:[/blue] {tool_name}")
@@ -169,12 +351,31 @@ def main():
# Run the agent again without parameters to continue the flow
orchestrator_output = orchestrator_agent.run()
- action_instance = orchestrator_output.action
- reasoning = orchestrator_output.reasoning
+
+ # Debug output for subsequent responses
+ console.print(f"[dim]Debug - subsequent orchestrator_output type: {type(orchestrator_output)}, fields: {orchestrator_output.model_dump()}")
+
+ # Handle different response formats
+ if hasattr(orchestrator_output, 'chat_message') and not hasattr(orchestrator_output, 'action'):
+ console.print("[yellow]Note: Converting BaseAgentOutputSchema to FinalResponseSchema[/yellow]")
+ action_instance = FinalResponseSchema(response_text=orchestrator_output.chat_message)
+ reasoning = "Response generated directly from chat model"
+ elif hasattr(orchestrator_output, 'action'):
+ action_instance = orchestrator_output.action
+ reasoning = orchestrator_output.reasoning if hasattr(orchestrator_output, 'reasoning') else "No reasoning provided"
+ else:
+ console.print("[yellow]Warning: Unexpected response format. Unable to process.[/yellow]")
+ break
+
console.print(f"[cyan]Orchestrator reasoning:[/cyan] {reasoning}")
# Final response from the agent
- console.print(f"[bold blue]Agent:[/bold blue] {action_instance.response_text}")
+ response_text = getattr(action_instance, 'response_text',
+ getattr(action_instance, 'chat_message', str(action_instance)))
+ md = Markdown(response_text)
+ # Render the response as markdown
+ console.print(f"[bold blue]Agent: [/bold blue]")
+ console.print(md)
except Exception as e:
console.print(f"[red]Error processing query:[/red] {str(e)}")
diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py b/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py
index 7bea079..85d72ca 100644
--- a/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py
+++ b/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py
@@ -114,6 +114,8 @@ class OrchestratorOutputSchema(BaseIOSchema):
action: ActionUnion = Field( # type: ignore[reportInvalidTypeForm]
..., description="The chosen action: either a tool's input schema instance or a final response schema instance."
)
+
+ model_config = {"arbitrary_types_allowed": True}
# 3. Main logic and script entry point
diff --git a/atomic-examples/mcp-agent/example-mcp-server/poetry.lock b/atomic-examples/mcp-agent/example-mcp-server/poetry.lock
index dfe662e..96f20d0 100644
--- a/atomic-examples/mcp-agent/example-mcp-server/poetry.lock
+++ b/atomic-examples/mcp-agent/example-mcp-server/poetry.lock
@@ -1,4 +1,4 @@
-# This file is automatically @generated by Poetry 2.0.1 and should not be changed by hand.
+# This file is automatically @generated by Poetry 2.1.2 and should not be changed by hand.
[[package]]
name = "annotated-types"
@@ -25,14 +25,13 @@ files = [
]
[package.dependencies]
-exceptiongroup = {version = ">=1.0.2", markers = "python_version < \"3.11\""}
idna = ">=2.8"
sniffio = ">=1.1"
typing_extensions = {version = ">=4.5", markers = "python_version < \"3.13\""}
[package.extras]
doc = ["Sphinx (>=8.2,<9.0)", "packaging", "sphinx-autodoc-typehints (>=1.2.0)", "sphinx_rtd_theme"]
-test = ["anyio[trio]", "blockbuster (>=1.5.23)", "coverage[toml] (>=7)", "exceptiongroup (>=1.2.0)", "hypothesis (>=4.0)", "psutil (>=5.9)", "pytest (>=7.0)", "trustme", "truststore (>=0.9.1)", "uvloop (>=0.21)"]
+test = ["anyio[trio]", "blockbuster (>=1.5.23)", "coverage[toml] (>=7)", "exceptiongroup (>=1.2.0)", "hypothesis (>=4.0)", "psutil (>=5.9)", "pytest (>=7.0)", "trustme", "truststore (>=0.9.1) ; python_version >= \"3.10\"", "uvloop (>=0.21) ; platform_python_implementation == \"CPython\" and platform_system != \"Windows\" and python_version < \"3.14\""]
trio = ["trio (>=0.26.1)"]
[[package]]
@@ -75,22 +74,6 @@ files = [
{file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
]
-[[package]]
-name = "exceptiongroup"
-version = "1.2.2"
-description = "Backport of PEP 654 (exception groups)"
-optional = false
-python-versions = ">=3.7"
-groups = ["main"]
-markers = "python_version < \"3.11\""
-files = [
- {file = "exceptiongroup-1.2.2-py3-none-any.whl", hash = "sha256:3111b9d131c238bec2f8f516e123e14ba243563fb135d3fe885990585aa7795b"},
- {file = "exceptiongroup-1.2.2.tar.gz", hash = "sha256:47c2edf7c6738fafb49fd34290706d1a1a2f4d1c6df275526b62cbb4aa5393cc"},
-]
-
-[package.extras]
-test = ["pytest (>=6)"]
-
[[package]]
name = "h11"
version = "0.14.0"
@@ -144,7 +127,7 @@ httpcore = "==1.*"
idna = "*"
[package.extras]
-brotli = ["brotli", "brotlicffi"]
+brotli = ["brotli ; platform_python_implementation == \"CPython\"", "brotlicffi ; platform_python_implementation != \"CPython\""]
cli = ["click (==8.*)", "pygments (==2.*)", "rich (>=10,<14)"]
http2 = ["h2 (>=3,<5)"]
socks = ["socksio (==1.*)"]
@@ -263,7 +246,7 @@ typing-inspection = ">=0.4.0"
[package.extras]
email = ["email-validator (>=2.0.0)"]
-timezone = ["tzdata"]
+timezone = ["tzdata ; python_version >= \"3.9\" and platform_system == \"Windows\""]
[[package]]
name = "pydantic-core"
@@ -446,7 +429,6 @@ files = [
[package.dependencies]
markdown-it-py = ">=2.2.0"
pygments = ">=2.13.0,<3.0.0"
-typing-extensions = {version = ">=4.0.0,<5.0", markers = "python_version < \"3.11\""}
[package.extras]
jupyter = ["ipywidgets (>=7.5.1,<9)"]
@@ -573,12 +555,11 @@ files = [
[package.dependencies]
click = ">=7.0"
h11 = ">=0.8"
-typing-extensions = {version = ">=4.0", markers = "python_version < \"3.11\""}
[package.extras]
-standard = ["colorama (>=0.4)", "httptools (>=0.6.3)", "python-dotenv (>=0.13)", "pyyaml (>=5.1)", "uvloop (>=0.14.0,!=0.15.0,!=0.15.1)", "watchfiles (>=0.13)", "websockets (>=10.4)"]
+standard = ["colorama (>=0.4) ; sys_platform == \"win32\"", "httptools (>=0.6.3)", "python-dotenv (>=0.13)", "pyyaml (>=5.1)", "uvloop (>=0.14.0,!=0.15.0,!=0.15.1) ; sys_platform != \"win32\" and sys_platform != \"cygwin\" and platform_python_implementation != \"PyPy\"", "watchfiles (>=0.13)", "websockets (>=10.4)"]
[metadata]
lock-version = "2.1"
-python-versions = ">=3.10"
-content-hash = "6b654da82cf3c93a2a39746906d418f29810499560f22a482f24843e23f2ca21"
+python-versions = ">=3.12.0"
+content-hash = "f019279978915791d091244ec047bc353fb0aaf920697afbceae26eb66783989"
diff --git a/atomic-examples/mcp-agent/example-mcp-server/pyproject.toml b/atomic-examples/mcp-agent/example-mcp-server/pyproject.toml
index da2d17b..3ec1cbc 100644
--- a/atomic-examples/mcp-agent/example-mcp-server/pyproject.toml
+++ b/atomic-examples/mcp-agent/example-mcp-server/pyproject.toml
@@ -3,6 +3,7 @@ name = "example-mcp-server"
version = "0.1.0"
description = "example-mcp-server MCP server"
authors = []
+requires-python = ">=3.12.0"
dependencies = [
"mcp[cli]",
"rich>=13.0.0",
diff --git a/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py b/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py
index 820c59c..e3eed86 100644
--- a/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py
+++ b/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py
@@ -72,29 +72,34 @@ class CurrentDateProvider(SystemPromptContextProviderBase):
######################
# ORCHESTRATOR AGENT #
######################
+orchestrator_agent_config = BaseAgentConfig(
+ client=instructor.from_openai(openai.OpenAI()),
+ model="gpt-4o-mini",
+ system_prompt_generator=SystemPromptGenerator(
+ background=[
+ "You are an Orchestrator Agent that decides between using a search tool or a calculator tool based on user input.",
+ "Use the search tool for queries requiring factual information, current events, or specific data.",
+ "Use the calculator tool for mathematical calculations and expressions.",
+ ],
+ output_instructions=[
+ "Analyze the input to determine whether it requires a web search or a calculation.",
+ "For search queries, use the 'search' tool and provide 1-3 relevant search queries.",
+ "For calculations, use the 'calculator' tool and provide the mathematical expression to evaluate.",
+ "When uncertain, prefer using the search tool.",
+ "Format the output using the appropriate schema.",
+ ],
+ ),
+)
orchestrator_agent = BaseAgent[OrchestratorInputSchema, OrchestratorOutputSchema](
- BaseAgentConfig(
- client=instructor.from_openai(openai.OpenAI()),
- model="gpt-4o-mini",
- system_prompt_generator=SystemPromptGenerator(
- background=[
- "You are an Orchestrator Agent that decides between using a search tool or a calculator tool based on user input.",
- "Use the search tool for queries requiring factual information, current events, or specific data.",
- "Use the calculator tool for mathematical calculations and expressions.",
- ],
- output_instructions=[
- "Analyze the input to determine whether it requires a web search or a calculation.",
- "For search queries, use the 'search' tool and provide 1-3 relevant search queries.",
- "For calculations, use the 'calculator' tool and provide the mathematical expression to evaluate.",
- "When uncertain, prefer using the search tool.",
- "Format the output using the appropriate schema.",
- ],
- ),
- )
+ config=orchestrator_agent_config
+)
+orchestrator_agent_final = BaseAgent[OrchestratorInputSchema, FinalAnswerSchema](
+ config=orchestrator_agent_config
)
# Register the current date provider
orchestrator_agent.register_context_provider("current_date", CurrentDateProvider("Current Date"))
+orchestrator_agent_final.register_context_provider("current_date", CurrentDateProvider("Current Date"))
def execute_tool(
@@ -171,11 +176,14 @@ if __name__ == "__main__":
console.print("\n" + "-" * 80 + "\n")
- orchestrator_agent.output_schema = FinalAnswerSchema
+ # Switch agent
+ memory = orchestrator_agent.memory
+ orchestrator_agent = orchestrator_agent_final
+ orchestrator_agent.memory = memory
orchestrator_agent.memory.add_message("system", response)
final_answer = orchestrator_agent.run(input_schema)
console.print(f"\n[bold blue]Final Answer:[/bold blue] {final_answer.final_answer}")
- orchestrator_agent.output_schema = OrchestratorOutputSchema
-
- # Reset the memory after each response
- orchestrator_agent.memory = AgentMemory()
+ # Reset the agent to the original
+ orchestrator_agent = BaseAgent[OrchestratorInputSchema, OrchestratorOutputSchema](
+ config=orchestrator_agent_config
+ )
diff --git a/atomic-examples/youtube-summarizer/youtube_summarizer/tools/youtube_transcript_scraper.py b/atomic-examples/youtube-summarizer/youtube_summarizer/tools/youtube_transcript_scraper.py
index 464cd86..3bc1d99 100644
--- a/atomic-examples/youtube-summarizer/youtube_summarizer/tools/youtube_transcript_scraper.py
+++ b/atomic-examples/youtube-summarizer/youtube_summarizer/tools/youtube_transcript_scraper.py
@@ -156,7 +156,8 @@ class YouTubeTranscriptTool(BaseTool[YouTubeTranscriptToolInputSchema, YouTubeTr
Raises:
Exception: If no metadata is found for the video.
"""
- youtube = build("youtube", "v3", developerKey=self.api_key)
+ api_key = os.getenv("YOUTUBE_API_KEY")
+ youtube = build("youtube", "v3", developerKey=api_key)
request = youtube.videos().list(part="snippet", id=video_id)
response = request.execute()
@@ -182,7 +183,6 @@ if __name__ == "__main__":
load_dotenv()
rich_console = Console()
- api_key = os.getenv("YOUTUBE_API_KEY")
search_tool_instance = YouTubeTranscriptTool(config=YouTubeTranscriptToolConfig())
search_input = YouTubeTranscriptTool.input_schema(video_url="https://www.youtube.com/watch?v=t1e8gqXLbsU", language="en")
diff --git a/atomic-examples/youtube-to-recipe/README.md b/atomic-examples/youtube-to-recipe/README.md
index b30bb09..70333e7 100644
--- a/atomic-examples/youtube-to-recipe/README.md
+++ b/atomic-examples/youtube-to-recipe/README.md
@@ -7,16 +7,19 @@ This directory contains the YouTube Recipe Extractor example for the Atomic Agen
To get started with the YouTube Recipe Extractor:
1. **Clone the main Atomic Agents repository:**
+
```bash
git clone https://github.com/BrainBlend-AI/atomic-agents
```
2. **Navigate to the YouTube Recipe Extractor directory:**
+
```bash
cd atomic-agents/atomic-examples/youtube-to-recipe
```
3. **Install the dependencies using Poetry:**
+
```bash
poetry install
```
@@ -24,6 +27,7 @@ To get started with the YouTube Recipe Extractor:
4. **Set up environment variables:**
Create a `.env` file in the `youtube-to-recipe` directory with the following content:
+
```env
OPENAI_API_KEY=your_openai_api_key
YOUTUBE_API_KEY=your_youtube_api_key
@@ -34,6 +38,7 @@ To get started with the YouTube Recipe Extractor:
Replace `your_openai_api_key` and `your_youtube_api_key` with your actual API keys.
5. **Run the YouTube Recipe Extractor:**
+
```bash
poetry run python youtube_to_recipe/main.py
```
@@ -43,6 +48,7 @@ To get started with the YouTube Recipe Extractor:
### 1. Agent (`agent.py`)
This module defines the `YouTubeRecipeExtractionAgent`, responsible for extracting structured recipe information from cooking video transcripts. It extracts:
+
- Recipe name and description
- Ingredients with quantities and units
- Step-by-step cooking instructions
@@ -61,6 +67,7 @@ The entry point for the YouTube Recipe Extractor application. It orchestrates fe
## Example Output
The agent extracts recipe information in a structured format including:
+
- Detailed ingredient lists with measurements
- Step-by-step cooking instructions with timing and temperature
- Required kitchen equipment
diff --git a/atomic-examples/youtube-to-recipe/youtube_to_recipe/tools/youtube_transcript_scraper.py b/atomic-examples/youtube-to-recipe/youtube_to_recipe/tools/youtube_transcript_scraper.py
index 93c4485..02d0869 100644
--- a/atomic-examples/youtube-to-recipe/youtube_to_recipe/tools/youtube_transcript_scraper.py
+++ b/atomic-examples/youtube-to-recipe/youtube_to_recipe/tools/youtube_transcript_scraper.py
@@ -153,7 +153,8 @@ class YouTubeTranscriptTool(BaseTool[YouTubeTranscriptToolInputSchema, YouTubeTr
Raises:
Exception: If no metadata is found for the video.
"""
- youtube = build("youtube", "v3", developerKey=self.api_key)
+ api_key = os.getenv("YOUTUBE_API_KEY")
+ youtube = build("youtube", "v3", developerKey=api_key)
request = youtube.videos().list(part="snippet", id=video_id)
response = request.execute()
@@ -179,7 +180,6 @@ if __name__ == "__main__":
load_dotenv()
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")
diff --git a/docs/api/agents.md b/docs/api/agents.md
index 88a70fc..17d8d99 100644
--- a/docs/api/agents.md
+++ b/docs/api/agents.md
@@ -4,7 +4,7 @@
The Atomic Agents framework uses Pydantic for schema validation and serialization. All input and output schemas follow this inheritance pattern:
-```
+```PlainText
pydantic.BaseModel
└── BaseIOSchema
β”œβ”€β”€ BaseAgentInputSchema
diff --git a/docs/api/components.md b/docs/api/components.md
index c2a8508..b85e5ef 100644
--- a/docs/api/components.md
+++ b/docs/api/components.md
@@ -194,12 +194,14 @@ class MyTool(BaseTool[MyToolInputSchema, MyToolOutputSchema]):
```
Key features:
+
- Structured input/output schemas
- Configuration management
- Title and description overrides
- Error handling
For full API details:
+
```{eval-rst}
.. automodule:: atomic_agents.lib.components.agent_memory
:members: