With PydanticAI, you can create multiple agents that participate in a conversation, each maintaining its own internal state by defining separate Pydantic models for each agent's state and then instantiating different agents with those models. Here's a step-by-step approach:
1. Define Pydantic models for each agent's internal state
Each agent can have a different internal state model depending on what information it needs to keep track of.
python
from pydantic import BaseModel
class AgentAState(BaseModel):
mood: str = "neutral"
last_message: str = ""
class AgentBState(BaseModel):
knowledge_level: int = 0
last_question: str = ""
2. Create agent classes or instances that use these states
You can create agent classes that hold their own state and implement methods to update or respond based on that state.
python
class AgentA:
def __init__(self):
self.state = AgentAState()
def respond(self, message: str) -> str:
self.state.last_message = message
# Example logic based on mood
if "happy" in message:
self.state.mood = "happy"
return f"AgentA (mood: {self.state.mood}): I heard you say '{message}'."
class AgentB:
def __init__(self):
self.state = AgentBState()
def respond(self, message: str) -> str:
self.state.last_question = message
self.state.knowledge_level += 1
return f"AgentB (knowledge level: {self.state.knowledge_level}): You asked '{message}'."
3. Simulate a conversation between agents
You can then have a loop or a function that passes messages back and forth between agents, updating their internal states independently.
python
agent_a = AgentA()
agent_b = AgentB()
conversation = [
"Hello, how are you?",
"I'm feeling happy today!",
"What do you know about Pydantic?",
"Tell me more about AI."
]
for i, msg in enumerate(conversation):
if i % 2 == 0:
response = agent_a.respond(msg)
else:
response = agent_b.respond(msg)
print(response)
4. Using PydanticAI's built-in conversation or agent framework (if applicable)
If PydanticAI provides a higher-level API for agents and conversations, you would:
Define each agent's state as a Pydantic model.
Instantiate agents with their own state.
Use the conversation manager to pass messages between agents.
Example (hypothetical):
python
from pydantic_ai import Agent, Conversation
class AgentAState(BaseModel):
mood: str = "neutral"
class AgentBState(BaseModel):
knowledge_level: int = 0
agent_a = Agent(state_model=AgentAState)
agent_b = Agent(state_model=AgentBState)
conv = Conversation(agents=[agent_a, agent_b])
conv.send_message(agent_a, "Hello!")
conv.send_message(agent_b, "Hi there!")
print(agent_a.state)
print(agent_b.state)
Summary
Define distinct Pydantic models for each agent's internal state.
Create separate agent instances each holding their own state.
Pass messages between agents and update their states independently.
Optionally, use PydanticAI's conversation management tools if available.
If you want, I can help you write a full example tailored to your exact use case or the specific PydanticAI API you are using!
User
Yes, I'd like an example. There should be two agents that have a name, a mood and a tool to change their mood. There should be a way for a human to interact with both agents in a conversation.
Assistant
Certainly! Below is a complete example using Pydantic and a simple custom setup to simulate two agents, each with their own internal state (name, mood) and a tool to change their mood. A human can interact with both agents in a conversation loop.
Example: Two Agents with Name, Mood, and Mood-Changing Tool
python
from pydantic import BaseModel
from typing import Optional
# Define the internal state model for an agent
class AgentState(BaseModel):
name: str
mood: str = "neutral"
# Define the Agent class
class Agent:
def __init__(self, name: str):
self.state = AgentState(name=name)
def change_mood(self, new_mood: str):
self.state.mood = new_mood
return f"{self.state.name} is now feeling {self.state.mood}."
def respond(self, message: str) -> str:
# Simple logic: if message contains mood keywords, change mood
mood_keywords = ["happy", "sad", "angry", "excited", "bored"]
for mood in mood_keywords:
if mood in message.lower():
return self.change_mood(mood)
# Otherwise, respond with current mood and echo message
return f"{self.state.name} ({self.state.mood}): You said '{message}'."
# Create two agents
agent1 = Agent(name="Alice")
agent2 = Agent(name="Bob")
# Simple conversation loop
def conversation():
print("You can talk to Alice and Bob. Prefix your message with 'Alice:' or 'Bob:' to direct it.")
print("Type 'exit' to quit.\n")
while True:
user_input = input("You: ").strip()
if user_input.lower() == "exit":
print("Conversation ended.")
break
# Parse input to determine which agent to talk to
if user_input.lower().startswith("alice:"):
message = user_input[len("alice:"):].strip()
response = agent1.respond(message)
elif user_input.lower().startswith("bob:"):
message = user_input[len("bob:"):].strip()
response = agent2.respond(message)
else:
response = "Please specify the agent by prefixing your message with 'Alice:' or 'Bob:'."
print(response)
if __name__ == "__main__":
conversation()
How it works:
Each agent has a name and a mood stored in a Pydantic model (AgentState).
The Agent class has a method change_mood to update the mood.
The respond method checks if the message contains mood keywords and changes the mood accordingly.
The human user interacts by typing messages prefixed with the agent's name (Alice: or Bob:).
The conversation continues until the user types exit.
Sample interaction:
code
You: Alice: Hello Alice!
Alice (neutral): You said 'Hello Alice!'.
You: Bob: I am feeling happy today.
Bob is now feeling happy.
You: Alice: You seem sad.
Alice is now feeling sad.
You: exit
Conversation ended.
If you want, I can help you extend this with more complex tools, memory, or integration with PydanticAI's specific APIs!