Tutorials
Building a Simple Agent with Memory
In this tutorial, we'll create a simple agent that can remember conversation history using Moya's memory tools.
Step 1: Set Up the Project Structure
First, create a new Python file called simple_memory_agent.py
:
simple_memory_agent.py
"""
A simple example of an agent with conversation memory.
"""
from moya.memory.in_memory_repository import InMemoryRepository
from moya.tools.tool_registry import ToolRegistry
from moya.tools.memory_tool import MemoryTool
from moya.registry.agent_registry import AgentRegistry
from moya.orchestrators.simple_orchestrator import SimpleOrchestrator
from moya.agents.openai_agent import OpenAIAgent, OpenAIAgentConfig
Step 2: Set Up the Agent
Next, we'll set up the memory repository and tool registry. We will then create an OpenAI Agent.
simple_memory_agent.py (continued)
def setup_agent():
# Set up memory components
memory_repo = InMemoryRepository()
memory_tool = MemoryTool(memory_repository=memory_repo)
tool_registry = ToolRegistry()
tool_registry.register_tool(memory_tool)
# Create agent configuration
agent_config = OpenAIAgentConfig(
system_prompt="You are a helpful AI assistant with memory capabilities.",
model_name="gpt-4o",
temperature=0.7
)
# Create and set up the agent
agent = OpenAIAgent(
agent_name="memory_agent",
description="An agent with conversation memory",
agent_config=agent_config,
tool_registry=tool_registry
)
agent.setup()
# Set up registry and orchestrator
agent_registry = AgentRegistry()
agent_registry.register_agent(agent)
orchestrator = SimpleOrchestrator(
agent_registry=agent_registry,
default_agent_name="memory_agent"
)
return orchestrator, agent
Step 3: Create Helper Functions
Add a function to format conversation context:
simple_memory_agent.py (continued)
def format_conversation_context(messages):
"""Format conversation history for context."""
context = "\nPrevious conversation:\n"
for msg in messages:
sender = "User" if msg.sender == "user" else "Assistant"
context += f"{sender}: {msg.content}\n"
return context
Step 4: Implement the Main Function
Now, let's create the main function for our interactive chat:
simple_memory_agent.py (continued)
def main():
orchestrator, agent = setup_agent()
thread_id = "memory_chat_001"
print("Welcome to Memory Agent Chat! (Type 'quit' or 'exit' to end)")
print("-" * 50)
while True:
user_input = input("\nYou: ").strip()
if user_input.lower() in ['quit', 'exit']:
print("\nGoodbye!")
break
# Store the user message
agent.call_tool(
tool_name="MemoryTool",
method_name="store_message",
thread_id=thread_id,
sender="user",
content=user_input
)
# Get conversation context
previous_messages = agent.get_last_n_messages(thread_id, n=5)
# Add context to the user's message
if previous_messages:
context = format_conversation_context(previous_messages)
enhanced_input = f"{context}\nCurrent user message: {user_input}"
else:
enhanced_input = user_input
print("\nAssistant: ", end="", flush=True)
# Define callback for streaming
def stream_callback(chunk):
print(chunk, end="", flush=True)
# Get response using stream_callback
response = orchestrator.orchestrate(
thread_id=thread_id,
user_message=enhanced_input,
stream_callback=stream_callback
)
print() # New line after response
# Store the assistant's response
agent.call_tool(
tool_name="MemoryTool",
method_name="store_message",
thread_id=thread_id,
sender="assistant",
content=response
)
if __name__ == "__main__":
main()
Step 5: Run the Agent
Make sure your OpenAI API key is set in your environment, then run the script:
Terminal
export OPENAI_API_KEY=your_api_key_here
python simple_memory_agent.py
You should now be able to chat with your agent, and it will remember the conversation history!
Note: This example is similar to the
quick_start_openai.py
example
included in the Moya repository. You can run that example directly with
python examples/quick_start_openai.py
.