Use MemoryGraph to persist conversation history for Microsoft AutoGen agents.

Installation

pip install memorygraphsdk[autogen]

Quick Start

from memorygraphsdk.integrations.autogen import MemoryGraphAutoGenHistory
import autogen

# Create persistent conversation history
history = MemoryGraphAutoGenHistory(
    api_key="mg_your_key_here",
    conversation_id="user_session_123"
)

# Configure AutoGen agent
config_list = [{"model": "gpt-4", "api_key": "your_openai_key"}]

assistant = autogen.AssistantAgent(
    name="assistant",
    llm_config={"config_list": config_list}
)

user_proxy = autogen.UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER"
)

# Save messages after each turn
def save_message(sender, recipient, message):
    history.add_message(
        role=sender.name,
        content=message,
        metadata={"recipient": recipient.name}
    )

# Use AutoGen with persistent history
assistant.initiate_chat(
    user_proxy,
    message="Help me fix Redis timeouts"
)

MemoryGraphAutoGenHistory API

Constructor

MemoryGraphAutoGenHistory(
    api_key: str,
    conversation_id: str = "default",
    api_url: str = "https://graph-api.memorygraph.dev"
)
Parameter Type Description
api_key str Your MemoryGraph API key
conversation_id str Conversation identifier for isolation
api_url str API URL

Methods

# Store a message in conversation history
history.add_message(
    role="assistant",
    content="To fix Redis timeouts, use connection pooling...",
    metadata={"timestamp": "2024-01-01T00:00:00Z"}
)

# Retrieve conversation history
messages = history.get_messages(limit=50)
for msg in messages:
    print(f"{msg['role']}: {msg['content']}")

# Clear conversation history (no-op in MemoryGraph)
history.clear()

Persistent Multi-Agent Conversations

from memorygraphsdk.integrations.autogen import MemoryGraphAutoGenHistory
import autogen

# Persistent history across sessions
history = MemoryGraphAutoGenHistory(
    api_key="mg_...",
    conversation_id="project_alpha"
)

# Create agents
config_list = [{"model": "gpt-4", "api_key": "your_key"}]

assistant = autogen.AssistantAgent(
    name="assistant",
    llm_config={"config_list": config_list}
)

user_proxy = autogen.UserProxyAgent(
    name="user",
    human_input_mode="ALWAYS"
)

# Session 1
assistant.initiate_chat(user_proxy, message="Let's debug this issue")
# ... conversation happens, save messages ...

# Session 2 (later)
# Load history
messages = history.get_messages()
# Continue conversation with context

Multi-User Agent System

from memorygraphsdk.integrations.autogen import MemoryGraphAutoGenHistory

def create_user_history(user_id: str):
    """Create isolated history per user."""
    return MemoryGraphAutoGenHistory(
        api_key="mg_...",
        conversation_id=f"user_{user_id}"
    )

# Each user has separate conversation history
alice_history = create_user_history("alice")
bob_history = create_user_history("bob")

Conversation Analysis

from memorygraphsdk import MemoryGraphClient

# Analyze all conversations
client = MemoryGraphClient(api_key="mg_...")

# Get all conversation memories
conversations = client.search_memories(
    memory_types=["conversation"],
    tags=["autogen"],
    limit=1000
)

# Analyze patterns
for conv in conversations:
    print(f"Role: {conv.context.get('role')}")
    print(f"Content: {conv.content[:100]}...")

Best Practices

1. Use Conversation IDs for Isolation

# Good: Per-user or per-session isolation
history = MemoryGraphAutoGenHistory(
    api_key="mg_...",
    conversation_id=f"user_{user_id}_session_{session_id}"
)

# Avoid: Shared history
history = MemoryGraphAutoGenHistory(api_key="mg_...")

2. Add Metadata to Messages

from datetime import datetime

history.add_message(
    role="assistant",
    content="Solution: Use Redis connection pooling",
    metadata={
        "timestamp": datetime.now().isoformat(),
        "model": "gpt-4",
        "task": "debugging"
    }
)

3. Retrieve Context Before New Conversations

# Load previous context
history = MemoryGraphAutoGenHistory(
    api_key="mg_...",
    conversation_id="user_123"
)
messages = history.get_messages(limit=10)

# Provide context to new conversation
context = "\n".join([
    f"{m['role']}: {m['content']}" for m in messages[-5:]
])
assistant.initiate_chat(
    user_proxy,
    message=f"Previous context:\n{context}\n\nNow let's continue..."
)

Troubleshooting

Messages Not Persisting

Solution: Ensure you're calling add_message after each turn:

def on_message(sender, message):
    history.add_message(
        role=sender.name,
        content=message["content"]
    )

Wrong Conversation Loaded

Solution: Use consistent conversation_id:

# Correct - same ID across sessions
history = MemoryGraphAutoGenHistory(
    api_key="mg_...",
    conversation_id="session_abc"  # Same ID
)

Next Steps