Python SDK
The official Python SDK for Memgraph. Available on PyPI as memgraph-sdk (v0.7.2).
Installation
# Sync client (requests-based)
pip install memgraph-sdk
# With async support (adds httpx)
pip install memgraph-sdk[async]Requires Python 3.9+.
Sync Client
The MemgraphClient uses the requests library. Best for scripts, CLI tools, and synchronous applications.
from memgraph_sdk import MemgraphClient
client = MemgraphClient(
api_key="mg_your_api_key",
tenant_id="your-tenant-uuid",
base_url=None, # defaults to MEMGRAPH_API_URL env var
timeout=30.0, # request timeout in seconds
max_retries=3, # automatic retries with exponential backoff
)Core methods
ping()→ DictCheck server connectivity and return health status.
status = client.ping()
# {"status": "healthy", "database": "connected"}remember(text, user_id, category="general", domain=None, confidence=0.90)→ DictStore a memory as a belief with vector embedding. Immediately searchable. Use this when you want the fact available right away.
client.remember(
text="User prefers dark mode",
user_id="alice",
category="preference", # decision, architecture, bug_fix, preference, general
domain="settings", # optional domain categorization
confidence=0.95,
)add(text, user_id)→ DictAdd a raw event to the memory pipeline. Goes through event → episode → belief extraction (asynchronous). Use this for raw interaction logging.
client.add(
text="User asked about Kubernetes deployment",
user_id="alice",
)search(query, user_id, agent_id=None, limit=10)→ DictSearch memories relevant to a query. Returns scored results with content, relevance score, and metadata.
result = client.search(
query="What does Alice prefer?",
user_id="alice",
)
# result["results"] is a list of {content, score, metadata}
for r in result["results"]:
print(f'{r["content"]} (score: {r["score"]:.2f})')get_beliefs(user_id, limit=50, cursor=None)→ DictFetch beliefs for a user with cursor-based pagination.
beliefs = client.get_beliefs(user_id="alice", limit=20)
# beliefs["items"] contains the belief objects
# beliefs["next_cursor"] for paginationMemory Intelligence
Methods for monitoring memory quality and health.
health(user_id=None)→ DictGet memory health metrics: belief counts, confidence distribution, domain breakdown, contradiction rate, staleness rate.
health = client.health()
# {"total_beliefs": 42, "avg_confidence": 0.87, "contradiction_rate": 0.02}contradictions(user_id=None)→ DictGet contradiction report showing conflicting beliefs.
report = client.contradictions(user_id="alice")mcis(user_id=None, save=False)→ DictCompute the Memgraph Cognitive Integrity Score (0-100). A composite score of memory quality.
score = client.mcis(save=True)
# {"score": 85, "breakdown": {"accuracy": 90, "completeness": 80, ...}}evaluate(query, user_id)→ DictRun a retrieval query with detailed scoring breakdown — useful for debugging search quality.
result = client.evaluate(query="deployment preferences", user_id="alice")benchmark(scenario)→ DictRun a memory benchmark scenario against your tenant's data.
result = client.benchmark(scenario="preference_recall")Async Client
The AsyncMemgraphClient uses httpx for non-blocking HTTP calls. Ideal for FastAPI, aiohttp, or high-throughput pipelines.
from memgraph_sdk import AsyncMemgraphClient
async with AsyncMemgraphClient(
api_key="mg_your_key",
tenant_id="your-tenant-uuid",
) as client:
# Same API as sync client, but all methods are awaitable
await client.remember("User prefers Python 3.12", user_id="alice", category="preference")
context = await client.search("What language does Alice prefer?", user_id="alice")
health = await client.health()Requires pip install memgraph-sdk[async] to install the httpx dependency. The async client has the same methods as the sync client.
CLI Tool
The SDK includes a memgraph command-line tool for quick interactions.
# Initialize configuration (saves to ~/.memgraph/config.json)
memgraph init --api-key mg_your_key --tenant-id your-tenant-uuid
# Store a memory as a belief
memgraph remember "User prefers dark mode" --user alice --category preference
# Search memories
memgraph recall "What does alice prefer?" --user alice
# Check server connection
memgraph statusCognitive Sidecar
Always-on memory layer that auto-recalls before every LLM call and auto-learns after. See the Sidecar guide for full details.
from memgraph_sdk.middleware import CognitiveSidecar
sidecar = CognitiveSidecar(
client=client,
user_id="alice",
agent_id="support-bot",
token_budget=4000,
auto_learn=True,
)
# Wrap your messages — memory is injected automatically
messages = [{"role": "user", "content": "How should I deploy?"}]
enriched, learn = sidecar.wrap(messages)
# Call your LLM with enriched messages...
# Then call learn(response_text) to store learningsSidecar methods
pre_flight(messages)→ List[Dict]Inject memory context as a system message before your LLM call.
enriched = sidecar.pre_flight(messages)
print(f"Found {sidecar.memories_found} memories")post_flight(messages)→ NoneExtract and store learnings from a message exchange.
sidecar.post_flight(full_messages)wrap(messages)→ Tuple[List, Callable]Pre-flight + returns a learn callback for post-flight.
enriched, learn = sidecar.wrap(messages)
# ... call LLM ...
learn(response_text)process(messages)→ List[Dict]Combined pre-flight + post-flight in a single API call.
enriched = sidecar.process(messages)v2 Cognitive Infrastructure
Methods for entities, relationships, decisions, and graph traversal. See the v2 API docs for endpoint details.
Context Graph
get_context_graph(query, user_id=None, agent_id=None, include_decisions=True, include_graph=True)→ Dict6-stage context retrieval: semantic → entity resolution → graph expansion → temporal filter → confidence weight → assembly.
context = client.get_context_graph(
query="What does Alice prefer?",
user_id="alice",
include_decisions=True,
)Entities
create_entity(entity_type, name=None, properties=None, aliases=None)→ DictCreate a named entity in the knowledge graph.
entity = client.create_entity(
entity_type="person",
name="Alice Chen",
properties={"role": "engineer"},
aliases=["alice"],
)search_entities(query, max_results=5)→ List[Dict]Fuzzy + semantic entity search.
results = client.search_entities("Alice", max_results=5)Decisions
record_decision(goal, reasoning_steps=None, tools_used=None, beliefs_used=None, confidence=None, outcome=None, agent_id=None, user_id=None)→ DictRecord a decision with full reasoning trace.
decision = client.record_decision(
goal="Recommend deployment strategy",
agent_id="bot",
confidence=0.85,
outcome="SUCCESS",
)explain_decision(decision_id)→ DictGet full explanation: beliefs, context snapshot, entity graph at decision time.
explanation = client.explain_decision("decision-uuid")list_decisions(agent_id=None, user_id=None, outcome=None, limit=50)→ List[Dict]List decisions with optional filters.
decisions = client.list_decisions(agent_id="bot", outcome="FAILURE")Relationships & Graph
create_relationship(source_entity_id, target_entity_id, relation_type, confidence=1.0)→ DictCreate a temporal relationship between two entities.
rel = client.create_relationship(
source_entity_id="entity-1",
target_entity_id="entity-2",
relation_type="works_with",
)traverse_graph(entity_ids, max_depth=2, temporal_filter=True)→ DictTraverse entity graph from seed entities.
graph = client.traverse_graph(entity_ids=["entity-1"], max_depth=2)Contradictions
list_contradictions(status=None, limit=50)→ List[Dict]List detected contradictions between beliefs.
contradictions = client.list_contradictions(status="active")resolve_contradiction(contradiction_id, resolution_status="resolved", resolved_by="manual")→ DictResolve or dismiss a contradiction.
client.resolve_contradiction("contradiction-uuid")OpenAI Agents SDK
First-class integration with the OpenAI Agents SDK. Auto-inject memory into agent instructions and capture decisions with lifecycle hooks.
from memgraph_sdk import MemgraphClient
from memgraph_sdk.openai_agents import create_memgraph_agent, MemgraphAgentHooks
from agents import Runner
client = MemgraphClient(api_key="mg_your_key")
# All-in-one: agent with memory-enriched instructions + decision capture
agent = create_memgraph_agent(
client=client,
user_id="alice",
name="Support Agent",
instructions="You are a helpful support agent.",
agent_id="support-bot",
include_memory_tools=True, # adds search_memory + store_memory tools
token_budget=4000,
)
result = await Runner.run(agent, "How should I deploy to production?")See the Integrations page for more OpenAI Agents patterns including hooks and multi-agent orchestration.
Memory Management
forget(belief_id)→ DictDelete a specific belief by ID.
client.forget("belief-uuid")forget_all(user_id, domain=None, soft=False)→ DictBulk delete beliefs for a user. Use soft=True for soft delete.
client.forget_all(user_id="alice", domain="settings")belief_history(user_id, key, as_of=None, include_inactive=True)→ List[Dict]Version history for a specific belief key.
history = client.belief_history(user_id="alice", key="preferred_language")belief_timeline(user_id, domain=None, since=None, limit=50)→ DictChronological timeline of all belief changes.
timeline = client.belief_timeline(user_id="alice", since="2025-01-01")MCP Server
Give Claude Code, Cursor, and other MCP clients persistent memory. See the MCP guide for full setup.
# One-command setup
memgraph setup --key mg_your_api_keyError Handling
The SDK uses a typed exception hierarchy for clean error handling:
from memgraph_sdk import (
MemgraphError, # Base exception
MemgraphConnectionError, # Cannot reach server
MemgraphAuthError, # 401/403 - bad API key or token
MemgraphValidationError, # 400-499 - bad request data
MemgraphRateLimitError, # 429 - rate limit exceeded
MemgraphAPIError, # 500+ - server error
)
try:
client.remember("test", user_id="alice")
except MemgraphAuthError:
print("Check your API key")
except MemgraphRateLimitError as e:
print(f"Rate limited, retry after {e.retry_after}s")
except MemgraphConnectionError:
print("Cannot reach server")
except MemgraphError as e:
print(f"Memgraph error: {e}")Automatic retries: The SDK retries on rate limits (429), server errors (5xx), and connection errors with exponential backoff. Auth errors (401/403) and validation errors (4xx) are not retried.
Environment Variables
| Variable | Default | Description |
|---|---|---|
| MEMGRAPH_API_URL | https://api.memgraph.ai/v1 | Base URL for the Memgraph API |
| MEMGRAPH_API_KEY | - | API key (used by MCP server) |
| MEMGRAPH_TENANT_ID | - | Tenant UUID (used by MCP server) |
