Memory that helps AI agents learn from their mistakes. Store beliefs, search with semantic similarity, track decision traces.
pip install memgraph-sdk==0.8.5 Copy PIP instructions
Memory for AI agents that learns from outcomes.
Documentation · Quickstart · API reference · Changelog
The Memgraph AI Python SDK gives your agents long-term memory: store what users tell them, retrieve it by meaning, keep it current as facts change, and record decisions so an agent doesn't repeat a mistake that already failed.
pip install "memgraph-sdk[async]" # AsyncMemgraphClient (httpx) pip install "memgraph-sdk[mcp]" # MCP server for Claude, Cursor, VS Code (Python 3.10+) pip install "memgraph-sdk[all]" Requires Python 3.8+.
import os from memgraph_sdk import MemgraphClient mg = MemgraphClient(api_key=os.environ["MEMGRAPH_API_KEY"]) mg.remember("Prefers dark mode and uses PyTorch", user_id="alice") results = mg.search("What does Alice prefer?", user_id="alice") print(results["results"][0]["content"]) # Prefers dark mode and uses PyTorch Get an API key (it starts with mg_) from Settings → API Keys at memgraph.ai. Keep it in the MEMGRAPH_API_KEY environment variable rather than in source code.
mg.remember( "Moved to Pune in September", user_id="alice", category="general", # general | preference | decision | architecture | bug_fix confidence=0.9, ) mg.add("User: I just started at Razorpay as a backend engineer.", user_id="alice") When a new memory updates an existing one, the old one is archived instead of competing with it: after "Moved to Pune", a search for where Alice lives returns Pune. The previous value stays available through belief_history() and only appears in results marked [PREVIOUSLY]. Storing the same fact twice keeps one copy.
results = mg.search("Where does Alice live?", user_id="alice", limit=5) { "results": [ { "id": "6f1c2b7e-…", "content": "Moved to Pune in September", "score": 0.81, "type": "belief", "metadata": {"key": "…", "value": "Moved to Pune in September", "domain": "general"}, } ], "total": 1, } Results are ranked by semantic similarity, recency, confidence, how often a memory is used, and keyword overlap. Pass agent_id to scope retrieval to one agent.
mg.get_beliefs(user_id="alice", limit=50) # current memories mg.belief_history(user_id="alice", key=" ") # versions of one memory mg.belief_timeline(user_id="alice", domain="work") # chronological changes Learning from outcomes Record what your agent decided and how it turned out. When a similar task comes in later, the earlier attempt, and why it failed, is part of the context.
# The agent acted, and you later learn it went wrong decision = mg.record_decision( goal="Refund order #4411 bought 45 days ago", user_id="alice", beliefs_used=[r["id"] for r in mg.search("refund policy", user_id="alice")["results"]], ) mg.record_outcome(decision["id"], "FAILURE", feedback="Refunds are only allowed within 30 days") # A similar request arrives ctx = mg.sidecar_pre_flight("Please refund my order #5520 from 50 days ago", user_id="alice") print(ctx["memory_context"]) LESSONS FROM PAST ATTEMPTS AT SIMILAR TASKS: - "Refund order #4411 bought 45 days ago" → FAILED: Refunds are only allowed within 30 days Do not repeat an approach that FAILED; adjust it using the reason given. Outcomes adjust confidence. FAILURE lowers the confidence of the memories listed in beliefs_used (pass memory IDs); SUCCESS raises it slightly. Past decisions are matched by goal similarity and scoped to the same user, plus agent-level decisions recorded without a user_id. get_context_graph(query, user_id=…)["decisions"] returns the same matches. Full record_decision reference decision = mg.record_decision( goal="Choose a database for the analytics service", reasoning_steps=[ {"step": 1, "description": "Compared PostgreSQL, MongoDB and ClickHouse"}, {"step": 2, "description": "Cost analysis: $50 vs $200 vs $150 per month"}, ], tools_used=[{"tool_name": "cost_calculator", "tool_input": "3 options", "tool_output": "$50/mo"}], beliefs_used=[" ", " "], confidence=0.92, outcome="SUCCESS", # SUCCESS | FAILURE | PARTIAL | UNKNOWN | REVERTED outcome_assessment="3x faster than MongoDB for our workload", agent_id="planner", user_id="alice", ) mg.get_decision(decision["id"]) mg.explain_decision(decision["id"]) # reasoning, memories used, context snapshot mg.list_decisions(agent_id="planner", outcome="FAILURE", limit=20) mg.delete_decision(decision["id"]) reasoning_steps field Type Required step int yes description str yes tool, input, output any no confidence float no Always-on memory (sidecar) Call sidecar_pre_flight before each LLM call and sidecar_post_flight after it. Memory is then present on every turn without the model having to decide to look it up.
ctx = mg.sidecar_pre_flight(message=user_message, user_id="alice", token_budget=4000) messages = ctx["system_messages"] + [{"role": "user", "content": user_message}] reply = llm(messages) mg.sidecar_post_flight( messages=[{"role": "user", "content": user_message}, {"role": "assistant", "content": reply}], user_id="alice", ) # returns immediately; learning runs in the background (wait=True to block) sidecar_pre_flight returns:
sidecar_process(messages, user_id) does both steps in one call.
person = mg.create_entity(entity_type="person", name="John Smith", properties={"role": "tech lead"}) org = mg.create_entity(entity_type="organization", name="Acme Corp") mg.create_relationship(person["id"], org["id"], relation_type="works_at", valid_from="2025-01-01") mg.search_entities("tech lead") # matches names, aliases and properties mg.traverse_graph(entity_ids=[person["id"]], max_depth=2) mg.delete_entity(person["id"]) # also removes its relationships Deleting user data When a user asks to be forgotten:
mg.forget_all(user_id="alice") # all memories for d in mg.list_decisions(user_id="alice", limit=200): mg.delete_decision(d["id"]) # decision records Use mg.forget(memory_id) to delete a single memory, forget_all(user_id, domain="work") to limit the scope, or soft=True to deactivate instead of delete.
from memgraph_sdk import AsyncMemgraphClient async with AsyncMemgraphClient(api_key=os.environ["MEMGRAPH_API_KEY"]) as mg: await mg.remember("Prefers dark mode", user_id="alice") results = await mg.search("preferences", user_id="alice") The async client supports add, remember, search, get_beliefs, forget, forget_all, sidecar_pre_flight, sidecar_post_flight, get_context_graph, record_decision, record_outcome, delete_decision and the memory-health methods. Install it with pip install "memgraph-sdk[async]".
All exceptions inherit from memgraph_sdk.exceptions.MemgraphError:
from memgraph_sdk.exceptions import MemgraphAPIError, MemgraphRateLimitError try: mg.search("query", user_id="alice") except MemgraphRateLimitError as e: print(f"Retry in {e.retry_after}s") except MemgraphAPIError as e: print(e.status_code, e) Retries. Connection errors, timeouts, 429 and 500/502/503/504 responses are retried with backoff, up to max_retries attempts (default 3). Timeouts. 30 seconds per request by default; set timeout= on the client. Rate limits. 120 requests per minute per API key. Contact hello@memgraph.ai for higher limits. No silent failures. search() raises on errors, so an outage never looks like "no memories". The client is safe to share across threads.
MemgraphClient( api_key="mg_…", base_url="https://api.memgraph.ai/v1", # or your own deployment timeout=30.0, max_retries=3, ) Environment variable Purpose MEMGRAPH_API_KEY API key for the CLI and MCP server. Pass it to the client explicitly. MEMGRAPH_API_URL Base URL when base_url is not given. Default: https://api.memgraph.ai/v1 The SDK validates input before sending a request: API keys must start with mg_ and user_id must be a non-empty string (otherwise MemgraphValidationError). mg.ping() checks connectivity and that the key is valid.
Give Claude Desktop, Cursor or VS Code persistent memory:
pip install "memgraph-sdk[mcp]" memgraph setup --key mg_your_api_key # detects your IDE and writes its MCP config Or configure it manually:
{ "mcpServers": { "memgraph": { "command": "python3", "args": ["-m", "memgraph_sdk.mcp"], "env": { "MEMGRAPH_API_KEY": "mg_your_api_key", "MEMGRAPH_AGENT_USER_ID": "your-name" } } } } Tool What it does memgraph_search Semantic search over stored memories memgraph_remember Store a memory memgraph_forget Delete a memory by the id from a search result memgraph_think Recall for the current topic and learn from the conversation memgraph_profile Consolidated profile MEMGRAPH_AGENT_USER_ID sets whose memory the IDE reads and writes (default ai_agent). Teammates who share an API key should each set their own value.
memgraph setup --key mg_your_api_key memgraph remember "We chose PostgreSQL for analytics" memgraph recall "database choice" memgraph status The CLI reads MEMGRAPH_API_KEY and MEMGRAPH_API_URL from the environment; they override the values memgraph setup saves in .memgraph.env.
This package follows semantic versioning; changes are listed in the changelog. Upgrade with pip install --upgrade memgraph-sdk. Avoid --force-reinstall, which can break other packages in the same environment.
Issues and pull requests are welcome; see CONTRIBUTING.md.
Report vulnerabilities privately to security@memgraph.ai, not in a public issue. See SECURITY.md.
agents ai beliefs cognitive context decision-traces langchain llm mcp memgraph memory openai rag
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 7, 2026.




