Skip to content

Building AI agents, atomically

Refactor agent memory and response handling + add more quickstart examples

KennyVaneetvelde24f013c7fa27
diff --git a/atomic-agents/atomic_agents/agents/base_agent.py b/atomic-agents/atomic_agents/agents/base_agent.py
index 15d7524..60bbe6e 100644
--- a/atomic-agents/atomic_agents/agents/base_agent.py
+++ b/atomic-agents/atomic_agents/agents/base_agent.py
@@ -119,10 +119,10 @@ class BaseAgent:
if user_input:
self.memory.initialize_turn()
self.current_user_input = user_input
- self.memory.add_message("user", str(user_input))
+ self.memory.add_message("user", user_input)
response = self.get_response(response_model=self.output_schema)
- self.memory.add_message("assistant", str(response))
+ self.memory.add_message("assistant", response)
return response
diff --git a/atomic-agents/atomic_agents/lib/components/agent_memory.py b/atomic-agents/atomic_agents/lib/components/agent_memory.py
index 4e72fa3..a26c21d 100644
--- a/atomic-agents/atomic_agents/lib/components/agent_memory.py
+++ b/atomic-agents/atomic_agents/lib/components/agent_memory.py
@@ -1,8 +1,10 @@
import uuid
-
+import json
from typing import Dict, List, Optional, Union
from pydantic import BaseModel, ValidationError
+from atomic_agents.lib.base.base_io_schema import BaseIOSchema
+
class Message(BaseModel):
"""
@@ -10,14 +12,14 @@ class Message(BaseModel):
Attributes:
role (str): The role of the message sender (e.g., 'user', 'system', 'tool').
- content (Union[str, Dict]): The content of the message.
+ content (Union[str, BaseIOSchema]): The content of the message.
tool_calls (Optional[List[Dict]]): Optional list of tool call messages.
tool_call_id (Optional[str]): Optional unique identifier for the tool call.
turn_id (Optional[str]): Unique identifier for the turn this message belongs to.
"""
role: str
- content: Union[str, Dict]
+ content: Union[str, BaseIOSchema]
tool_calls: Optional[List[Dict]] = None
tool_call_id: Optional[str] = None
turn_id: Optional[str] = None
@@ -53,7 +55,7 @@ class AgentMemory:
def add_message(
self,
role: str,
- content: Union[str, Dict],
+ content: Union[str, BaseIOSchema],
tool_message: Optional[Dict] = None,
tool_id: Optional[str] = None,
) -> None:
@@ -62,7 +64,7 @@ class AgentMemory:
Args:
role (str): The role of the message sender.
- content (Union[str, Dict]): The content of the message.
+ content (Union[str, BaseIOSchema]): The content of the message.
tool_message (Optional[Dict]): Optional tool message to be included.
tool_id (Optional[str]): Optional unique identifier for the tool call.
"""
@@ -87,9 +89,23 @@ class AgentMemory:
while len(self.history) > self.max_messages:
self.history.pop(0)
+ def _serialize_content(self, content: Union[str, BaseIOSchema]) -> str:
+ """
+ Serializes the content of a message to a JSON string if it's a BaseIOSchema instance.
+
+ Args:
+ content (Union[str, BaseIOSchema]): The content to serialize.
+
+ Returns:
+ str: The serialized content.
+ """
+ if isinstance(content, BaseIOSchema):
+ return json.dumps(content.model_dump())
+ return content
+
def get_history(self) -> List[Dict]:
"""
- Retrieves the chat history, filtering out unnecessary fields.
+ Retrieves the chat history, filtering out unnecessary fields and serializing content.
Returns:
List[Dict]: The list of messages in the chat history as dictionaries.
@@ -97,7 +113,7 @@ class AgentMemory:
return [
{
"role": message.role,
- "content": message.content,
+ "content": self._serialize_content(message.content),
**({"tool_calls": message.tool_calls} if message.tool_calls else {}),
**({"tool_call_id": message.tool_call_id} if message.tool_call_id else {}),
}
@@ -106,12 +122,18 @@ class AgentMemory:
def dump(self) -> List[Dict]:
"""
- Converts the chat history to a list of dictionaries, including turn_id.
+ Converts the chat history to a list of dictionaries, including turn_id and serializing content.
Returns:
List[Dict]: The list of messages as dictionaries, including turn_id.
"""
- return [message.model_dump(exclude_none=True) for message in self.history]
+ return [
+ {
+ **message.model_dump(exclude_none=True),
+ "content": self._serialize_content(message.content),
+ }
+ for message in self.history
+ ]
def load(self, dict_list: List[Dict]) -> None:
"""
@@ -123,6 +145,12 @@ class AgentMemory:
self.history = []
for message_dict in dict_list:
try:
+ content = message_dict["content"]
+ if isinstance(content, dict):
+ # Assume it's a BaseIOSchema subclass, but we don't know which one
+ # For now, we'll keep it as a dict, but in practice, you might want to
+ # implement a way to determine the correct BaseIOSchema subclass
+ message_dict["content"] = content
message = Message.model_validate(message_dict)
self.history.append(message)
except ValidationError as e:
diff --git a/atomic-examples/quickstart/quickstart/main.py b/atomic-examples/quickstart/quickstart/basic_chatbot.py
similarity index 69%
rename from atomic-examples/quickstart/quickstart/main.py
rename to atomic-examples/quickstart/quickstart/basic_chatbot.py
index d1bd0fd..4b62647 100644
--- a/atomic-examples/quickstart/quickstart/main.py
+++ b/atomic-examples/quickstart/quickstart/basic_chatbot.py
@@ -4,9 +4,8 @@ import openai
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
from atomic_agents.lib.components.agent_memory import AgentMemory
-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig
+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema, BaseAgentOutputSchema
# API Key setup
API_KEY = ""
@@ -14,7 +13,9 @@ if not API_KEY:
API_KEY = os.getenv("OPENAI_API_KEY")
if not API_KEY:
- raise ValueError("API key is not set. Please set the API key as a static variable or in the environment variable OPENAI_API_KEY.")
+ raise ValueError(
+ "API key is not set. Please set the API key as a static variable or in the environment variable OPENAI_API_KEY."
+ )
# Initialize a Rich Console for pretty console outputs
console = Console()
@@ -23,14 +24,10 @@ console = Console()
memory = AgentMemory()
# Initialize memory with an initial 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?"}
-]
-memory.load(initial_memory)
+initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")
+memory.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library
-# Note, you can also set up a client using any other LLM provider, such as Anthropic, Cohere, etc.
-# See the Instructor library for more information: https://github.com/instructor-ai/instructor
client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))
# Agent setup with specified configuration
@@ -48,9 +45,8 @@ default_system_prompt = agent.system_prompt_generator.generate_prompt()
console.print(Panel(default_system_prompt, width=console.width, style="bold cyan"), style="bold cyan")
# Display the initial message from the assistant
-agent_message = Text(initial_memory[0]["content"], style="bold green")
console.print(Text("Agent:", style="bold green"), end=" ")
-console.print(agent_message)
+console.print(Text(initial_message.chat_message, style="bold green"))
# Start an infinite loop to handle user inputs and agent responses
while True:
@@ -61,8 +57,10 @@ while True:
console.print("Exiting chat...")
break
- # Process the user's input through the agent and get the response and display it
- response = agent.run(agent.input_schema(chat_message=user_input))
+ # Process the user's input through the agent and get the response
+ input_schema = BaseAgentInputSchema(chat_message=user_input)
+ response = agent.run(input_schema)
+
agent_message = Text(response.chat_message, style="bold green")
console.print(Text("Agent:", style="bold green"), end=" ")
console.print(agent_message)
diff --git a/atomic-examples/quickstart/quickstart/basic_custom_chatbot.py b/atomic-examples/quickstart/quickstart/basic_custom_chatbot.py
new file mode 100644
index 0000000..09c76e6
--- /dev/null
+++ b/atomic-examples/quickstart/quickstart/basic_custom_chatbot.py
@@ -0,0 +1,79 @@
+import os
+import instructor
+import openai
+from rich.console import Console
+from rich.panel import Panel
+from rich.text import Text
+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
+from atomic_agents.lib.components.agent_memory import AgentMemory
+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentOutputSchema
+
+# API Key setup
+API_KEY = ""
+if not API_KEY:
+ API_KEY = os.getenv("OPENAI_API_KEY")
+
+if not API_KEY:
+ raise ValueError(
+ "API key is not set. Please set the API key as a static variable or in the environment variable OPENAI_API_KEY."
+ )
+
+# Initialize a Rich Console for pretty console outputs
+console = Console()
+
+# Memory setup
+memory = AgentMemory()
+
+# Initialize memory with an initial message from the assistant
+initial_message = BaseAgentOutputSchema(
+ chat_message="How do you do? What can I do for you? Tell me, pray, what is your need today?"
+)
+memory.add_message("assistant", initial_message)
+
+# OpenAI client setup using the Instructor library
+# Note, you can also set up a client using any other LLM provider, such as Anthropic, Cohere, etc.
+# See the Instructor library for more information: https://github.com/instructor-ai/instructor
+client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))
+
+# Instead of the default system prompt, we can set a custom system prompt
+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."],
+ output_instructions=[
+ "Provide helpful and relevant information to assist the user.",
+ "Be friendly and respectful in all interactions.",
+ "Always answer in rhyming verse.",
+ ],
+)
+console.print(Panel(system_prompt_generator.generate_prompt(), width=console.width, style="bold cyan"), style="bold cyan")
+
+# Agent setup with specified configuration
+agent = BaseAgent(
+ config=BaseAgentConfig(
+ client=client,
+ model="gpt-4o-mini",
+ system_prompt_generator=system_prompt_generator,
+ memory=memory,
+ )
+)
+
+# Display the initial message from the assistant
+console.print(Text("Agent:", style="bold green"), end=" ")
+console.print(Text(initial_message.chat_message, style="bold green"))
+
+# Start an infinite loop to handle user inputs and agent responses
+while True:
+ # Prompt the user for input with a styled prompt
+ user_input = console.input("[bold blue]You:[/bold blue] ")
+ # Check if the user wants to exit the chat
+ if user_input.lower() in ["/exit", "/quit"]:
+ console.print("Exiting chat...")
+ break
+
+ # Process the user's input through the agent and get the response and display it
+ response = agent.run(agent.input_schema(chat_message=user_input))
+ agent_message = Text(response.chat_message, style="bold green")
+ console.print(Text("Agent:", style="bold green"), end=" ")
+ console.print(agent_message)
diff --git a/atomic-examples/quickstart/quickstart/basic_custom_chatbot_with_custom_schema.py b/atomic-examples/quickstart/quickstart/basic_custom_chatbot_with_custom_schema.py
new file mode 100644
index 0000000..4003781
--- /dev/null
+++ b/atomic-examples/quickstart/quickstart/basic_custom_chatbot_with_custom_schema.py
@@ -0,0 +1,109 @@
+import os
+import instructor
+import openai
+from rich.console import Console
+from rich.panel import Panel
+from rich.text import Text
+from typing import List
+from pydantic import Field
+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
+from atomic_agents.lib.components.agent_memory import AgentMemory
+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema, BaseIOSchema
+
+# API Key setup
+API_KEY = ""
+if not API_KEY:
+ API_KEY = os.getenv("OPENAI_API_KEY")
+
+if not API_KEY:
+ raise ValueError(
+ "API key is not set. Please set the API key as a static variable or in the environment variable OPENAI_API_KEY."
+ )
+
+# Initialize a Rich Console for pretty console outputs
+console = Console()
+
+# Memory setup
+memory = AgentMemory()
+
+
+# Custom output schema
+class CustomOutputSchema(BaseIOSchema):
+ """This schema represents the response generated by the chat agent, including follow-up questions."""
+
+ chat_message: str = Field(
+ ...,
+ description="The chat message exchanged between the user and the chat agent.",
+ )
+ quick_replies: List[str] = Field(
+ ...,
+ description="A list of suggested follow-up message suggesions the user could reply with to the assistant.",
+ )
+
+
+# Initialize memory with an initial message from the assistant
+initial_message = CustomOutputSchema(
+ chat_message="Hello! How can I assist you today?",
+ quick_replies=["What can you do?", "Tell me a joke", "Tell me about how you were made"],
+)
+memory.add_message("assistant", initial_message)
+
+# OpenAI client setup using the Instructor library
+client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))
+
+# Custom system prompt
+system_prompt_generator = SystemPromptGenerator(
+ background=[
+ "This assistant is a knowledgeable AI designed to be helpful, friendly, and poetic.",
+ ],
+ steps=[
+ "Understand the user's input and provide a relevant response.",
+ "Generate 3 follow-up questions based on the context of the conversation.",
+ "Respond to the user in rhyming verse.",
+ ],
+ output_instructions=[
+ "Provide helpful and relevant information to assist the user.",
+ "Be friendly and respectful in all interactions.",
+ "Always answer in rhyming verse.",
+ "Include 3 follow-up questions in your response.",
+ ],
+)
+console.print(Panel(system_prompt_generator.generate_prompt(), width=console.width, style="bold cyan"), style="bold cyan")
+
+# Agent setup with specified configuration and custom output schema
+agent = BaseAgent(
+ config=BaseAgentConfig(
+ client=client,
+ model="gpt-4o-mini",
+ system_prompt_generator=system_prompt_generator,
+ memory=memory,
+ output_schema=CustomOutputSchema,
+ )
+)
+
+# Display the initial message from the assistant
+console.print(Text("Agent:", style="bold green"), end=" ")
+console.print(Text(initial_message.chat_message, style="bold green"))
+
+# Start an infinite loop to handle user inputs and agent responses
+while True:
+ # Prompt the user for input with a styled prompt
+ user_input = console.input("[bold blue]You:[/bold blue] ")
+ # Check if the user wants to exit the chat
+ if user_input.lower() in ["/exit", "/quit"]:
+ console.print("Exiting chat...")
+ break
+
+ # Process the user's input through the agent and get the response
+ response = agent.run(BaseAgentInputSchema(chat_message=user_input))
+
+ # Display the agent's response
+ agent_message = Text(response.chat_message, style="bold green")
+ console.print(Text("Agent:", style="bold green"), end=" ")
+ console.print(agent_message)
+
+ # Display follow-up questions
+ console.print("\n[bold cyan]Follow-up Questions:[/bold cyan]")
+ for i, question in enumerate(response.quick_replies, 1):
+ console.print(f"[cyan]{i}. {question}[/cyan]")
+ console.print() # Add an empty line for better readability