Build Your First Memory-Enabled Agent
Learn how to build an AI agent with persistent memory using MEMANTO’s REST API.What You’ll Build
A simple customer support agent that:- Remembers customer preferences
- Recalls relevant context
- Uses memories to provide personalized responses
Prerequisites
- MEMANTO server running (
memanto serve) - Python 3.8+
httpxlibrary:pip install httpx- Moorcheh API key
Architecture
Your Agent Code
↓
REST API
↓
MEMANTO Server
↓
Moorcheh.ai (Semantic Database)
Step 1: Start MEMANTO Server
In a terminal:memanto serve
INFO: Application startup complete
Step 2: Create the Agent
Createcustomer_agent.py:
import httpx
import os
from typing import Optional
class CustomerSupportAgent:
def __init__(self, agent_id: str = "customer-support"):
self.memanto_url = "http://localhost:8000"
self.agent_id = agent_id
self.api_key = os.getenv("MOORCHEH_API_KEY")
if not self.api_key:
raise ValueError("MOORCHEH_API_KEY environment variable not set")
self.session_token: Optional[str] = None
self.client = httpx.Client()
def activate_session(self) -> str:
"""Start a new agent session."""
response = self.client.post(
f"{self.memanto_url}/api/v2/agents/{self.agent_id}/activate",
headers={"Authorization": f"Bearer {self.api_key}"}
)
response.raise_for_status()
data = response.json()
self.session_token = data["session_token"]
print(f"✓ Session activated for '{self.agent_id}'")
print(f" Session expires: {data['expires_at']}")
return self.session_token
def remember(self, content: str, memory_type: str = "fact") -> str:
"""Store a memory about the customer."""
if not self.session_token:
raise ValueError("Session not activated. Call activate_session() first.")
response = self.client.post(
f"{self.memanto_url}/api/v2/agents/{self.agent_id}/remember",
params={
"memory_type": memory_type,
"title": f"{memory_type.title()}: {content[:50]}",
"content": content,
"confidence": 1.0
},
headers={
"Authorization": f"Bearer {self.api_key}",
"X-Session-Token": self.session_token
}
)
response.raise_for_status()
data = response.json()
print(f"✓ Memory stored: {data['memory_id']}")
return data['memory_id']
def recall(self, query: str, limit: int = 5) -> list[dict]:
"""Retrieve relevant memories about the customer."""
if not self.session_token:
raise ValueError("Session not activated. Call activate_session() first.")
response = self.client.get(
f"{self.memanto_url}/api/v2/agents/{self.agent_id}/recall",
params={"query": query, "limit": limit},
headers={
"Authorization": f"Bearer {self.api_key}",
"X-Session-Token": self.session_token
}
)
response.raise_for_status()
data = response.json()
return data.get("memories", [])
def answer(self, question: str) -> str:
"""Generate an answer grounded in agent memories."""
if not self.session_token:
raise ValueError("Session not activated. Call activate_session() first.")
response = self.client.post(
f"{self.memanto_url}/api/v2/agents/{self.agent_id}/answer",
params={"question": question},
headers={
"Authorization": f"Bearer {self.api_key}",
"X-Session-Token": self.session_token
}
)
response.raise_for_status()
data = response.json()
return data.get("answer", "")
def close(self):
"""Clean up resources."""
self.client.close()
Step 3: Use Your Agent
Createmain.py:
import os
from customer_agent import CustomerSupportAgent
def main():
# Initialize agent
agent = CustomerSupportAgent(agent_id="my-support-bot")
try:
# Activate session
agent.activate_session()
# Remember customer preferences
print("\n📝 Storing customer memories...")
agent.remember("Customer name is Alice Johnson", "fact")
agent.remember("Alice works in the finance industry", "fact")
agent.remember("Alice prefers email communication", "preference")
agent.remember("Alice's timezone is PST (UTC-8)", "fact")
# Recall memories
print("\n🔍 Recalling memories...")
memories = agent.recall("What do I know about Alice?")
print(f"Found {len(memories)} memories:")
for mem in memories:
print(f" - {mem['content']} ({mem['type']})")
# Get AI-powered answer
print("\n🤖 Generating AI answer...")
answer = agent.answer("How should I communicate with Alice and what time zone is she in?")
print(f"Answer: {answer}")
# Simulate another conversation
print("\n\n--- Later Conversation ---\n")
# Agent automatically recalls context
memories = agent.recall("Tell me about this customer")
print(f"✓ Recalled {len(memories)} memories from first conversation")
# Use recalled context in response
if memories:
context = memories[0]['content']
print(f"Using context: {context}")
finally:
agent.close()
if __name__ == "__main__":
main()
Step 4: Run Your Agent
export MOORCHEH_API_KEY=mk_your_api_key
python main.py
✓ Session activated for 'my-support-bot'
Session expires: 2025-03-30 20:30:00Z
📝 Storing customer memories...
✓ Memory stored: mem_abc123
✓ Memory stored: mem_def456
✓ Memory stored: mem_ghi789
✓ Memory stored: mem_jkl012
🔍 Recalling memories...
Found 4 memories:
- Alice works in the finance industry (fact)
- Customer name is Alice Johnson (fact)
- Alice prefers email communication (preference)
- Alice's timezone is PST (UTC-8) (fact)
🤖 Generating AI answer...
Answer: Alice works in finance and is in the PST timezone.
She prefers email communication, so I should reach out
to her via email during business hours in PST.
--- Later Conversation ---
✓ Recalled 4 memories from first conversation
Using context: Alice works in the finance industry
Step 5: Use Memory Types Effectively
Different memory types help organize information:# Facts - objective information
agent.remember("Customer ID is CUST-12345", "fact")
# Preferences - user likes/dislikes
agent.remember("Prefers concise responses", "preference")
# Decisions - choices made
agent.remember("Chose Plan B (Enterprise)", "decision")
# Commitments - promises made
agent.remember("Will provide report by Friday", "commitment")
# Events - what happened
agent.remember("Attended quarterly business review", "event")
# Goals - objectives
agent.remember("Target: Reduce support tickets by 20%", "goal")
# Errors - mistakes to avoid
agent.remember("Previous order had billing issue", "error")
Step 6: Extend Your Agent
Batch Store Memories
Store multiple memories at once:def batch_remember(self, memories: list[dict]) -> list[str]:
"""Store multiple memories efficiently."""
if not self.session_token:
raise ValueError("Session not activated.")
response = self.client.post(
f"{self.memanto_url}/api/v2/agents/{self.agent_id}/batch-remember",
json={"memories": memories},
headers={
"Authorization": f"Bearer {self.api_key}",
"X-Session-Token": self.session_token
}
)
response.raise_for_status()
return response.json()["memory_ids"]
# Usage
agent.batch_remember([
{"content": "Alice Johnson", "type": "fact"},
{"content": "Finance industry", "type": "fact"},
{"content": "Email preferred", "type": "preference"}
])
Temporal Queries
Recall memories from specific time periods:def recall_as_of(self, query: str, timestamp: str) -> list[dict]:
"""Get memories as they were at a specific time."""
response = self.client.get(
f"{self.memanto_url}/api/v2/agents/{self.agent_id}/recall/as-of",
params={"query": query, "as_of": timestamp},
headers={
"Authorization": f"Bearer {self.api_key}",
"X-Session-Token": self.session_token
}
)
response.raise_for_status()
return response.json()["memories"]
# Recall state as of yesterday
memories = agent.recall_as_of(
query="customer preferences",
timestamp="2025-03-29T12:00:00Z"
)
Extend Session
Sessions expire after 6 hours. Extend when needed:def extend_session(self, hours: int = 6) -> dict:
"""Extend current session."""
response = self.client.post(
f"{self.memanto_url}/api/v2/session/extend",
params={"extend_hours": hours},
headers={
"Authorization": f"Bearer {self.api_key}",
"X-Session-Token": self.session_token
}
)
response.raise_for_status()
return response.json()
Complete Example
For a production-ready example, see the API Overview with all endpoints documented.Next Steps
- Full REST API Reference: API Documentation
- Memory Types: Memory Types Reference
- Advanced Patterns: Agent Patterns Guide
- CLI Alternative: CLI Commands
- Integrations: Connect to IDE Plugins
Congratulations! You’ve built your first memory-enabled agent. Now explore advanced features!