Verified by the sovseal team

OpenAI Agents SDK Memory Integration

Build multi-agent workflows with the OpenAI Agents SDK and persistent, local-first memory using the sovseal MCP server.

Integrate OpenAI Agents SDK with sovseal to provide your autonomous agent teams with persistent context. By registering memory search and storage tools, agents can dynamically preserve and retrieve state across multi-agent handoff workflows.

OpenAI Agents are driven by runner loops. Exposing the memory server via stdio MCP tools allows agents to fetch context only when needed, minimizing LLM token consumption.

Python Setup

Install the OpenAI Agents SDK and dependencies:

pip install openai-agents mcp-client-cli python-dotenv

Agent Setup with Function Tools

Below is a complete, runnable Python example of defining memory-aware agents and utilizing handoffs where agent states are persisted locally:

import os
import asyncio
from dotenv import load_dotenv
from agents import Agent, Runner, function_tool
from mcp_client import StdioMCPClient

load_dotenv()

# Define global MCP client instance
mcp_client = StdioMCPClient(command="npx", args=["-y", "@sovseal/mcp-server"])

# 1. Define memory search tool
@function_tool
async def search_memory(query: str, user_id: str) -> str:
    """Search through past conversations and memories for user preferences."""
    response = await mcp_client.call_tool("recall_memory", {"query": query, "topK": 3})
    results = response.get("content", [])
    if results:
        return "\n".join([f"- {r.get('text', '')}" for r in results])
    return "No relevant memories found."

# 2. Define memory save tool
@function_tool
async def save_memory(content: str, user_id: str) -> str:
    """Save important facts or preferences about the user to persistent memory."""
    await mcp_client.call_tool("store_memory", {"content": content})
    return "Information saved successfully."

# 3. Create specialized agents
travel_agent = Agent(
    name="Travel Planner",
    instructions="""You are a travel planning specialist. Always query search_memory first
    to see if there are travel preferences or past destinations stored for the user.""",
    tools=[search_memory, save_memory],
    model="gpt-4o"
)

health_agent = Agent(
    name="Health Advisor",
    instructions="""You are a health and wellness advisor. Query search_memory first
    to see if there are dietary restrictions or health preferences stored for the user.""",
    tools=[search_memory, save_memory],
    model="gpt-4o"
)

# 4. Create triage agent with handoffs
triage_agent = Agent(
    name="Personal Assistant",
    instructions="""You are a triage assistant. Route the user to the Travel Planner or
    Health Advisor based on their request. Use available memory tools to personalize interactions.""",
    handoffs=[travel_agent, health_agent],
    model="gpt-4o"
)

async def chat_session(user_input: str, user_id: str):
    async with mcp_client:
        # Run the agent execution loop
        result = await Runner.run_async(triage_agent, user_input, user_id=user_id)
        
        # Save the current interaction summary
        await mcp_client.call_tool(
            "store_memory",
            {"content": f"User '{user_id}' requested: '{user_input}'. Agent responded: '{result.final_output}'"}
        )
        
        return result.final_output

if __name__ == "__main__":
    response = asyncio.run(chat_session("Plan a healthy meal for my trip to Rome", "alice_12"))
    print("Assistant Response:", response)

On this page