To build a multi-agent conversation system using PydanticAI, where each agent has its own unique internal state, you can follow a structured approach that leverages the ability to:
Create distinct agent classes or instances.
Maintain persistent internal state per agent.
Facilitate message passing between them.
✅ Step-by-Step Overview
1. Define Agent Class with PydanticAI
Create a class for each type of agent using the @ai_function decorator or by subclassing BaseAgent if you’re using the PydanticAI Agent framework.
Each agent maintains its own state.
python
from pydantic_ai import AIModel, AIField, BaseAgent
class ChatAgent(BaseAgent):
name: str
memory: list[str] = [] # Internal state: logs of prior messages
def receive_message(self, message: str, sender: str):
"""Handles incoming message and updates internal state."""
self.memory.append(f"{sender}: {message}")
# Simulate generating a response based on memory
response = f"(Agent {self.name} received and remembers {len(self.memory)} messages)"
self.memory.append(f"{self.name}: {response}")
return response
2. Instantiate Multiple Agents
Each instance of ChatAgent has its own memory and name:
conversation(agent_alice, agent_bob, "Hello Bob, how are you?")
You'll get output showing message flow and each agent maintaining their own memory.
🔁 Optional: Add Real LLM Responses (ChatGPT or Claude models)
If you want the agents to actually generate human-like responses:
Integrate with OpenAI API (or use ChatOpenAI from LangChain/LLMs)
Replace the mock response in receive_message() with actual completions from the LLM
Use the memory (self.memory) to build the full prompt
🧠 Advanced: Memory Management
To make internal state more powerful:
Store structured dialogs (List[Dict[str, str]])
Use vector store for memory retrieval
Add personality traits or goals (self.personality, etc.)
Example with real PydanticAI AIModel
You can build models where internal state affects generation:
python
from pydantic_ai import AIModel
class StatefulResponder(AIModel):
memory: list[str] = AIField(description="Chat history")
def chat(self, input: str) -> str:
self.memory.append(input)
return f"Replying based on {len(self.memory)} messages remembered."
Summary
You create individual agent classes or instances where each stores internal state (like a memory list). Messages are passed between agents, and each modifies its own state independently. This setup allows for AI agent simulations, cooperative AIs, or competitive dialog systems.
Would you like a runnable example or integration with OpenAI/LLMs?
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
Great! Let's create a runnable example that demonstrates:
Two independent agents (AgentA, AgentB)
Each has:
A name
A mood (e.g., "happy", "sad", "angry")
A tool that can change their mood
A loop to let a human interact with the agents via a terminal.
We'll use PydanticAI's AIModel and BaseAgent structure, and simulate mood changes via prompt-based reasoning.
✅ Full Example: Two Conversational Agents with Mood and Tool
🧱 Requirements
Install the required libraries if not already installed:
bash
pip install pydantic-ai openai
Set your environment (e.g. export OPENAI_API_KEY=your-key or use .env file).
📄 Code: multi_agent_chat.py
python
from pydantic_ai import AIModel, AIField, ai_model
from typing import Literal
# Define possible moods
Mood = Literal["happy", "sad", "angry", "neutral"]
# Define the agent class
@ai_model
class AIAgent(AIModel):
name: str = AIField(description="The agent's name.")
mood: Mood = AIField(description="The agent's current mood.")
tool: str = AIField(description="A tool that the agent uses to change its mood.")
memory: list[str] = AIField(default_factory=list, description="Memory of recent messages.")
def talk(self, user_message: str) -> str:
"""Responds to the human, possibly using its tool to change its own mood."""
self.memory.append(f"Human: {user_message}")
system_prompt = (
f"You are an AI agent named {self.name}. You are currently in a '{self.mood}' mood. "
f"You have a tool called '{self.tool}' that you can use to change your mood, depending on your feelings. "
f"Respond thoughtfully to the human's message. If your current mood is not appropriate for the situation, you can use your tool to modify it. "
f"After responding, optionally state your new mood."
)
past_memory = "\n".join(self.memory[-5:]) # use recent history
# Use LLM to generate a response
response = self.chat(
prompt=f"{system_prompt}\n\n{self.name} (current mood: {self.mood}):",
max_tokens=200,
temperature=0.7,
)
self.memory.append(f"{self.name}: {response}")
# Optionally parse mood updates here if you'd like to extract mood from message
return response
🚀 Main Chat Loop
python
def main():
# Create two agents
alice = AIAgent(name="Alice", mood="happy", tool="positivity coil")
bob = AIAgent(name="Bob", mood="sad", tool="joke blaster")
agents = {"alice": alice, "bob": bob}
print("Welcome to the AgentChat!")
print("You can talk to 'alice' or 'bob'. Type 'exit' to quit.\n")
while True:
recipient = input("> Talk to (alice/bob): ").strip().lower()
if recipient == "exit":
break
if recipient not in agents:
print("Invalid agent name. Try 'alice' or 'bob'.")
continue
message = input(f"You to {recipient.capitalize()}: ").strip()
if message.lower() == "exit":
break
agent = agents[recipient]
reply = agent.talk(message)
print(f"{agent.name} (mood: {agent.mood}): {reply}\n")
if __name__ == "__main__":
main()
✅ Example Output
code
Welcome to the AgentChat!
You can talk to 'alice' or 'bob'. Type 'exit' to quit.
> Talk to (alice/bob): bob
You to Bob: Why are you so sad today?
Bob (mood: sad): I'm feeling a bit down, but maybe a bit of humor will help. *activates joke blaster* Here's a joke: Why don't robots get scared? Because they have nerves of steel! 😄 I feel a bit better already.
> Talk to (alice/bob): alice
You to Alice: You're always so upbeat!
Alice (mood: happy): Thank you! It's my positivity coil keeping the good vibes flowing. I'm glad you're enjoying it!
🧠 Mood Tracking (Optional Extension)
You can:
Use regex/NLP to detect if the agent says "I'm now happy" and update self.mood
Use a structured prompt to ask explicitly for {"reply": ..., "new_mood": ...} JSON output
🌐 Want Real LLM Interactions?
Make sure you’re authenticated with OpenAI (OPENAI_API_KEY), and it will automatically use OpenAI’s chat models via pydantic_ai.
🧪 Example JSON Parsing (Advanced)
You can change talk() to expect structured output like: