diff --git a/pages/_meta.ts b/pages/_meta.ts index 0f343f87b..d0b3cc9e8 100644 --- a/pages/_meta.ts +++ b/pages/_meta.ts @@ -3,6 +3,7 @@ export default { "getting-started": "Getting started", "client-libraries": "Client libraries", "ai-ecosystem": "AI ecosystem", + "use-cases": "Use cases", "fundamentals": "Fundamentals", "data-modeling": "Data modeling", "data-migration": "Data migration", diff --git a/pages/use-cases.mdx b/pages/use-cases.mdx new file mode 100644 index 000000000..9a3535f3d --- /dev/null +++ b/pages/use-cases.mdx @@ -0,0 +1,17 @@ +--- +title: Use cases +description: End-to-end Memgraph use cases — each one a walkthrough plus a runnable script for macOS, Linux and Windows. +--- + +# Use cases + +Each use case is a walkthrough plus a runnable script — `.sh` for +macOS/Linux and `.ps1` for Windows PowerShell. The scripts live in the +[memgraph/memgraph-platform](https://github.com/memgraph/memgraph-platform/tree/main/code-examples) +repository. + +| Use case | Linux | macOS | Windows | +| --- | :---: | :---: | :---: | +| [Agentic GraphRAG](/use-cases/agentic-graphrag) | ✅ | ✅ | ✅ | +| [AI Memory](/use-cases/ai-memory) | ✅ | ✅ | ⬜ | +| [Agentic AI](/use-cases/agentic-ai) | ✅ | ✅ | ✅ | diff --git a/pages/use-cases/_meta.ts b/pages/use-cases/_meta.ts new file mode 100644 index 000000000..5c5d23376 --- /dev/null +++ b/pages/use-cases/_meta.ts @@ -0,0 +1,5 @@ +export default { + "agentic-graphrag": "Agentic GraphRAG", + "ai-memory": "AI Memory", + "agentic-ai": "Agentic AI" +} diff --git a/pages/use-cases/agentic-ai.mdx b/pages/use-cases/agentic-ai.mdx new file mode 100644 index 000000000..369e707b5 --- /dev/null +++ b/pages/use-cases/agentic-ai.mdx @@ -0,0 +1,224 @@ +--- +title: Agentic AI +description: Agents that plan, not prompt — model the problem as a reasoning graph on a shared, federated data layer and plan by traversal instead of by prompting. +--- + +# Agentic AI: Reasoning Graphs on a Shared Data Layer + +> Agents That Plan. Not Prompt. + +On Memgraph ([memgraph.com/agentic-ai](https://memgraph.com/agentic-ai)) an agent +models its problem as a **reasoning graph** and plans by traversal instead of by +prompting: + +- **nodes** = states / decision points +- **edges** = available actions +- **properties** = scores (expected value, success rate, feasibility) + +Four graph operations replace LLM guesswork, and the path an agent takes is an +**inspectable, auditable trace** that can be scored against alternatives: + +| Operation | What it answers | +| --- | --- | +| **Weighted traversal** | Evaluate multi-step plans without LLM calls | +| **Shortest path** | Most efficient route to a goal | +| **Centrality** | Which intermediate states are critical | +| **Community detection** | Which sub-tasks can run in parallel | + +The page also stresses **multi-agent coordination over shared state**. That +shared layer is **Memgraph Zero / MemGQL**: a federated GQL engine that puts one +Bolt + GQL endpoint in front of many backends, so a fleet of agents reaches the +same data with no ETL. This example federates two sources: + +- **Memgraph** hosts the **reasoning graph** the agents plan over (plus MAGE algorithms). +- **PostgreSQL** hosts **customer records** the agents pull as shared context. + +## High-level Plan + +1. **Start the shared data layer**: Memgraph + Postgres, federated by MemGQL. +2. **Seed the reasoning graph** (a customer-support agent's plan space). +3. **Read shared context** through the one MemGQL endpoint (multi-agent coordination). +4. **Plan over the reasoning graph** with the four operations, and audit the choice. + +## What You Need + +- **Docker**: https://docs.docker.com/get-docker/ + +Docker only. No API keys. Uses the Memgraph ecosystem plus stock `postgres` +(PostgreSQL is one of MemGQL's supported connectors). + +## Run It + +The scripts live in the +[memgraph/memgraph-platform](https://github.com/memgraph/memgraph-platform/tree/main/code-examples) +repository. + +macOS / Linux: + +```bash +./agentic-ai.sh # bring up the shared layer + reasoning graph, then plan +./agentic-ai.sh clean # stop and remove everything the script created +``` + +Windows (PowerShell 5.1 or 7+), same steps, same output: + +```powershell +.\agentic-ai.ps1 # bring up the shared layer + reasoning graph, then plan +.\agentic-ai.ps1 clean # stop and remove everything the script created +``` + +If Windows blocks the script, allow local scripts for the session first: +`Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass`. The script +bind-mounts two generated files into containers, so the drive it lives on must be +shared with Docker Desktop (**Settings → Resources → File sharing**; `C:\Users` is +shared by default). + +## Step-by-step + +### 1. Start the shared data layer + +Demo-scoped names (`zero-demo-*`) avoid clobbering your own containers. Only +MemGQL's port (`7688`) is published; the backends are reached internally, so +agents talk to a single endpoint: + +```bash +docker network create zero-demo-net + +docker run -d --name zero-demo-memgraph --network zero-demo-net \ + memgraph/memgraph-mage:3.12.0 --schema-info-enabled=True --log-level=TRACE --also-log-to-stderr + +docker run -d --name zero-demo-postgres --network zero-demo-net \ + -e POSTGRES_PASSWORD=postgres \ + -v "$PWD/.memgql-work/init.sql":/docker-entrypoint-initdb.d/init.sql \ + postgres:18 + +docker run -d --name zero-demo-memgql --network zero-demo-net --stop-timeout 2 -p 7688:7688 \ + --env CONNECTOR_TYPE=multi \ + --env BOLT_LISTEN_ADDR=0.0.0.0:7688 \ + -v "$PWD/.memgql-work/mapping.json":/data/mapping.json \ + memgraph/memgql:0.7.0 +``` + +MemGQL learns about each backend and opens a named connection to it: + +```cypher +ADD CONNECTOR mg TYPE memgraph URI 'zero-demo-memgraph:7687' GRAPH memgraph; +CONNECT mg AS mg_conn; + +ADD MAPPING social FROM '/data/mapping.json'; +ADD CONNECTOR pg TYPE postgres URI 'host=zero-demo-postgres user=postgres password=postgres dbname=postgres' MAPPING social; +CONNECT pg AS pg_conn; +``` + +### 2. Seed the reasoning graph + +States are nodes, actions are scored edges. The score is the expected probability +that the action moves the ticket toward resolution: + +```cypher +MERGE (s0:State {name:"Ticket received"}); +MERGE (s1:State {name:"Assess severity"}); +MERGE (a:State {name:"Auto-resolve"}); +MERGE (e:State {name:"Escalate to human"}); +MERGE (d:State {name:"Resolved"}); +MATCH (s0:State{name:"Ticket received"}),(s1:State{name:"Assess severity"}) MERGE (s0)-[:ACTION {name:"triage", score:1.0}]->(s1); +MATCH (s1:State{name:"Assess severity"}),(a:State{name:"Auto-resolve"}) MERGE (s1)-[:ACTION {name:"auto_resolve", score:0.87}]->(a); +MATCH (s1:State{name:"Assess severity"}),(e:State{name:"Escalate to human"}) MERGE (s1)-[:ACTION {name:"escalate", score:0.54}]->(e); +MATCH (a:State{name:"Auto-resolve"}),(d:State{name:"Resolved"}) MERGE (a)-[:ACTION {name:"close", score:0.92}]->(d); +MATCH (e:State{name:"Escalate to human"}),(d:State{name:"Resolved"}) MERGE (e)-[:ACTION {name:"human_fix", score:0.95}]->(d); +``` + +### 3. Read shared context through MemGQL + +Every agent reads the same federated layer. An agent fetches customer context +from Postgres, through MemGQL, with no copy: + +```cypher +USE CONNECTION pg_conn + MATCH (c:Customer)-[:WORKS_AT]->(co:Company) + WHERE c.tier = 'enterprise' + RETURN c.name AS customer, c.tier AS tier, co.name AS company; +``` + +### 4. Plan over the reasoning graph + +These run natively in Memgraph (MAGE and weighted shortest path). + +**Weighted traversal** ranks whole plans by expected value, no LLM in the loop: + +```cypher +MATCH path=(:State {name:"Ticket received"})-[rels:ACTION *1..6]->(:State {name:"Resolved"}) +RETURN [n IN nodes(path) | n.name] AS plan, + reduce(p=1.0, r IN rels | p * r.score) AS expected_value +ORDER BY expected_value DESC LIMIT 4; +``` + +The top result, `Ticket received → Assess severity → Auto-resolve → Resolved` +(expected value 0.8), is the **chosen path**; the next row is the scored +**alternative**. Returning both is the audit trail the page describes. + +**Shortest path** finds the most efficient route to the goal (cost = `1 - score`): + +```cypher +MATCH path=(:State {name:"Ticket received"})-[:ACTION *WSHORTEST (e, n | 1.0 - e.score) total_cost]->(:State {name:"Resolved"}) +RETURN [x IN nodes(path) | x.name] AS route, total_cost AS cost; +``` + +**Centrality** flags the critical intermediate state (here, `Assess severity`): + +```cypher +CALL betweenness_centrality.get() YIELD node, betweenness_centrality +RETURN node.name AS state, betweenness_centrality AS centrality +ORDER BY centrality DESC LIMIT 5; +``` + +**Community detection** groups sub-tasks a fleet of agents can take in parallel: + +```cypher +CALL community_detection.get() YIELD node, community_id +RETURN community_id, collect(node.name) AS states ORDER BY community_id; +``` + +## Give a Fleet of Agents MCP Access + +Run the Memgraph MCP server against MemGQL's endpoint (`bolt://localhost:7688`) so +every agent shares the same layer through MCP (see +[`agentic-graphrag.sh`](https://github.com/memgraph/memgraph-platform/blob/main/code-examples/agentic-graphrag.sh) +for a working MCP setup): + +```json +{ + "mcpServers": { + "memgraph-zero": { + "url": "http://localhost:8000/mcp/" + } + } +} +``` + +## Notes (MemGQL Is Early) + +- **Native analytics run in Memgraph.** MAGE algorithms and weighted shortest path + execute in Memgraph itself; MemGQL federates pattern queries and pushes them + down to each source. +- **No auth yet**: keep it local. +- **Two data sources** in MemGQL Community (unlimited in Enterprise). + +## Clean Up + +```bash +./agentic-ai.sh clean # .\agentic-ai.ps1 clean on Windows +# and, if you started Lab: +docker rm -f memgql-lab +``` + +## Where to Go Next + +- [Memgraph Agentic AI](https://memgraph.com/agentic-ai) (reasoning graphs and the + four planning operations). +- [Memgraph Zero](/memgraph-zero) / + [MemGQL docs](/memgraph-zero/memgql) and the + [complete Docker Compose setup](/memgraph-zero/memgql/complete). +- Docs: [betweenness centrality](/advanced-algorithms/available-algorithms/betweenness_centrality), + [community detection](/advanced-algorithms/available-algorithms/community_detection), + [weighted shortest path](/advanced-algorithms/deep-path-traversal). diff --git a/pages/use-cases/agentic-graphrag.mdx b/pages/use-cases/agentic-graphrag.mdx new file mode 100644 index 000000000..347816f08 --- /dev/null +++ b/pages/use-cases/agentic-graphrag.mdx @@ -0,0 +1,209 @@ +--- +title: Agentic GraphRAG +description: Run the three GraphRAG retrieval pipelines (Text2Cypher, pivot search + relevance expansion, query-focused summarisation) as atomic Cypher, then let an LLM agent pick the pipeline. +--- + +# Agentic GraphRAG with Memgraph + +Standard RAG retrieves text chunks by similarity. **GraphRAG** traverses a +knowledge graph to follow multi-hop relationships across entities, giving an LLM +structured context that vector search alone misses. On Memgraph +([memgraph.com/graphrag](https://memgraph.com/graphrag)) the whole retrieval +pipeline runs as **one atomic database operation**, not a distributed system you +orchestrate, which makes each pipeline self-contained and easy for an agent to +generate. + +Memgraph frames GraphRAG as **three retrieval pipeline types**, each matched to a +kind of question: + +| Pipeline | Question type | Example | +| --- | --- | --- | +| **Text2Cypher** | Analytical | "How many organizations of each type are covered?" | +| **Pivot search + relevance expansion** | Local | "What is connected to NVIDIA?" | +| **Query-focused summarisation** | Global | "What are the main themes overall?" | + +This example imports a real knowledge graph and runs **all three pipelines as +atomic Cypher** against it (Docker only). It then optionally launches Memgraph's +official **agentic** GraphRAG app, where an LLM agent classifies each question and +picks the matching pipeline for you. The **Memgraph MCP server** is also started +so your own harness (Claude Desktop, Cursor, VS Code) can query the same graph. + +## High-level Plan + +1. **Spin up** Memgraph and the Memgraph MCP server. +2. **Load** a knowledge graph (an AskNews finance dataset). +3. **Run the three GraphRAG pipelines** as atomic queries (Analytical, Local, Global). +4. **Optional agent**: let an LLM pick the pipeline, or attach your own MCP harness. + +## What You Need + +- **Docker**: https://docs.docker.com/get-docker/ (required) +- **git**: https://git-scm.com/downloads (required) +- For the **optional** agentic app only: + - **Python 3.10–3.13 and pip**: https://www.python.org/downloads/ (the demo's + pinned deps have no wheels for 3.14+; the script auto-picks a compatible one) + - **An OpenAI API key**: `export OPENAI_API_KEY=sk-...` + +## Run It + +The scripts live in the +[memgraph/memgraph-platform](https://github.com/memgraph/memgraph-platform/tree/main/code-examples) +repository. + +macOS / Linux: + +```bash +./agentic-graphrag.sh # import + run the three atomic pipelines (Docker only) +./agentic-graphrag.sh clean # stop containers and remove the work dir +``` + +Windows (PowerShell 5.1 or 7+), same steps, same output: + +```powershell +.\agentic-graphrag.ps1 # import + run the three atomic pipelines (Docker only) +.\agentic-graphrag.ps1 clean # stop containers and remove the work dir +``` + +Or run it straight from the web, without downloading it first: + +```powershell +iwr -UseBasicParsing https://raw.githubusercontent.com/memgraph/memgraph-platform/main/code-examples/agentic-graphrag.ps1 | iex +``` + +This does the same as the bare form above. `clean` needs the downloaded file, but +the script also prints the equivalent `docker` commands when you run it this way. + +If Windows blocks the script, allow local scripts for the session first: +`Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass`. + +To also launch the LLM agent app, set a key first: + +```bash +export OPENAI_API_KEY=sk-... +./agentic-graphrag.sh # runs the pipelines, then opens the app at :8501 +``` + +```powershell +$env:OPENAI_API_KEY = "sk-..." +.\agentic-graphrag.ps1 # runs the pipelines, then opens the app at :8501 +``` + +## Step-by-step + +### 1. Spin up Memgraph and the MCP server + +Memgraph starts with schema info enabled (so a connected agent can inspect the +graph), and the MCP server is pointed at it: + +```bash +docker network create agenticgraphrag-net + +docker run -d --name agenticgraphrag-memgraph --network agenticgraphrag-net \ + -p 7687:7687 -p 7444:7444 \ + memgraph/memgraph-mage:3.12.0 --schema-info-enabled=True + +docker run -d --name agenticgraphrag-mcp --network agenticgraphrag-net \ + -p 8000:8000 --env MEMGRAPH_URL=bolt://agenticgraphrag-memgraph:7687 \ + memgraph/mcp-memgraph:0.2.0 +``` + +### 2. Load the knowledge graph + +The demo ships a `.cypherl` dump. `mgconsole` accepts a bounded amount of input +per call, so the script streams it in batches over the Docker network (the same +idea as the demo's `setup.sh`, but network-based so it behaves the same on Linux, +macOS, and Windows): + +```bash +lines=$(wc -l < asknews-finance-graph.cypherl); batch=300; start=1 +while [ "$start" -le "$lines" ]; do + sed -n "${start},$((start + batch - 1))p" asknews-finance-graph.cypherl \ + | docker run -i --rm --network agenticgraphrag-net memgraph/mgconsole:1.6.0 \ + --host agenticgraphrag-memgraph --port 7687 + start=$((start + batch)) +done +``` + +This loads roughly 1,000 nodes and 1,600 relationships (finance entities such as +organizations, people, markets, and events). Swap in your own `.cypherl` to make +the example dataset-agnostic. + +### 3. Run the three GraphRAG pipelines + +Each pipeline is a single atomic query. This is the core of GraphRAG on Memgraph; +the agent in step 4 just decides which one to run. + +**Text2Cypher (Analytical)** turns an analytical question into one aggregating query: + +```cypher +MATCH (n:organization) WHERE n.detailed_type IS NOT NULL +RETURN n.detailed_type AS organization_type, count(*) AS count +ORDER BY count DESC LIMIT 8; +``` + +**Pivot search + relevance expansion (Local)** pivots on a seed entity, then +expands its neighborhood in one traversal. In production the pivot is a native +vector search; here we pivot by name: + +```cypher +MATCH (seed {id: 'nvidia'})-[*1..2]-(context) +RETURN DISTINCT context.id AS related_entity, context.main_type AS type +LIMIT 10; +``` + +**Query-focused summarisation (Global)** ranks the whole graph with PageRank +(MAGE) to surface the central themes an LLM would then summarise: + +```cypher +CALL pagerank.get() YIELD node, rank +RETURN node.id AS theme, node.main_type AS type, round(rank * 10000) / 10000 AS importance +ORDER BY importance DESC LIMIT 10; +``` + +On the AskNews finance graph this surfaces "federal reserve", "us stock market", +and "wall street" as the top themes. + +### 4. Optional: let an agent pick the pipeline + +**a) The official agentic app.** If `OPENAI_API_KEY` is set, the script creates a +virtualenv, installs the demo's `requirements.txt` (Streamlit, the Neo4j driver, +`sentence-transformers`, `openai`), and launches it: + +```bash +streamlit run agenticGraphRAG.py # http://localhost:8501 +``` + +The agent classifies each question and runs the matching pipeline. It makes +autonomous decisions, so the same question can take different paths across runs. + +**b) Your own MCP harness.** The MCP server is already running, so any MCP-capable +assistant can query the same graph. Add to its MCP config: + +```json +{ + "mcpServers": { + "memgraph": { + "url": "http://localhost:8000/mcp/" + } + } +} +``` + +Your assistant then has tools like `run_query`, `get_schema`, `get_page_rank`, +and `search_node_vectors`, the same building blocks the three pipelines use. + +## Clean Up + +```bash +./agentic-graphrag.sh clean # .\agentic-graphrag.ps1 clean on Windows +``` + +## Where to Go Next + +- [Memgraph GraphRAG](https://memgraph.com/graphrag) (the three pipeline types and + the atomic retrieval pipeline). +- Blog: [How To Build Agentic GraphRAG?](https://memgraph.com/blog/build-agentic-graphrag-ai) +- Demo source: [memgraph/ai-demos / agentic-graph-rag/agentic](https://github.com/memgraph/ai-demos/tree/main/agentic-graph-rag/agentic) +- Docs: [Memgraph GraphRAG](/ai-ecosystem/graph-rag), + [vector search](/querying/vector-search), + [PageRank](/advanced-algorithms/available-algorithms/pagerank). diff --git a/pages/use-cases/ai-memory.mdx b/pages/use-cases/ai-memory.mdx new file mode 100644 index 000000000..373c2fadb --- /dev/null +++ b/pages/use-cases/ai-memory.mdx @@ -0,0 +1,236 @@ +--- +title: AI Memory +description: Vector memory forgets, graphs don't — model semantic, episodic and procedural memory as one unified graph and recall it with a single traversal. +--- + +# AI Memory with Memgraph + +> Vector Memory Forgets. Graphs Don't. + +LLMs are stateless, so they need an external memory. Vector memory retrieves what +*sounds* similar, not what is structurally relevant given the full history. On +Memgraph ([memgraph.com/ai-memory](https://memgraph.com/ai-memory)) memory is a +**graph** of entities and typed relationships you traverse, so recall follows the +actual connections between what the system knows, did, and knows how to do. + +Memgraph models three kinds of long-term memory as one unified graph: + +| Memory type | What it holds | How it is stored | +| --- | --- | --- | +| **Semantic** | What the system **knows** (facts, preferences) | `(:User)-[:HAS_MEMORY]->(:Memory)` | +| **Episodic** | What the system **experienced** (past interactions, time) | `(:Session)-[:HAS_ACTION]->(:Action)`, sequenced by `FOLLOWED_BY` | +| **Procedural** | What the system **knows how to do** (workflows) | `(:Session)-[:USED_SKILL]->(:Skill)` | + +This example writes and reads all three through the actual +[Context Graph](https://github.com/memgraph/ai-toolkit/tree/main/context-graph) +packages a live coding-assistant plugin uses — `sessions-graph`, `actions-graph`, +`skills-graph` — instead of a hand-rolled schema. The `(:User)`/`(:Session)` +nodes those three packages share are the join key, so the payoff is a genuine +graph traversal, not three separate lookups glued together. + +## High-level Plan + +1. **Spin up** the memory store (Memgraph). +2. **Write** the three memory types for a client the assistant has worked with, + through `sessions-graph`/`actions-graph`/`skills-graph`. +3. **Recall** each type, then all three together to answer *"Schedule a + follow-up with the client like last time."* + +## What You Need + +- **Docker**: https://docs.docker.com/get-docker/ +- **Python 3.10-3.13**: https://www.python.org/downloads/ (installs the three + Context Graph packages above from PyPI into a throwaway virtualenv — no + repository checkout needed) + +No API keys: this example writes structured memory directly, the same way an +application would call these packages. Automatic, LLM-backed extraction from +raw conversation text is a separate, opt-in step — see +[Where to Go Next](#where-to-go-next). + +## Run It + +The scripts live in the +[memgraph/memgraph-platform](https://github.com/memgraph/memgraph-platform/tree/main/code-examples) +repository. + +macOS / Linux: + +```bash +./ai-memory.sh # bring everything up, seed memory, run recall +./ai-memory.sh clean # stop and remove everything the script created +``` + +Windows (PowerShell 5.1 or 7+), same steps, same output: + +```powershell +.\ai-memory.ps1 # bring everything up, seed memory, run recall +.\ai-memory.ps1 clean # stop and remove everything the script created +``` + +If Windows blocks the script, allow local scripts for the session first: +`Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass`. + +## Step-by-step + +### 1. Spin up Memgraph + +Memgraph starts with schema info enabled, so the ontology is queryable once the +Context Graph packages have written into it: + +```bash +docker network create aimemory-net + +docker run -d --name aimemory-memgraph --network aimemory-net \ + -p 7687:7687 -p 7444:7444 \ + memgraph/memgraph-mage:3.12.0 --schema-info-enabled=True +``` + +### 2. Install the Context Graph memory packages + +```bash +python3 -m venv .ai-memory-venv +.ai-memory-venv/bin/pip install sessions-graph actions-graph skills-graph memgraph-toolbox +``` + +### 3. Write the three memory types + +The assistant has met a client before and knows how to schedule follow-ups. +That knowledge is split across three packages, glued together by a shared +`(:User {user_id})` and two `(:Session {session_id})` nodes +(`session-acme-kickoff`, `session-acme-followup`) — see +[`ai-memory.py`](https://github.com/memgraph/memgraph-platform/blob/main/code-examples/ai-memory.py): + +```python +# Episodic: two real sessions, each with a ToolCall/ToolResult (actions-graph) +actions.create_session(Session(session_id="session-acme-kickoff", ...)) +actions.create_session(Session(session_id="session-acme-followup", ...)) +actions.record_tool_call(session_id=..., tool_name="schedule_meeting", tool_input={...}) +actions.record_tool_result(session_id=..., tool_use_id=..., tool_name="schedule_meeting", ...) + +# Semantic: a durable fact about the client (sessions-graph) +memories.save_memory( + user_id="acme-corp", + content="Acme Corp's contact is Dana Lee (timezone America/New_York); they prefer 30-minute meetings.", + session_id="session-acme-kickoff", +) + +# Procedural: a reusable skill, used during the follow-up session (skills-graph) +skills.add_skill(Skill(name="schedule-follow-up", description="...", content="1. Book a calendar slot...\n2. Send a calendar invite.")) +skills.record_skill_usage(session_id="session-acme-followup", skill_name="schedule-follow-up", action="used", timestamp=...) +``` + +Run it: + +```bash +MEMGRAPH_URL=bolt://localhost:7687 .ai-memory-venv/bin/python ai-memory.py +``` + +### 4. Recall + +Each memory type is a small, package-provided lookup: + +```python +memories.get_memories("acme-corp") # semantic +actions.list_sessions(limit=1) # episodic: most recent session +actions.get_session_actions(session.session_id) # ... and what happened in it +skills.get_skill("schedule-follow-up") # procedural +``` + +The payoff is the **interconnected** recall: one Cypher traversal through the +shared `User`/`Session` nodes joins all three to answer *"schedule a follow-up +with the client like last time"*: + +```cypher +MATCH (u:User {user_id: "acme-corp"})-[:HAS_MEMORY]->(mem:Memory) +MATCH (u)-[:HAD_SESSION]->(s:Session)-[:HAS_ACTION]->(a:Action {tool_name: "schedule_meeting"}) +WITH u, mem, s, a ORDER BY s.started_at DESC LIMIT 1 +OPTIONAL MATCH (s)-[:USED_SKILL]->(sk:Skill) +RETURN mem.content AS client_facts, s.session_id AS last_session, + a.timestamp AS last_meeting_at, sk.name AS skill, sk.content AS how_to +``` + +It returns *Dana Lee's Acme Corp facts, the `session-acme-followup` session, +the `schedule-follow-up` skill and its steps* — everything needed for the +assistant to reply *"Done. 30 min Tuesday slot booked, invite sent."* + +### 5. Inspect the memory ontology + +`SHOW SCHEMA INFO` returns the whole ontology (labels, relationship types, +properties) in constant time, so an agent can learn the shape of memory before +querying it — now the real `User`/`Session`/`Memory`/`Action`/`Skill` schema +the Context Graph packages created, not a demo-only schema: + +```cypher +SHOW SCHEMA INFO; +``` + +### 6. Explore visually (optional) + +```bash +docker run -d --name aimemory-lab --network aimemory-net -p 3000:3000 \ + -e QUICK_CONNECT_MG_HOST=aimemory-memgraph -e QUICK_CONNECT_MG_PORT=7687 \ + memgraph/lab:3.12.0 +# open http://localhost:3000 -> MATCH p=()-[]-() RETURN p; +``` + +## Wire It Into a Real Harness + +The seeding above did by hand what a real coding-assistant plugin does +automatically. One script installs and wires the +[Context Graph](https://github.com/memgraph/ai-toolkit/tree/main/context-graph) +plugin end to end for Claude Code or Codex, defaulting to this same Memgraph +instance (`bolt://localhost:7687`, no auth, database `memgraph`): + +```bash +curl -fsSL https://raw.githubusercontent.com/memgraph/ai-toolkit/main/context-graph/scripts/install.sh | bash +# Codex instead of Claude Code: +CONTEXT_GRAPH_RUNTIME=codex bash -c "$(curl -fsSL https://raw.githubusercontent.com/memgraph/ai-toolkit/main/context-graph/scripts/install.sh)" +``` + +It registers the runtime's plugin marketplace and installs the plugin — the +step a bare `agent-context-graph bootstrap` can't do, since that's what +actually wires hooks into the runtime — installs the CLI with all three +connectors, sets your identity, and verifies with `doctor`. It even starts +Memgraph itself if nothing's reachable, so on a clean machine it doubles as +an alternative to steps 1–2 above. Override identity with +`AGENT_CONTEXT_GRAPH_USER_ID` (defaults to `git config user.name`); see the +[Context Graph guide](https://github.com/memgraph/ai-toolkit/blob/main/context-graph/README.md#getting-started-claude-code-or-codex) +for the rest of the configurable env vars and defaults, reconciliation, and +cross-component queries. + +Every real session then writes `Memory`/`Action`/`Skill` nodes automatically — +the same nodes `ai-memory.py` just wrote by hand — and the next session reads +that memory back before it starts. + +## Clean Up + +```bash +./ai-memory.sh clean # .\ai-memory.ps1 clean on Windows +# and, if you started Lab: +docker rm -f aimemory-lab +``` + +If you ran the installer above, mind the order: the plugin keeps writing to +whatever answers on `bolt://localhost:7687` — which is this demo's container. +Removing it leaves the hooks with nowhere to write. Either hold off until you're +done with the plugin, or re-run `install.sh` afterwards — with nothing reachable +it starts a Memgraph of its own on the same port. + +## Where to Go Next + +- [Memgraph AI Memory](https://memgraph.com/ai-memory) (the three memory types and + the graph-vs-vector argument). +- Turn on **automatic, LLM-backed extraction**: this example wrote Memory nodes + by hand; `sessions-graph`'s reconciliation step instead extracts entities + from real session transcripts via `unstructured2graph` + LightRAG — see + [sessions-graph § reconciliation](https://github.com/memgraph/ai-toolkit/blob/main/context-graph/sessions-graph/README.md#session-reconciliation). +- Add **semantic recall by similarity**: `sessions-graph` already maintains a + full-text index over `Memory.content`; pair it with Memgraph + [vector search](/querying/vector-search) for + embedding-based recall alongside traversal. +- Retrieve memory with the same [GraphRAG](https://memgraph.com/graphrag) pipelines + (Text2Cypher, pivot search, query-focused summarisation); see the + [Agentic GraphRAG](/use-cases/agentic-graphrag) use case. +- Read the [Context Graph](https://github.com/memgraph/ai-toolkit/tree/main/context-graph) + project docs and [AI ecosystem](/ai-ecosystem) docs.