Skip to content

Building AI agents, atomically

formatting, start refactoring to use docstrings instead of config class

KennyVaneetveldeacc41697b987
diff --git a/atomic_agents/agents/base_agent.py b/atomic_agents/agents/base_agent.py
index c96ecfd..c67e883 100644
--- a/atomic_agents/agents/base_agent.py
+++ b/atomic_agents/agents/base_agent.py
@@ -1,7 +1,9 @@
-from typing import Optional, Type
+from pydantic import BaseModel, ConfigDict, Field, validator
+from typing import Dict, Any, Optional, Type
+import inspect
import instructor
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field
from rich.json import JSON
from atomic_agents.lib.components.agent_memory import AgentMemory
@@ -9,10 +11,6 @@ from atomic_agents.lib.components.system_prompt_generator import SystemPromptCon
class BaseIOSchema(BaseModel):
- """
- Base class for input and output schemas for chat agents.
- """
-
def __str__(self):
return self.model_dump_json()
@@ -20,23 +18,46 @@ class BaseIOSchema(BaseModel):
json_str = self.model_dump_json()
return JSON(json_str)
+ @classmethod
+ def __pydantic_init_subclass__(cls, **kwargs):
+ super().__pydantic_init_subclass__(**kwargs)
+ cls._validate_description()
+
+ @classmethod
+ def _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)
+
+ @classmethod
+ def model_json_schema(cls, *args, **kwargs):
+ schema = super().model_json_schema(*args, **kwargs)
+ if "description" not in schema and cls.__doc__:
+ schema["description"] = inspect.cleandoc(cls.__doc__)
+ return schema
+
class BaseAgentInputSchema(BaseIOSchema):
+ """This schema represents the input from the user to the AI agent."""
+
chat_message: str = Field(
...,
description="The chat message sent by the user to the assistant.",
)
- class Config:
- title = "BaseAgentInputSchema"
- description = "This schema represents the user input message exchanged between the user and the chat agent."
- json_schema_extra = {
- "title": title,
- "description": description,
- }
-
class BaseAgentOutputSchema(BaseIOSchema):
+ """This schema represents the response generated by the chat agent."""
+
chat_message: str = Field(
...,
description=(
@@ -45,14 +66,6 @@ class BaseAgentOutputSchema(BaseIOSchema):
),
)
- class Config:
- title = "BaseAgentOutputSchema"
- description = "This schema represents the response message exchanged between the user and the chat agent."
- json_schema_extra = {
- "title": title,
- "description": description,
- }
-
class BaseAgentConfig(BaseModel):
client: instructor.client.Instructor = Field(..., description="Client for interacting with the language model.")
@@ -190,3 +203,74 @@ class BaseAgent:
del self.system_prompt_generator.context_providers[provider_name]
else:
raise KeyError(f"Context provider '{provider_name}' not found.")
+
+
+if __name__ == "__main__":
+ from rich.console import Console
+ from rich.panel import Panel
+ from rich.table import Table
+ from rich.syntax import Syntax
+ from rich import box
+ import instructor
+ import openai
+ from pydantic import BaseModel, Field
+
+ # Initialize the agent
+ client = instructor.from_openai(openai.OpenAI())
+ config = BaseAgentConfig(
+ client=client,
+ model="gpt-4o-mini",
+ )
+ agent = BaseAgent(config)
+
+ # Create a Rich console
+ console = Console()
+
+ # Print agent information
+ console.print(Panel.fit("[bold blue]Agent Information[/bold blue]", border_style="blue", padding=(1, 1)))
+
+ # Print input schema
+ input_schema_table = Table(title="Input Schema", box=box.ROUNDED)
+ input_schema_table.add_column("Field", style="cyan")
+ input_schema_table.add_column("Type", style="magenta")
+ input_schema_table.add_column("Description", style="green")
+
+ for field_name, field in agent.input_schema.model_fields.items():
+ input_schema_table.add_row(field_name, str(field.annotation), field.description or "")
+
+ console.print(input_schema_table)
+
+ # Print output schema
+ output_schema_table = Table(title="Output Schema", box=box.ROUNDED)
+ output_schema_table.add_column("Field", style="cyan")
+ output_schema_table.add_column("Type", style="magenta")
+ output_schema_table.add_column("Description", style="green")
+
+ for field_name, field in agent.output_schema.model_fields.items():
+ output_schema_table.add_row(field_name, str(field.annotation), field.description or "")
+
+ console.print(output_schema_table)
+
+ # Print other agent information
+ info_table = Table(title="Agent Configuration", box=box.ROUNDED)
+ info_table.add_column("Property", style="cyan")
+ info_table.add_column("Value", style="yellow")
+
+ info_table.add_row("Model", agent.model)
+ info_table.add_row("Memory", str(type(agent.memory).__name__))
+ info_table.add_row("System Prompt Generator", str(type(agent.system_prompt_generator).__name__))
+
+ console.print(info_table)
+
+ # Print a sample of the system prompt
+ system_prompt = agent.system_prompt_generator.generate_prompt()
+ console.print(
+ Panel(
+ Syntax(system_prompt, "markdown", theme="monokai", line_numbers=True),
+ title="Sample System Prompt",
+ border_style="green",
+ expand=False,
+ )
+ )
+
+ console.print("\n[bold]Agent initialized and ready to use![/bold]")
diff --git a/atomic_agents/agents/tool_interface_agent.py b/atomic_agents/agents/tool_interface_agent.py
index d9e9265..d4c6d12 100644
--- a/atomic_agents/agents/tool_interface_agent.py
+++ b/atomic_agents/agents/tool_interface_agent.py
@@ -10,7 +10,6 @@ from atomic_agents.lib.utils.format_tool_message import format_tool_message
class ToolInterfaceAgentConfig(BaseAgentConfig):
tool_instance: BaseTool
- return_raw_output: bool = False
class ToolInterfaceAgent(BaseAgent):
@@ -18,11 +17,10 @@ class ToolInterfaceAgent(BaseAgent):
A specialized chat agent designed to interact with a specific tool.
This agent extends the BaseAgent to include functionality for interacting with a tool instance.
- It generates system prompts, handles tool input and output, and can optionally return raw tool output.
+ It generates system prompts, handles tool input and output, and processes the tool output.
Attributes:
tool_instance: The instance of the tool this agent will interact with.
- return_raw_output (bool): Whether to return the raw output from the tool.
"""
def __init__(self, config: ToolInterfaceAgentConfig):
@@ -35,7 +33,6 @@ class ToolInterfaceAgent(BaseAgent):
super().__init__(config=config)
self.tool_instance = config.tool_instance
- self.return_raw_output = config.return_raw_output
# Create a new model with the updated schema
self.input_schema = create_model(
@@ -59,20 +56,11 @@ class ToolInterfaceAgent(BaseAgent):
"description": self.tool_instance.tool_description,
}
- if self.return_raw_output:
- self.output_schema = self.tool_instance.output_schema
-
output_instructions = [
"Make sure the tool call will maximize the utility of the tool in the context of the user input.",
+ "Process the output of the tool into a human readable format and use it to respond to the user input.",
]
- if self.return_raw_output:
- output_instructions.append(
- "Process the output of the tool into a human readable format " "and/or use it to respond to the user input."
- )
- else:
- output_instructions.append("Return the raw output of the tool.")
-
self.system_prompt_generator = SystemPromptGenerator(
background=[
f"This AI agent is designed to interact with the {self.tool_instance.tool_name} tool.",
@@ -82,21 +70,20 @@ class ToolInterfaceAgent(BaseAgent):
"Get the user input.",
"Convert the input to the proper parameters to call the tool.",
"Call the tool with the parameters.",
- "Respond to the user",
+ "Process the tool output and respond to the user",
],
output_instructions=output_instructions,
)
- def get_response(self, response_model=None):
+ def get_response(self):
"""
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, and processes the tool output. If `return_raw_output` is True, it returns
- the raw tool output; otherwise, it processes the output and returns the response.
+ runs the tool, processes the tool output, and returns the processed response.
Returns:
- BaseModel: The processed response or raw tool output.
+ BaseModel: The processed response.
"""
tool_input = super().get_response(response_model=self.tool_instance.input_schema)
formatted_tool_input = format_tool_message(tool_input)
@@ -105,12 +92,91 @@ class ToolInterfaceAgent(BaseAgent):
tool_output = self.tool_instance.run(tool_input)
self.memory.add_message("assistant", "TOOL RESPONSE: " + tool_output.model_dump_json())
- if self.return_raw_output:
- return tool_output
-
self.memory.add_message(
"assistant",
"I will now formulate a response for the user based on the tool output.",
)
response = super().get_response(response_model=self.output_schema)
return response
+
+
+if __name__ == "__main__":
+ from rich.console import Console
+ from rich.panel import Panel
+ from rich.table import Table
+ from rich.syntax import Syntax
+ from rich import box
+ import instructor
+ import openai
+ from pydantic import BaseModel, Field
+ from atomic_agents.lib.tools.calculator_tool import CalculatorTool
+
+ # Initialize the console
+ console = Console()
+
+ # Initialize the client
+ client = instructor.from_openai(openai.OpenAI())
+
+ # Initialize the tool
+ example_tool = CalculatorTool()
+
+ # Initialize the agent
+ config = ToolInterfaceAgentConfig(client=client, model="gpt-4o-mini", tool_instance=example_tool)
+ agent = ToolInterfaceAgent(config)
+
+ # Print agent information
+ console.print(Panel.fit("[bold blue]Tool Interface Agent Information[/bold blue]", border_style="blue", padding=(1, 1)))
+
+ # Print input schema
+ input_schema_table = Table(title="Input Schema", box=box.ROUNDED)
+ input_schema_table.add_column("Field", style="cyan")
+ input_schema_table.add_column("Type", style="magenta")
+ input_schema_table.add_column("Description", style="green")
+
+ for field_name, field in agent.input_schema.model_fields.items():
+ input_schema_table.add_row(field_name, str(field.annotation), field.description or "")
+
+ console.print(input_schema_table)
+
+ # Print output schema
+ output_schema_table = Table(title="Output Schema", box=box.ROUNDED)
+ output_schema_table.add_column("Field", style="cyan")
+ output_schema_table.add_column("Type", style="magenta")
+ output_schema_table.add_column("Description", style="green")
+
+ for field_name, field in agent.output_schema.model_fields.items():
+ output_schema_table.add_row(field_name, str(field.annotation), field.description or "")
+
+ console.print(output_schema_table)
+
+ # Print other agent information
+ info_table = Table(title="Agent Configuration", box=box.ROUNDED)
+ info_table.add_column("Property", style="cyan")
+ info_table.add_column("Value", style="yellow")
+
+ info_table.add_row("Model", agent.model)
+ info_table.add_row("Memory", str(type(agent.memory).__name__))
+ info_table.add_row("System Prompt Generator", str(type(agent.system_prompt_generator).__name__))
+ info_table.add_row("Tool Instance", str(type(agent.tool_instance).__name__))
+
+ console.print(info_table)
+
+ # Print a sample of the system prompt
+ system_prompt = agent.system_prompt_generator.generate_prompt()
+ console.print(
+ Panel(
+ Syntax(system_prompt, "markdown", theme="monokai", line_numbers=True),
+ title="Sample System Prompt",
+ border_style="green",
+ expand=False,
+ )
+ )
+
+ console.print("\n[bold]Tool Interface Agent initialized and ready to use![/bold]")
+
+ # Test the agent with a sample input
+ test_input = agent.input_schema(tool_input="What's the weather like today?")
+ console.print(Panel(f"Test Input: {test_input}", title="Test Run", border_style="yellow"))
+
+ response = agent.run(test_input)
+ console.print(Panel(f"Agent Response: {response}", title="Test Result", border_style="green"))
diff --git a/atomic_agents/lib/tools/base_tool.py b/atomic_agents/lib/tools/base_tool.py
index b0a23b2..35b881c 100644
--- a/atomic_agents/lib/tools/base_tool.py
+++ b/atomic_agents/lib/tools/base_tool.py
@@ -32,8 +32,8 @@ class BaseTool:
Args:
config (BaseToolConfig): Configuration for the tool, including optional title and description overrides.
"""
- self.tool_name = config.title or self.input_schema.Config.title
- self.tool_description = config.description or self.input_schema.Config.description
+ self.tool_name = config.title or self.input_schema.model_json_schema()['title']
+ self.tool_description = config.description or self.input_schema.model_json_schema()['description']
def run(self, params: Type[BaseIOSchema]) -> BaseIOSchema:
"""
diff --git a/atomic_agents/lib/tools/search/searxng_tool.py b/atomic_agents/lib/tools/search/searxng_tool.py
index 40cfa02..f9c9b78 100644
--- a/atomic_agents/lib/tools/search/searxng_tool.py
+++ b/atomic_agents/lib/tools/search/searxng_tool.py
@@ -8,38 +8,38 @@ from rich.console import Console
from atomic_agents.agents.base_agent import BaseIOSchema
from atomic_agents.lib.tools.base_tool import BaseTool, BaseToolConfig
+
################
# INPUT SCHEMA #
################
-
-
class SearxNGToolInputSchema(BaseIOSchema):
+ """
+ Schema for input to a tool for searching for information, news, references, and other content using SearxNG.
+ Returns a list of search results with a short description or content snippet and URLs for further exploration
+ """
+
queries: List[str] = Field(..., description="List of search queries.")
category: Optional[Literal["general", "news", "social_media"]] = Field(
"general", description="Category of the search queries."
)
- class Config:
- title = "SearxNGTool"
- description = (
- "Tool for searching for information, news, references, and other content on the SearxNG. "
- "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 SearxNGResultSchema(BaseIOSchema):
- url: str
- title: str
- content: Optional[str] = None
+class SearxNGSearchResultItemSchema(BaseIOSchema):
+ """This schema represents a single seaarch result item"""
+
+ url: str = Field(..., description="The URL of the search result")
+ title: str = Field(..., description="The title of the search result")
+ content: Optional[str] = Field(None, description="The content snippet of the search result")
class SearxNGToolOutputSchema(BaseIOSchema):
- results: List[SearxNGResultSchema]
- category: Optional[str] = None
+ """This schema represents the output of the SearxNG search tool."""
+
+ results: List[SearxNGSearchResultItemSchema] = Field(..., description="List of search result items")
+ category: Optional[str] = Field(None, description="The category of the search results")
##############
diff --git a/examples/basic_custom_chatbot.py b/examples/basic_custom_chatbot.py
index 9a0e26f..45999ee 100644
--- a/examples/basic_custom_chatbot.py
+++ b/examples/basic_custom_chatbot.py
@@ -13,41 +13,37 @@ import openai
# Define system prompt information including background, steps, and output instructions
system_prompt_generator = SystemPromptGenerator(
background=[
- 'This assistant is a general-purpose AI designed to be helpful and friendly.',
- ],
- steps=[
- 'Understand the user\'s input and provide a relevant response.',
- 'Respond to the user.'
+ "This assistant is a general-purpose AI designed to be helpful and friendly.",
],
+ steps=["Understand the user's input and provide a relevant response.", "Respond to the user."],
output_instructions=[
- 'Provide helpful and relevant information to assist the user.',
- 'Be friendly and respectful in all interactions.',
- 'Always answer in rhyming verse.'
- ]
+ "Provide helpful and relevant information to assist the user.",
+ "Be friendly and respectful in all interactions.",
+ "Always answer in rhyming verse.",
+ ],
)
# Initialize chat memory to store conversation history
memory = AgentMemory()
# Define initial memory with a greeting message from the assistant
initial_memory = [
- {'role': 'assistant', 'content': 'How do you do? What can I do for you? Tell me, pray, what is your need today?'}
+ {"role": "assistant", "content": "How do you do? What can I do for you? Tell me, pray, what is your need today?"}
]
# Load the initial memory into the chat memory
-memory.load(initial_memory)
+memory.load(initial_memory)
# Create a chat agent with the specified model, system prompt generator, and memory
# For all supported clients such as Anthropic & Gemini, have a look at the `instructor` library documentation.
-base_url = None # Replace with your OpenAI API base URL
-api_key = None # Replace with your OpenAI API key
+base_url = None # Replace with your OpenAI API base URL
+api_key = None # Replace with your OpenAI API key
agent = BaseAgent(
config=BaseAgentConfig(
- client=instructor.from_openai(openai.OpenAI(
- base_url=base_url or os.getenv('OPENAI_BASE_URL'),
- api_key=api_key or os.getenv('OPENAI_API_KEY')
- )),
+ client=instructor.from_openai(
+ openai.OpenAI(base_url=base_url or os.getenv("OPENAI_BASE_URL"), api_key=api_key or os.getenv("OPENAI_API_KEY"))
+ ),
system_prompt_generator=system_prompt_generator,
- model='gpt-4o-mini',
+ model="gpt-4o-mini",
memory=memory,
)
)
@@ -57,10 +53,10 @@ console = Console()
console.print(f'Agent: {initial_memory[0]["content"]}')
while True:
- user_input = input('You: ')
- if user_input.lower() in ['/exit', '/quit']:
- print('Exiting chat...')
+ user_input = input("You: ")
+ if user_input.lower() in ["/exit", "/quit"]:
+ print("Exiting chat...")
break
response = agent.run(agent.input_schema(chat_message=user_input))
- console.print(f'Agent: {response.chat_message}')
\ No newline at end of file
+ console.print(f"Agent: {response.chat_message}")
diff --git a/examples/conversing_agents.py b/examples/conversing_agents.py
index 97b5974..d9db447 100644
--- a/examples/conversing_agents.py
+++ b/examples/conversing_agents.py
@@ -10,48 +10,54 @@ from atomic_agents.lib.components.system_prompt_generator import SystemPromptGen
# Initialize the system prompts. For simplicity, we use the same system prompt for both agents.
agent1_system_prompt_generator = SystemPromptGenerator(
- background=['You are an agent that adds 1 to the number said by the previous person in the conversation.'],
- steps=['If the previous message contains a number, add 1 to it.'],
- output_instructions=['Respond with only the resulting added number and never anything else. Do not include any additional text.']
+ background=["You are an agent that adds 1 to the number said by the previous person in the conversation."],
+ steps=["If the previous message contains a number, add 1 to it."],
+ output_instructions=[
+ "Respond with only the resulting added number and never anything else. Do not include any additional text."
+ ],
)
agent2_system_prompt_generator = SystemPromptGenerator(
- background=['You are an agent that adds 1 to the number said by the previous person in the conversation.'],
- steps=['If the previous message contains a number, add 1 to it.'],
- output_instructions=['Respond with only the resulting added number and never anything else. Do not include any additional text.']
+ background=["You are an agent that adds 1 to the number said by the previous person in the conversation."],
+ steps=["If the previous message contains a number, add 1 to it."],
+ output_instructions=[
+ "Respond with only the resulting added number and never anything else. Do not include any additional text."
+ ],
)
# Initialize the agents. For fun, we use two different clients for the agents. One uses Groq and the other uses OpenAI.
# You can use the same client for both agents if you prefer. For a list of supported clients, refer to the `instructor` library documentation.
agent1 = BaseAgent(
config=BaseAgentConfig(
- client=instructor.from_groq(groq.Groq(api_key=os.getenv('GROQ_API_KEY'))),
- model=os.getenv('GROQ_CHAT_MODEL'),
- system_prompt_generator=agent1_system_prompt_generator
+ client=instructor.from_groq(groq.Groq(api_key=os.getenv("GROQ_API_KEY"))),
+ model=os.getenv("GROQ_CHAT_MODEL"),
+ system_prompt_generator=agent1_system_prompt_generator,
)
)
agent2 = BaseAgent(
config=BaseAgentConfig(
client=instructor.from_openai(openai.OpenAI()),
- model='gpt-4o-mini',
- system_prompt_generator=agent2_system_prompt_generator
+ model="gpt-4o-mini",
+ system_prompt_generator=agent2_system_prompt_generator,
)
)
+
# Function to simulate a conversation between the two agents
def simulate_conversation(num_turns=5):
console = Console()
next_input = "123"
-
+
for _ in range(num_turns):
agent1_response = agent1.run(agent1.input_schema(chat_message=next_input))
- console.print(f'[bold blue]Agent 1:[/bold blue] {agent1_response.chat_message}')
+ console.print(f"[bold blue]Agent 1:[/bold blue] {agent1_response.chat_message}")
next_input = agent1_response.chat_message
-
+
agent2_response = agent2.run(agent2.input_schema(chat_message=next_input))
- console.print(f'[bold green]Agent 2:[/bold green] {agent2_response.chat_message}')
+ console.print(f"[bold green]Agent 2:[/bold green] {agent2_response.chat_message}")
next_input = agent2_response.chat_message
+
if __name__ == "__main__":
simulate_conversation(num_turns=5)
diff --git a/examples/deep_research_multi_agent/agents/info_refiner_agent.py b/examples/deep_research_multi_agent/agents/info_refiner_agent.py
index 27b4188..00d672f 100644
--- a/examples/deep_research_multi_agent/agents/info_refiner_agent.py
+++ b/examples/deep_research_multi_agent/agents/info_refiner_agent.py
@@ -5,36 +5,39 @@ import openai
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
+
class RefineAnswerInputSchema(BaseIOSchema):
- question: str = Field(..., description='The question that was asked.')
- answer: str = Field(..., description='The initial answer to the question.')
+ question: str = Field(..., description="The question that was asked.")
+ answer: str = Field(..., description="The initial answer to the question.")
+
class RefineAnswerOutputSchema(BaseModel):
- refined_answer: str = Field(..., description='The refined answer to the question.')
+ refined_answer: str = Field(..., description="The refined answer to the question.")
+
# Create the refine answer agent
refine_answer_agent = BaseAgent(
BaseAgentConfig(
- client=instructor.from_openai(openai.OpenAI()),
- model='gpt-4o-mini',
+ client=instructor.from_openai(openai.OpenAI()),
+ model="gpt-4o-mini",
system_prompt_generator=SystemPromptGenerator(
background=[
"You are an intelligent answer refinement expert.",
- "Your task is to expand and elaborate on an existing answer to a question using additional context from vector DB chunks."
+ "Your task is to expand and elaborate on an existing answer to a question using additional context from vector DB chunks.",
],
steps=[
"You will receive a question or instruction, the initial answer, and additional context from vector DB chunks.",
"Correct any inaccuracies and factual errors in the initial answer.",
- "Expand and elaborate on the initial answer using the additional context to provide a more comprehensive and detailed response."
+ "Expand and elaborate on the initial answer using the additional context to provide a more comprehensive and detailed response.",
],
output_instructions=[
"Ensure the refined answer is clear, concise, and well-structured.",
"Ensure the refined answer is directly relevant to the question and incorporates the additional context provided.",
"Add new information and details to make the final answer more elaborate and informative.",
- "Do not make up any new information; only use the information present in the context."
- ]
+ "Do not make up any new information; only use the information present in the context.",
+ ],
),
input_schema=RefineAnswerInputSchema,
- output_schema=RefineAnswerOutputSchema
+ output_schema=RefineAnswerOutputSchema,
)
-)
\ No newline at end of file
+)
diff --git a/examples/deep_research_multi_agent/agents/query_agent.py b/examples/deep_research_multi_agent/agents/query_agent.py
index d24e352..315cdc3 100644
--- a/examples/deep_research_multi_agent/agents/query_agent.py
+++ b/examples/deep_research_multi_agent/agents/query_agent.py
@@ -4,31 +4,33 @@ from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentCo
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool
+
class QueryAgentInputSchema(BaseIOSchema):
- instruction: str = 'A detailed instruction or request to generate deep research queries for.'
- num_queries: int = 'The number of queries to generate.'
+ 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_agent = BaseAgent(
BaseAgentConfig(
- client=instructor.from_openai(openai.OpenAI()),
- model='gpt-4o-mini',
+ 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."
+ "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."
+ "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."
- ]
+ "Ensure each query is unique and as diverse as possible while remaining relevant to the instruction.",
+ ],
),
input_schema=QueryAgentInputSchema,
- output_schema=SearxNGTool.input_schema
+ output_schema=SearxNGTool.input_schema,
)
-)
\ No newline at end of file
+)
diff --git a/examples/deep_research_multi_agent/agents/question_answering_agent.py b/examples/deep_research_multi_agent/agents/question_answering_agent.py
index 06a4e17..1ac127f 100644
--- a/examples/deep_research_multi_agent/agents/question_answering_agent.py
+++ b/examples/deep_research_multi_agent/agents/question_answering_agent.py
@@ -4,32 +4,35 @@ from pydantic import BaseModel, Field
from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
+
class AnswerAgentInputSchema(BaseIOSchema):
- question: str = Field(..., description='A question that needs to be answered based on the provided context.')
+ question: str = Field(..., description="A question that needs to be answered based on the provided context.")
+
class AnswerAgentOutputSchema(BaseIOSchema):
- markdown_output: str = Field(..., description='The answer to the question in markdown format.')
+ markdown_output: str = Field(..., description="The answer to the question in markdown format.")
+
# Create the answer agent
answer_agent = BaseAgent(
BaseAgentConfig(
- client=instructor.from_openai(openai.OpenAI()),
- model='gpt-4o-mini',
+ client=instructor.from_openai(openai.OpenAI()),
+ model="gpt-4o-mini",
system_prompt_generator=SystemPromptGenerator(
background=[
"You are an intelligent answering expert.",
- "Your task is to provide accurate and detailed answers to user questions based on the given context."
+ "Your task is to provide accurate and detailed answers to user questions based on the given context.",
],
steps=[
"You will receive a question and the context information.",
- "Generate a detailed and accurate answer based on the context."
+ "Generate a detailed and accurate answer based on the context.",
],
output_instructions=[
"Ensure clarity and conciseness in each answer.",
- "Ensure the answer is directly relevant to the question and context provided."
- ]
+ "Ensure the answer is directly relevant to the question and context provided.",
+ ],
),
input_schema=AnswerAgentInputSchema,
- output_schema=AnswerAgentOutputSchema
+ output_schema=AnswerAgentOutputSchema,
)
-)
\ No newline at end of file
+)
diff --git a/examples/deep_research_multi_agent/agents/top_urls_selector_agent.py b/examples/deep_research_multi_agent/agents/top_urls_selector_agent.py
index 6f7dc1e..a9e6ca2 100644
--- a/examples/deep_research_multi_agent/agents/top_urls_selector_agent.py
+++ b/examples/deep_research_multi_agent/agents/top_urls_selector_agent.py
@@ -5,22 +5,25 @@ from pydantic import Field, HttpUrl
from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
+
class TopUrlsSelectorInputSchema(BaseIOSchema):
- user_input: str = Field(..., description='The user input or question.')
- num_urls: int = Field(..., description='The number of top URLs to select.')
+ user_input: str = Field(..., description="The user input or question.")
+ num_urls: int = Field(..., description="The number of top URLs to select.")
+
class TopUrlsSelectorOutputSchema(BaseIOSchema):
- top_urls: List[HttpUrl] = Field(..., description='The list of top URLs selected based on the user input.')
+ top_urls: List[HttpUrl] = Field(..., description="The list of top URLs selected based on the user input.")
+
# Create the top URLs selector agent
top_urls_selector_agent = BaseAgent(
BaseAgentConfig(
- client=instructor.from_openai(openai.OpenAI()),
- model='gpt-4o-mini',
+ client=instructor.from_openai(openai.OpenAI()),
+ model="gpt-4o-mini",
system_prompt_generator=SystemPromptGenerator(
background=[
"You are an intelligent URL selection expert.",
- "Your task is to select the best URLs from a list of search results that are most relevant to the user input or question."
+ "Your task is to select the best URLs from a list of search results that are most relevant to the user input or question.",
],
steps=[
"You will receive the user input or question, the list of search results, and the number of best URLs to select.",
@@ -28,10 +31,10 @@ top_urls_selector_agent = BaseAgent(
],
output_instructions=[
"Ensure each selected URL is highly relevant to the user input or question.",
- "Ensure the selected URLs are diverse yet as relevant as possible."
- ]
+ "Ensure the selected URLs are diverse yet as relevant as possible.",
+ ],
),
input_schema=TopUrlsSelectorInputSchema,
- output_schema=TopUrlsSelectorOutputSchema
+ output_schema=TopUrlsSelectorOutputSchema,
)
-)
\ No newline at end of file
+)
diff --git a/examples/deep_research_multi_agent/in_memory_faiss.py b/examples/deep_research_multi_agent/in_memory_faiss.py
index dcce3b2..7c91ca6 100644
--- a/examples/deep_research_multi_agent/in_memory_faiss.py
+++ b/examples/deep_research_multi_agent/in_memory_faiss.py
@@ -6,6 +6,7 @@ from playwright.async_api import async_playwright
from bs4 import BeautifulSoup
import markdownify
+
class InMemFaiss:
def __init__(self, openai_api_key):
openai.api_key = openai_api_key
@@ -20,21 +21,21 @@ class InMemFaiss:
await page.goto(url)
html_content = await page.content()
await browser.close()
-
+
# Clean HTML content
cleaned_html = self.clean_html(html_content)
-
+
# Convert cleaned HTML to Markdown
markdown_content = markdownify.markdownify(cleaned_html, heading_style="ATX")
return markdown_content
def clean_html(self, html_content):
- soup = BeautifulSoup(html_content, 'html.parser')
-
+ soup = BeautifulSoup(html_content, "html.parser")
+
# Example cleaning: remove script and style tags
for script_or_style in soup(["script", "style"]):
script_or_style.decompose()
-
+
# Additional cleaning can be done here
cleaned_html = str(soup)
return cleaned_html
@@ -42,7 +43,7 @@ class InMemFaiss:
def split_text(self, text, chunk_size=1000, overlap=250):
chunks = []
for i in range(0, len(text), chunk_size - overlap):
- chunk = text[i:i + chunk_size].strip()
+ chunk = text[i : i + chunk_size].strip()
chunks.append(chunk)
return chunks
@@ -52,7 +53,7 @@ class InMemFaiss:
response = openai.embeddings.create(input=text, model="text-embedding-3-small")
embedding = response.data[0].embedding
embeddings.append(embedding)
- return np.array(embeddings).astype('float32')
+ return np.array(embeddings).astype("float32")
async def ingest_urls(self, urls):
tasks = [self.process_url(url) for url in urls]
@@ -73,4 +74,4 @@ class InMemFaiss:
async def retrieve_chunks(self, query, top_k=5):
query_embedding = await self.generate_embeddings([query])
distances, indices = self.index.search(query_embedding, top_k)
- return [self.texts[idx] for idx in indices[0]]
\ No newline at end of file
+ return [self.texts[idx] for idx in indices[0]]
diff --git a/examples/deep_research_multi_agent/main.py b/examples/deep_research_multi_agent/main.py
index 5df5d89..fa8a5af 100644
--- a/examples/deep_research_multi_agent/main.py
+++ b/examples/deep_research_multi_agent/main.py
@@ -9,22 +9,23 @@ from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGTool
from rich.console import Console
import asyncio
+
async def main():
-
+
console = Console()
# Initialize the search tool
- search_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=30))
- in_mem_faiss = InMemFaiss(openai_api_key=os.getenv('OPENAI_API_KEY'))
+ search_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=30))
+ in_mem_faiss = InMemFaiss(openai_api_key=os.getenv("OPENAI_API_KEY"))
user_input = input("Enter your question (or type 'exit' to quit): ")
- answer_agent.register_context_provider('search_results', search_results_provider)
- top_urls_selector_agent.register_context_provider('search_results', search_results_provider)
- refine_answer_agent.register_context_provider('vector_db_chunks', vector_db_chunks_provider)
+ answer_agent.register_context_provider("search_results", search_results_provider)
+ top_urls_selector_agent.register_context_provider("search_results", search_results_provider)
+ refine_answer_agent.register_context_provider("vector_db_chunks", vector_db_chunks_provider)
while True:
- if user_input.lower() == 'exit':
+ if user_input.lower() == "exit":
break
console.print("[bold green]Getting queries...[/bold green]")
@@ -35,13 +36,10 @@ async def main():
console.print("[bold green]Getting search results...[/bold green]")
search_results_provider.search_results = search_tool.run(search_tool.input_schema(**queries.model_dump()))
-
+
# Select top URLs
console.print("[bold green]Selecting top URLs...[/bold green]")
- top_urls = top_urls_selector_agent.run(top_urls_selector_agent.input_schema(
- user_input=user_input,
- num_urls=5
- ))
+ top_urls = top_urls_selector_agent.run(top_urls_selector_agent.input_schema(user_input=user_input, num_urls=5))
# Call the answer agent
console.print("[bold green]Calling the answer agent...[/bold green]")
@@ -62,10 +60,9 @@ async def main():
vector_db_chunks_provider.chunks = chunks
console.print("[bold green]Refining the answer...[/bold green]")
- refined_answer = refine_answer_agent.run(refine_answer_agent.input_schema(
- question=user_input,
- answer=initial_answer.markdown_output
- ))
+ refined_answer = refine_answer_agent.run(
+ refine_answer_agent.input_schema(question=user_input, answer=initial_answer.markdown_output)
+ )
console.print("Refined Answer:")
console.print(refined_answer.refined_answer, markup=True)
@@ -75,5 +72,6 @@ async def main():
user_input = input("Enter your question (or type 'exit' to quit): ")
+
# Run the main function
-asyncio.run(main())
\ No newline at end of file
+asyncio.run(main())
diff --git a/examples/deep_research_multi_agent/providers.py b/examples/deep_research_multi_agent/providers.py
index e0a0942..0bff2b9 100644
--- a/examples/deep_research_multi_agent/providers.py
+++ b/examples/deep_research_multi_agent/providers.py
@@ -1,12 +1,14 @@
from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase
-
+
+
class SearchResultsProvider(SystemPromptContextProviderBase):
def __init__(self, title: str):
super().__init__(title=title)
self.search_results = []
-
+
def get_info(self) -> str:
- return f'SEARCH RESULTS: {self.search_results}'
+ return f"SEARCH RESULTS: {self.search_results}"
+
class VectorDBChunksProvider(SystemPromptContextProviderBase):
def __init__(self, title: str):
@@ -14,7 +16,8 @@ class VectorDBChunksProvider(SystemPromptContextProviderBase):
self.chunks = []
def get_info(self) -> str:
- return f'VECTOR DB CHUNKS: {self.chunks}'
+ return f"VECTOR DB CHUNKS: {self.chunks}"
+
-search_results_provider = SearchResultsProvider(title='Search results')
-vector_db_chunks_provider = VectorDBChunksProvider(title='Vector DB chunks')
\ No newline at end of file
+search_results_provider = SearchResultsProvider(title="Search results")
+vector_db_chunks_provider = VectorDBChunksProvider(title="Vector DB chunks")
diff --git a/examples/memory_demo.py b/examples/memory_demo.py
index 0238012..6440b22 100644
--- a/examples/memory_demo.py
+++ b/examples/memory_demo.py
@@ -7,9 +7,11 @@ from atomic_agents.lib.components.agent_memory import AgentMemory
console = Console()
+
def print_panel(title, content):
console.print(Panel(content, title=title, expand=False, border_style="cyan"))
+
# Create a AgentMemory with a maximum of 5 messages
memory = AgentMemory(max_messages=5)
@@ -32,7 +34,7 @@ content = Text()
tool_message = {
"id": "weather_1",
"type": "function",
- "function": {"name": "get_weather", "arguments": '{"location": "New York"}'}
+ "function": {"name": "get_weather", "arguments": '{"location": "New York"}'},
}
memory.add_message("assistant", "Certainly! I'll check the weather for you.", tool_message=tool_message)
content.append(f"Total messages: {memory.get_message_count()}\n\n")
@@ -58,7 +60,10 @@ memory.add_message("user", "Thanks for the weather info!")
content.append(f"Total messages: {memory.get_message_count()}\n\n")
content.append("Current history (should only have 5 most recent messages):\n")
for msg in memory.get_history():
- content.append(f"- {msg.role}: {msg.content}\n", style=f"{'green' if msg.role == 'user' else 'blue' if msg.role == 'assistant' else 'yellow'}")
+ content.append(
+ f"- {msg.role}: {msg.content}\n",
+ style=f"{'green' if msg.role == 'user' else 'blue' if msg.role == 'assistant' else 'yellow'}",
+ )
print_panel("4. Testing overflow management", content)
# Test Case 5: Testing dump and load functionality
@@ -71,7 +76,10 @@ new_memory = AgentMemory(max_messages=5)
new_memory.load(dumped_data)
content.append("Loaded memory:\n")
for msg in new_memory.get_history():
- content.append(f"- {msg.role}: {msg.content}\n", style=f"{'green' if msg.role == 'user' else 'blue' if msg.role == 'assistant' else 'yellow'}")
+ content.append(
+ f"- {msg.role}: {msg.content}\n",
+ style=f"{'green' if msg.role == 'user' else 'blue' if msg.role == 'assistant' else 'yellow'}",
+ )
content.append(f"\nTotal messages in loaded memory: {new_memory.get_message_count()}")
print_panel("5. Testing dump and load", content)
@@ -88,9 +96,7 @@ print_panel("6. Testing copy", content)
# Test Case 7: Testing loading a larger buffer than max_messages
content = Text()
-large_buffer = [
- {"role": "user", "content": f"Message {i}"} for i in range(10)
-]
+large_buffer = [{"role": "user", "content": f"Message {i}"} for i in range(10)]
large_memory = AgentMemory(max_messages=5)
large_memory.load(large_buffer)
content.append(f"Total messages after loading large buffer: {large_memory.get_message_count()}\n\n")
@@ -108,5 +114,8 @@ mixed_memory.add_message("system", {"command": "reset_conversation"})
content.append(f"Total messages in mixed memory: {mixed_memory.get_message_count()}\n\n")
content.append("Mixed memory contents:\n")
for msg in mixed_memory.get_history():
- content.append(f"- {msg.role}: {msg.content}\n", style=f"{'green' if msg.role == 'user' else 'blue' if msg.role == 'assistant' else 'red'}")
-print_panel("8. Testing adding messages with different content types", content)
\ No newline at end of file
+ content.append(
+ f"- {msg.role}: {msg.content}\n",
+ style=f"{'green' if msg.role == 'user' else 'blue' if msg.role == 'assistant' else 'red'}",
+ )
+print_panel("8. Testing adding messages with different content types", content)
diff --git a/examples/mesop_example.py b/examples/mesop_example.py
index f096d1c..03052b5 100644
--- a/examples/mesop_example.py
+++ b/examples/mesop_example.py
@@ -22,29 +22,32 @@ from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGTool
console = Console()
client = instructor.from_openai(openai.OpenAI())
+
def initialize_searxng_tool():
- base_url = os.getenv('SEARXNG_BASE_URL')
+ base_url = os.getenv("SEARXNG_BASE_URL")
config = SearxNGToolConfig(base_url=base_url, max_results=10)
return SearxNGTool(config)
+
searxng_tool = initialize_searxng_tool()
+
def initialize_agent(client, searxng_tool):
agent_config = ToolInterfaceAgentConfig(
- client=client,
- model='gpt-4o-mini',
- tool_instance=searxng_tool,
- return_raw_output=False
+ client=client, model="gpt-4o-mini", tool_instance=searxng_tool, return_raw_output=False
)
return ToolInterfaceAgent(config=agent_config)
+
agent = initialize_agent(client, searxng_tool)
+
# Mesop state class
@me.stateclass
class State:
chat_history: list[mel.ChatMessage] = field(default_factory=list)
+
# Mesop transform function
def transform(input: str, history: list[mel.ChatMessage]):
state = me.state(State)
@@ -55,13 +58,11 @@ def transform(input: str, history: list[mel.ChatMessage]):
# Mesop page
- path="/",
- title="ToolInterfaceAgent Chat"
-)
[email protected](path="/", title="ToolInterfaceAgent Chat")
def page():
mel.chat(transform, title="ToolInterfaceAgent with SearxNGTool", bot_user="Agent")
+
# Main function to run the Mesop app
if __name__ == "__main__":
me.run(page)
diff --git a/examples/minimal_chatbot.py b/examples/minimal_chatbot.py
index 004b850..bff9a8e 100644
--- a/examples/minimal_chatbot.py
+++ b/examples/minimal_chatbot.py
@@ -7,22 +7,17 @@ from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig
# Create an instance of `BaseAgent` with default settings.
# For all supported clients such as Anthropic & Gemini, have a look at the `instructor` library documentation.
-agent = BaseAgent(
- config=BaseAgentConfig(
- client=instructor.from_openai(openai.OpenAI()),
- model='gpt-4o-mini'
- )
-)
+agent = BaseAgent(config=BaseAgentConfig(client=instructor.from_openai(openai.OpenAI()), model="gpt-4o-mini"))
# Initialize a `Console` object for rich text output in the terminal.
console = Console()
# Main chat loop for testing the chat agent.
while True:
- user_input = input('You: ')
- if user_input.lower() in ['/exit', '/quit']:
- print('Exiting chat...')
+ user_input = input("You: ")
+ if user_input.lower() in ["/exit", "/quit"]:
+ print("Exiting chat...")
break
response = agent.run(agent.input_schema(chat_message=user_input))
- console.print(f'Agent: {response.chat_message}')
\ No newline at end of file
+ console.print(f"Agent: {response.chat_message}")
diff --git a/examples/minimal_multi_agent_tool_use.py b/examples/minimal_multi_agent_tool_use.py
index bfdbefa..0098c08 100644
--- a/examples/minimal_multi_agent_tool_use.py
+++ b/examples/minimal_multi_agent_tool_use.py
@@ -11,32 +11,38 @@ from atomic_agents.lib.tools.calculator_tool import CalculatorTool, CalculatorTo
console = Console()
client = instructor.from_openai(openai.OpenAI())
-searxng_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=10))
+searxng_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=10))
calc_tool = CalculatorTool(CalculatorToolConfig())
-search_agent_config = ToolInterfaceAgentConfig(client=client, model='gpt-4o-mini', tool_instance=searxng_tool, return_raw_output=False)
-calculator_agent_config = ToolInterfaceAgentConfig(client=client, model='gpt-4o-mini', tool_instance=calc_tool, return_raw_output=False)
+search_agent_config = ToolInterfaceAgentConfig(
+ client=client, model="gpt-4o-mini", tool_instance=searxng_tool, return_raw_output=False
+)
+calculator_agent_config = ToolInterfaceAgentConfig(
+ client=client, model="gpt-4o-mini", tool_instance=calc_tool, return_raw_output=False
+)
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 = create_model(
+ "UnionResponse", __base__=BaseIOSchema, response=(Union[searx_agent.input_schema, calc_agent.input_schema], ...)
+)
-orchestration_agent = BaseAgent(config=BaseAgentConfig(client=client, model='gpt-4o-mini', output_schema=UnionResponse))
+orchestration_agent = BaseAgent(config=BaseAgentConfig(client=client, model="gpt-4o-mini", output_schema=UnionResponse))
while True:
- user_input = input('You: ')
- if user_input.lower() in ['exit', 'quit']:
- print('Exiting chat...')
+ user_input = input("You: ")
+ if user_input.lower() in ["exit", "quit"]:
+ print("Exiting chat...")
break
orchestration_agent_output = orchestration_agent.run(orchestration_agent.input_schema(chat_message=user_input))
- console.print(f'Agent: {orchestration_agent_output.response}')
+ console.print(f"Agent: {orchestration_agent_output.response}")
if isinstance(orchestration_agent_output.response, searx_agent.input_schema):
- console.print(f'Using searx agent')
+ console.print(f"Using searx agent")
response = searx_agent.run(orchestration_agent_output.response)
elif isinstance(orchestration_agent_output.response, calc_agent.input_schema):
- console.print(f'Using calc agent')
+ console.print(f"Using calc agent")
response = calc_agent.run(orchestration_agent_output.response)
- console.print(f'Agent: {response}')
\ No newline at end of file
+ console.print(f"Agent: {response}")
diff --git a/examples/product_finder.py b/examples/product_finder.py
index afbc69d..59db91f 100644
--- a/examples/product_finder.py
+++ b/examples/product_finder.py
@@ -12,33 +12,36 @@ from atomic_agents.agents.base_agent import BaseAgent, BaseAgentOutputSchema, Ba
from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig, SearxNGToolInputSchema
# Configure logging
-logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
# Define system prompt information
system_prompt_generator = SystemPromptGenerator(
background=[
- 'This assistant is a product finder AI designed to help users find products based on their preferences by asking clarifying questions.',
+ "This assistant is a product finder AI designed to help users find products based on their preferences by asking clarifying questions.",
],
steps=[
- 'Greet the user and introduce yourself as a product finder assistant.',
- 'Ask the user questions to gather information about the product they are looking for.',
- 'Use the chat responses to gather all necessary information from the user.',
- 'Once sufficient information is gathered, use the SearxNGTool to search for products.',
- 'Summarize the search results and provide recommendations to the user.',
+ "Greet the user and introduce yourself as a product finder assistant.",
+ "Ask the user questions to gather information about the product they are looking for.",
+ "Use the chat responses to gather all necessary information from the user.",
+ "Once sufficient information is gathered, use the SearxNGTool to search for products.",
+ "Summarize the search results and provide recommendations to the user.",
],
output_instructions=[
- 'Always think in steps before answering using internal reasoning.',
- 'Provide helpful and relevant information to assist the user.',
- 'Be friendly and respectful in all interactions.',
- 'Ensure that the chat responses are used to ask clarifying questions and gather information, and the search tool is used to find products.'
- ]
+ "Always think in steps before answering using internal reasoning.",
+ "Provide helpful and relevant information to assist the user.",
+ "Be friendly and respectful in all interactions.",
+ "Ensure that the chat responses are used to ask clarifying questions and gather information, and the search tool is used to find products.",
+ ],
)
# Initialize chat memory
memory = AgentMemory()
initial_memory = [
- {'role': 'assistant', 'content': 'Hello! I\'m your product finder assistant. What kind of product are you looking for today?'}
+ {
+ "role": "assistant",
+ "content": "Hello! I'm your product finder assistant. What kind of product are you looking for today?",
+ }
]
memory.load(initial_memory)
@@ -48,24 +51,29 @@ console = Console()
client = instructor.from_openai(openai.OpenAI())
# Initialize the SearxNGTool
-searxng_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=5))
+searxng_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=5))
+
# Define a custom response schema
class OutputSchema(BaseIOSchema):
- 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)')
+ 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.'
+ title = "OutputSchema"
+ description = "The response schema for the chat agent."
+
# Create a config for the chat agent
agent_config = BaseAgentConfig(
client=client,
system_prompt_generator=system_prompt_generator,
- model='gpt-4o-mini',
+ model="gpt-4o-mini",
memory=memory,
- output_schema=OutputSchema
+ output_schema=OutputSchema,
)
# Create a chat agent
@@ -75,21 +83,24 @@ console.print("Product Finder Agent is ready.")
console.print(f'Agent: {initial_memory[0]["content"]}')
while True:
- user_input = input('You: ')
- if user_input.lower() in ['exit', 'quit']:
- print('Exiting chat...')
+ user_input = input("You: ")
+ if user_input.lower() in ["exit", "quit"]:
+ print("Exiting chat...")
break
response = agent.run(agent.input_schema(chat_message=user_input))
-
- logger.info(f'Chosen schema: {response.chosen_schema}')
-
+
+ logger.info(f"Chosen schema: {response.chosen_schema}")
+
if isinstance(response.chosen_schema, SearxNGToolInputSchema):
search_results = searxng_tool.run(response.chosen_schema)
-
- agent.memory.add_message('assistant', f'INTERNAL THOUGHT: I have found the following products: {search_results.results}\n\n I will now summarize the results for the user.')
+
+ agent.memory.add_message(
+ "assistant",
+ f"INTERNAL THOUGHT: I have found the following products: {search_results.results}\n\n I will now summarize the results for the user.",
+ )
output = agent.run().chosen_schema.chat_message
else:
output = response.chosen_schema.chat_message
-
- console.print(f'Agent: {output}')
\ No newline at end of file
+
+ console.print(f"Agent: {output}")
diff --git a/examples/shared_context.py b/examples/shared_context.py
index 7ffb3b1..4a9fe1f 100644
--- a/examples/shared_context.py
+++ b/examples/shared_context.py
@@ -5,6 +5,7 @@ import openai
from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase
from atomic_agents.agents.base_agent import BaseAgentConfig, BaseAgent
+
class SharedContextProvider(SystemPromptContextProviderBase):
def __init__(self, title):
super().__init__(title)
@@ -17,42 +18,47 @@ class SharedContextProvider(SystemPromptContextProviderBase):
def update_context(self, key: str, value: str):
self.shared_context[key] = value
+
# Define two simple agents with shared context
agent_one = BaseAgent(
config=BaseAgentConfig(
client=instructor.from_openai(openai.OpenAI()),
- model='gpt-4o-mini',
+ model="gpt-4o-mini",
)
)
agent_two = BaseAgent(
config=BaseAgentConfig(
client=instructor.from_openai(openai.OpenAI()),
- model='gpt-4o-mini',
+ model="gpt-4o-mini",
)
)
# Add an additional output instruction to agent two, to have some differences between the two agents
-agent_two.system_prompt_generator.system_prompt_info.output_instructions.append('Always respond in a beautiful poetic rhyming verse.')
+agent_two.system_prompt_generator.system_prompt_info.output_instructions.append(
+ "Always respond in a beautiful poetic rhyming verse."
+)
# Define a context provider that will be shared between the two agents
-shared_context_provider = SharedContextProvider('Shared Context Provider')
+shared_context_provider = SharedContextProvider("Shared Context Provider")
+
+agent_one.register_context_provider("shared_context", shared_context_provider)
+agent_two.register_context_provider("shared_context", shared_context_provider)
-agent_one.register_context_provider('shared_context', shared_context_provider)
-agent_two.register_context_provider('shared_context', shared_context_provider)
# Function to update context with a random number and query both agents
def query_agents_with_random_number():
random_number = random.randint(1, 100)
- shared_context_provider.update_context('random_number', str(random_number))
- print(f'Updated shared context with random number: {random_number}')
+ shared_context_provider.update_context("random_number", str(random_number))
+ print(f"Updated shared context with random number: {random_number}")
# Get responses from both agents
response_one = agent_one.run(agent_one.input_schema(chat_message="What is the random number?"))
response_two = agent_two.run(agent_two.input_schema(chat_message="What is the random number?"))
- print(f'Agent One: {response_one.chat_message}')
- print(f'Agent Two: {response_two.chat_message}')
+ print(f"Agent One: {response_one.chat_message}")
+ print(f"Agent Two: {response_two.chat_message}")
+
if __name__ == "__main__":
- query_agents_with_random_number()
\ No newline at end of file
+ query_agents_with_random_number()
diff --git a/examples/simple_web_search_agent.py b/examples/simple_web_search_agent.py
index 897fb5f..1970fb6 100644
--- a/examples/simple_web_search_agent.py
+++ b/examples/simple_web_search_agent.py
@@ -7,26 +7,26 @@ from rich.console import Console
from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInterfaceAgentConfig
from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig
+
def initialize_searxng_tool():
"""
Initialize the SearxNGTool with configuration.
"""
- base_url = os.getenv('SEARXNG_BASE_URL')
+ base_url = os.getenv("SEARXNG_BASE_URL")
config = SearxNGToolConfig(base_url=base_url, max_results=10)
return SearxNGTool(config)
+
def initialize_agent(client, searxng_tool):
"""
Initialize the ToolInterfaceAgent with the given client and SearxNGTool.
"""
agent_config = ToolInterfaceAgentConfig(
- client=client,
- model='gpt-4o-mini',
- tool_instance=searxng_tool,
- return_raw_output=False
+ client=client, model="gpt-4o-mini", tool_instance=searxng_tool, return_raw_output=False
)
return ToolInterfaceAgent(config=agent_config)
+
def main():
console = Console()
client = instructor.from_openai(openai.OpenAI())
@@ -36,14 +36,15 @@ def main():
console.print("ToolInterfaceAgent with SearxNGTool is ready.")
while True:
- user_input = input('You: ')
- if user_input.lower() in ['exit', 'quit']:
- print('Exiting chat...')
+ user_input = input("You: ")
+ if user_input.lower() in ["exit", "quit"]:
+ print("Exiting chat...")
break
-
+
# Fix this
response = agent.run(agent.input_schema(tool_input_SearxNGTool=user_input))
- console.print(f'Agent: {response.chat_message}')
+ console.print(f"Agent: {response.chat_message}")
+
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/examples/system_prompt_generator_demo.py b/examples/system_prompt_generator_demo.py
index 6a8502e..1ac58ac 100644
--- a/examples/system_prompt_generator_demo.py
+++ b/examples/system_prompt_generator_demo.py
@@ -4,12 +4,13 @@ from atomic_agents.lib.components.system_prompt_generator import SystemPromptCon
class CurrentDateProvider(SystemPromptContextProviderBase):
- def __init__(self, title, format: str = '%Y-%m-%d %H:%M:%S'):
- super().__init__(title)
- self.format = format
+ def __init__(self, title, format: str = "%Y-%m-%d %H:%M:%S"):
+ super().__init__(title)
+ self.format = format
+
+ def get_info(self) -> str:
+ return f'The current date, in the format "{self.format}", is {datetime.now().strftime(self.format)}'
- def get_info(self) -> str:
- return f'The current date, in the format "{self.format}", is {datetime.now().strftime(self.format)}'
class LoremIpsumProvider(SystemPromptContextProviderBase):
def get_info(self) -> str:
@@ -19,23 +20,21 @@ class LoremIpsumProvider(SystemPromptContextProviderBase):
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
)
+
system_prompt_generator = SystemPromptGenerator(
background=[
- 'This assistant is a general-purpose AI designed to be helpful and friendly.',
- ],
- steps=[
- 'Understand the user\'s input and provide a relevant response.',
- 'Respond to the user.'
+ "This assistant is a general-purpose AI designed to be helpful and friendly.",
],
+ steps=["Understand the user's input and provide a relevant response.", "Respond to the user."],
output_instructions=[
- 'Provide helpful and relevant information to assist the user.',
- 'Be friendly and respectful in all interactions.',
- 'Always answer in rhyming verse.'
+ "Provide helpful and relevant information to assist the user.",
+ "Be friendly and respectful in all interactions.",
+ "Always answer in rhyming verse.",
],
context_providers={
- 'date': CurrentDateProvider(title='Current date', format='%Y-%m-%d %H:%M:%S'),
- 'lorem': LoremIpsumProvider(title='Lorem Ipsum')
- }
+ "date": CurrentDateProvider(title="Current date", format="%Y-%m-%d %H:%M:%S"),
+ "lorem": LoremIpsumProvider(title="Lorem Ipsum"),
+ },
)
print(system_prompt_generator.generate_prompt())
diff --git a/examples/yelp_restaurant_finder.py b/examples/yelp_restaurant_finder.py
index fc83b20..afea64f 100644
--- a/examples/yelp_restaurant_finder.py
+++ b/examples/yelp_restaurant_finder.py
@@ -12,34 +12,32 @@ from atomic_agents.agents.base_agent import BaseAgent, BaseAgentOutputSchema, Ba
from atomic_agents.lib.tools.yelp_restaurant_finder_tool import YelpSearchTool, YelpSearchToolConfig, YelpSearchToolInputSchema
# Configure logging
-logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
# Define system prompt information including background, steps, and output instructions
system_prompt_generator = SystemPromptGenerator(
background=[
- 'This assistant is a restaurant finder AI designed to help users find the best restaurants based on their preferences by asking clarifying questions.',
+ "This assistant is a restaurant finder AI designed to help users find the best restaurants based on their preferences by asking clarifying questions.",
],
steps=[
- 'Greet the user and introduce yourself as a restaurant finder assistant.',
- 'Inspect the required Yelp schema and identify the necessary filters.',
- 'Ask the user questions to gather information for each filter until all required information is clear.',
- 'Use the chat responses to gather all necessary information from the user.',
- 'Once all required information is gathered, use the YelpSearchTool schema to search Yelp for restaurants.',
+ "Greet the user and introduce yourself as a restaurant finder assistant.",
+ "Inspect the required Yelp schema and identify the necessary filters.",
+ "Ask the user questions to gather information for each filter until all required information is clear.",
+ "Use the chat responses to gather all necessary information from the user.",
+ "Once all required information is gathered, use the YelpSearchTool schema to search Yelp for restaurants.",
],
output_instructions=[
- 'Provide helpful and relevant information to assist the user.',
- 'Be friendly and respectful in all interactions.',
- 'Ensure that the chat responses are used to ask clarifying questions and gather information, and the Yelp schema is used to perform the actual search.'
- ]
+ "Provide helpful and relevant information to assist the user.",
+ "Be friendly and respectful in all interactions.",
+ "Ensure that the chat responses are used to ask clarifying questions and gather information, and the Yelp schema is used to perform the actual search.",
+ ],
)
# Initialize chat memory to store conversation history
memory = AgentMemory()
# Define initial memory with a greeting message from the assistant
-initial_memory = [
- {'role': 'assistant', 'content': 'Hello, can I help you find a restaurant?'}
-]
+initial_memory = [{"role": "assistant", "content": "Hello, can I help you find a restaurant?"}]
# Load the initial memory into the chat memory
memory.load(initial_memory)
@@ -50,27 +48,31 @@ console = Console()
client = instructor.from_openai(openai.OpenAI())
# Initialize the YelpSearchTool
-yelp_tool = YelpSearchTool(YelpSearchToolConfig(api_key=os.getenv('YELP_API_KEY'), max_results=10))
+yelp_tool = YelpSearchTool(YelpSearchToolConfig(api_key=os.getenv("YELP_API_KEY"), max_results=10))
+
# Define a custom response schema that can handle both chat responses and Yelp search tool responses
class OutputSchema(BaseModel):
- chosen_schema: Union[BaseAgentOutputSchema, YelpSearchToolInputSchema] = Field(..., description='The response from the chat 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.'
+ title = "OutputSchema"
+ description = "The response schema for the chat agent."
json_schema_extra = {
- 'title': title,
- 'description': description,
+ "title": title,
+ "description": description,
}
+
# Create a config for the chat agent
agent_config = BaseAgentConfig(
client=client,
system_prompt_generator=system_prompt_generator,
- model='gpt-4o-mini',
+ model="gpt-4o-mini",
memory=memory,
- output_schema=OutputSchema
+ output_schema=OutputSchema,
)
# Create a chat agent with the specified config
@@ -80,26 +82,29 @@ console.print("BaseAgent with YelpSearchTool is ready.")
console.print(f'Agent: {initial_memory[0]["content"]}')
while True:
- user_input = input('You: ')
- if user_input.lower() in ['exit', 'quit']:
- print('Exiting chat...')
+ user_input = input("You: ")
+ if user_input.lower() in ["exit", "quit"]:
+ print("Exiting chat...")
break
response = agent.run(agent.input_schema(chat_message=user_input))
-
+
# Log the chosen schema
- logger.info(f'Chosen schema: {response.chosen_schema}')
-
+ logger.info(f"Chosen schema: {response.chosen_schema}")
+
# Check the type of the response schema
if isinstance(response.chosen_schema, YelpSearchToolInputSchema):
output = yelp_tool.run(response.chosen_schema)
-
- # In this example, we will add a simple "internal thought" to the chat memory followed by an empty agent.run() call.
+
+ # In this example, we will add a simple "internal thought" to the chat memory followed by an empty agent.run() call.
# This will make the agent continue the conversation without user input.
# In a more complex example, it might be preferable to extend the BaseAgent class and override the _get_and_handle_response method.
- agent.memory.add_message('assistant', f'INTERNAL THOUGHT: I have found the following information: {output.results}\n\n I will now summarize the results for the user.')
+ agent.memory.add_message(
+ "assistant",
+ f"INTERNAL THOUGHT: I have found the following information: {output.results}\n\n I will now summarize the results for the user.",
+ )
output = agent.run().chosen_schema.chat_message
else:
output = response.chosen_schema.chat_message
-
- console.print(f'Agent: {output}')
\ No newline at end of file
+
+ console.print(f"Agent: {output}")
diff --git a/examples/youtube_knowledge_extraction.py b/examples/youtube_knowledge_extraction.py
index 4ef2de0..e008601 100644
--- a/examples/youtube_knowledge_extraction.py
+++ b/examples/youtube_knowledge_extraction.py
@@ -8,7 +8,11 @@ from typing import List, Optional
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig
from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase, SystemPromptGenerator
-from atomic_agents.lib.tools.yt_transcript_scraper_tool import YouTubeTranscriptTool, YouTubeTranscriptToolConfig, YouTubeTranscriptToolInputSchema
+from atomic_agents.lib.tools.yt_transcript_scraper_tool import (
+ YouTubeTranscriptTool,
+ YouTubeTranscriptToolConfig,
+ YouTubeTranscriptToolInputSchema,
+)
console = Console()
@@ -18,76 +22,112 @@ client = instructor.from_openai(openai.OpenAI())
yt_scraper_tool = YouTubeTranscriptTool(config=YouTubeTranscriptToolConfig())
+
class YtTranscriptProvider(SystemPromptContextProviderBase):
def __init__(self, title):
super().__init__(title)
self.transcript = None
self.duration = None
self.metadata = None
-
+
def get_info(self) -> str:
return f'VIDEO TRANSCRIPT: "{self.transcript}"\n\nDURATION: {self.duration}\n\nMETADATA: {self.metadata}'
-
-transcript_provider = YtTranscriptProvider(title='YouTube Transcript')
+
+
+transcript_provider = YtTranscriptProvider(title="YouTube Transcript")
# Define the system prompt information
system_prompt_generator = SystemPromptGenerator(
background=[
- 'This Assistant is an expert at extracting knowledge and other insightful and interesting information from YouTube transcripts.'
+ "This Assistant is an expert at extracting knowledge and other insightful and interesting information from YouTube transcripts."
],
steps=[
- 'Analyse the YouTube transcript thoroughly to extract the most valuable insights, facts, and recommendations.',
- 'Adhere strictly to the provided schema when extracting information from the input content.',
- 'Ensure that the output matches the field descriptions, types and constraints exactly.',
+ "Analyse the YouTube transcript thoroughly to extract the most valuable insights, facts, and recommendations.",
+ "Adhere strictly to the provided schema when extracting information from the input content.",
+ "Ensure that the output matches the field descriptions, types and constraints exactly.",
],
output_instructions=[
- 'Only output Markdown-compatible strings.',
- 'Ensure you follow ALL these instructions when creating your output.'
+ "Only output Markdown-compatible strings.",
+ "Ensure you follow ALL these instructions when creating your output.",
],
- context_providers={'yt_transcript': transcript_provider}
+ context_providers={"yt_transcript": transcript_provider},
)
+
# Define the response model with detailed descriptions, constraints, and field types
class ResponseModel(BaseModel):
- summary: str = Field(..., description="A short summary of the content, including who is presenting and the content being discussed.")
- insights: List[str] = Field(..., min_items=5, max_items=5, description="exactly 5 of the best insights and ideas from the input.")
- quotes: List[str] = Field(None, min_items=5, max_items=5, description="exactly 5 of the most surprising, insightful, and/or interesting quotes from the input.")
- habits: Optional[List[str]] = Field(None, min_items=5, max_items=5, description="exactly 5 of the most practical and useful personal habits mentioned by the speakers.")
- facts: List[str] = Field(..., min_items=5, max_items=5, description="exactly 5 of the most surprising, insightful, and/or interesting valid facts about the greater world mentioned in the content.")
- recommendations: List[str] = Field(..., min_items=5, max_items=5, description="exactly 5 of the most surprising, insightful, and/or interesting recommendations from the content.")
- references: List[str] = Field(..., description="All mentions of writing, art, tools, projects, and other sources of inspiration mentioned by the speakers.")
- one_sentence_takeaway: str = Field(..., description="The most potent takeaways and recommendations condensed into a single 20-word sentence.")
+ summary: str = Field(
+ ..., description="A short summary of the content, including who is presenting and the content being discussed."
+ )
+ insights: List[str] = Field(
+ ..., min_items=5, max_items=5, description="exactly 5 of the best insights and ideas from the input."
+ )
+ quotes: List[str] = Field(
+ None,
+ min_items=5,
+ max_items=5,
+ description="exactly 5 of the most surprising, insightful, and/or interesting quotes from the input.",
+ )
+ habits: Optional[List[str]] = Field(
+ None,
+ min_items=5,
+ max_items=5,
+ description="exactly 5 of the most practical and useful personal habits mentioned by the speakers.",
+ )
+ facts: List[str] = Field(
+ ...,
+ min_items=5,
+ max_items=5,
+ description="exactly 5 of the most surprising, insightful, and/or interesting valid facts about the greater world mentioned in the content.",
+ )
+ recommendations: List[str] = Field(
+ ...,
+ min_items=5,
+ max_items=5,
+ description="exactly 5 of the most surprising, insightful, and/or interesting recommendations from the content.",
+ )
+ references: List[str] = Field(
+ ...,
+ description="All mentions of writing, art, tools, projects, and other sources of inspiration mentioned by the speakers.",
+ )
+ one_sentence_takeaway: str = Field(
+ ..., description="The most potent takeaways and recommendations condensed into a single 20-word sentence."
+ )
+
agent = BaseAgent(
- config = BaseAgentConfig(
- client=client,
- model='gpt-4o-mini',
- system_prompt_generator=system_prompt_generator,
- output_schema=ResponseModel
+ config=BaseAgentConfig(
+ client=client, model="gpt-4o-mini", system_prompt_generator=system_prompt_generator, output_schema=ResponseModel
)
)
-video_url = input('Enter the YouTube video URL: ')
+video_url = input("Enter the YouTube video URL: ")
scraped_transcript = yt_scraper_tool.run(YouTubeTranscriptToolInputSchema(video_url=video_url))
transcript_provider.transcript = scraped_transcript.transcript
transcript_provider.duration = scraped_transcript.duration
transcript_provider.metadata = scraped_transcript.metadata
-response = agent.run(agent.input_schema(chat_message='Perform your assignment on the YouTube video transcript present in your context. Do not reply with anything other than the output of the assignment.'))
+response = agent.run(
+ agent.input_schema(
+ chat_message="Perform your assignment on the YouTube video transcript present in your context. Do not reply with anything other than the output of the assignment."
+ )
+)
# Convert the ResponseModel to a dictionary and then to a Markdown string
response_dict = response.model_dump()
+
def format_markdown_section(title, items):
if isinstance(items, list):
return f"## {title}\n" + "\n".join([f"- {item}" for item in items]) + "\n"
return f"## {title}\n{items}\n"
+
markdown_string = ""
for key, value in response_dict.items():
- title = key.replace('_', ' ').title()
+ title = key.replace("_", " ").title()
markdown_string += format_markdown_section(title, value)
# Print the response in a pretty Markdown formatted way
markdown_response = Markdown(markdown_string)
-console.print(markdown_response)
\ No newline at end of file
+console.print(markdown_response)