Ask your support agent what laptop a customer uses and it will answer confidently — from a chat log three weeks old. The customer switched laptops since. The agent isn't lying; it is remembering the wrong version of the truth.

Retrieval-augmented generation stores passages. Passages don't know they expired. What an agent needs is a memory that tracks when each fact was true — and when it stopped being true. That is what Zep's open-source Graphiti builds: a temporal knowledge graph. Entities, relationships, and facts, each with a validity window, all traced back to the raw episodes they came from. When a fact changes, the old one is invalidated, not deleted, so the agent can answer "what is true now?" and "what was true then?" from the same graph.

The idea comes from Zep's paper, "Zep: A Temporal Knowledge Graph Architecture for Agent Memory" (arXiv:2501.13956). The paper reports, on its own benchmarks, 94.8% accuracy on the Deep Memory Retrieval task against 93.4% for the MemGPT baseline, up to 18.5% higher accuracy on LongMemEval, and roughly 90% lower latency — vendor-reported numbers, but the architecture is what matters here: a bi-temporal model where every fact carries both the time it was true in the world and the time it was recorded.

Until recently, trying Graphiti meant standing up Neo4j or FalkorDB first — a server, a container, credentials. Graphiti 0.32.1 changes the on-ramp: the new Relate backend is an embedded graph database that lives inside your Python process. No server, no container, one file on disk. This tutorial builds a working temporal memory for a fictional support agent, first with OpenAI, then with a fully local Ollama setup — and proves, with real output, that a superseded fact gets invalidated instead of silently lingering.

What you'll need#

  • Python 3.11 or newer. Relate requires 3.11+; the walkthrough uses 3.12.
  • pip and a virtual environment. Nothing in this tutorial installs anything system-wide.
  • Either an OpenAI API key (the fast path; the demo costs pennies) or Ollama with about 2.5 GB free for a local 3B model and an embedding model.
  • About 45 minutes if you take the local path on a modest machine (the three-episode demo took about 22 minutes on a 1.5-CPU virtual machine; a desktop CPU will be faster). The OpenAI path runs in about a minute.

Versions used here, all verified against the packages as installed: graphiti-core 0.32.1, relate-db 1.0.1, Ollama 0.40.19, Qwen2.5:3b, nomic-embed-text. Graphiti is Apache-2.0, from getzep/graphiti on GitHub, which had about 33,200 stars at the time of writing.

1. Install Graphiti with the Relate backend#

Create a virtual environment and install Graphiti with the Relate extra. The extra pulls in relate-db, the embedded database; without it, RelateDriver is not available.

python3 -m venv .venv
source .venv/bin/activate
pip install "graphiti-core[relate]==0.32.1"

Confirm the install and the versions before going further. A quick import check also verifies that Relate's native library loads on your platform:

python -c "import graphiti_core, relate; print('graphiti-core OK'); print('relate OK')"

One note before you run anything: Graphiti collects anonymous usage telemetry — a random UUID, your OS, Python version, and configuration choices, never your data, keys, or content. Opt out with an environment variable:

export GRAPHITI_TELEMETRY_ENABLED=false

Set it in your shell and also inside your script, so the setting survives however the script is launched.

2. Pick your LLM: OpenAI, or Ollama on your own machine#

Graphiti needs three model clients: an LLM to extract entities and facts and to judge duplicates and contradictions, an embedder for vector search, and a cross-encoder to rerank results. If you pass none of them, Graphiti builds default OpenAI clients — the LLM defaults to gpt-6-luna for both the main model and the smaller model, and the embedder defaults to text-embedding-3-small (1,024 dimensions). All the OpenAI path needs is a key:

export OPENAI_API_KEY="sk-..."
from graphiti_core import Graphiti
from graphiti_core.driver.relate_driver import RelateDriver

# Defaults: OpenAI LLM (gpt-6-luna) + text-embedding-3-small.
# No llm_client / embedder / cross_encoder arguments needed.
graphiti = Graphiti(graph_driver=RelateDriver("support.relate"))

The local path takes more wiring, and it is the path every output in this tutorial comes from. Install Ollama, pull a small instruction model and an embedding model, and start the server:

ollama pull qwen2.5:3b
ollama pull nomic-embed-text
ollama serve

Qwen2.5:3b is about 2.1 GB; nomic-embed-text is 84 MB and produces 768-dimensional vectors. Then construct the clients explicitly. Three details matter, and each one cost a failed run to learn:

  • Use OpenAIGenericClient, not OpenAIClient. The generic client is built for OpenAI-compatible endpoints and defaults to a 16,000-token context window instead of 8,000.
  • Set temperature=0. Extraction is a precision task. The default temperature of 1 makes a small model sample noisily; this run's temperature-1 attempt hallucinated entities — people and places never mentioned in the episodes — and missed facts entirely. Step 6 shows the evidence.
  • Keep structured_output_mode="json_schema", the default. Ollama enforces the schema through constrained decoding, so the model cannot return a schema instead of data. With json_object, this run's 3B model returned the JSON Schema itself and the dedupe step crashed with a Pydantic validation error. The README's advice to prefer json_object on small local models assumes a server that does not enforce schemas; Ollama does enforce them, so json_schema is the right call here.
from graphiti_core import Graphiti
from graphiti_core.driver.relate_driver import RelateDriver
from graphiti_core.cross_encoder.openai_reranker_client import OpenAIRerankerClient
from graphiti_core.embedder.openai import OpenAIEmbedder, OpenAIEmbedderConfig
from graphiti_core.llm_client.config import LLMConfig
from graphiti_core.llm_client.openai_generic_client import OpenAIGenericClient

llm_config = LLMConfig(
    api_key="ollama",  # Ollama needs a placeholder, not a real key
    model="qwen2.5:3b",
    small_model="qwen2.5:3b",
    base_url="http://localhost:11434/v1",
    temperature=0,  # extraction is a precision task
)
llm_client = OpenAIGenericClient(
    config=llm_config,
    structured_output_mode="json_schema",  # Ollama enforces it; see Step 6
)
embedder = OpenAIEmbedder(
    config=OpenAIEmbedderConfig(
        api_key="ollama",
        embedding_model="nomic-embed-text",
        embedding_dim=768,  # nomic-embed-text is 768-dimensional
        base_url="http://localhost:11434/v1",
    )
)
graphiti = Graphiti(
    graph_driver=RelateDriver("support.relate"),
    llm_client=llm_client,
    embedder=embedder,
    cross_encoder=OpenAIRerankerClient(client=llm_client, config=llm_config),
)

One more setting for the local path: Graphiti runs up to 10 LLM calls concurrently by default (SEMAPHORE_LIMIT). A CPU-served 3B model cannot take that load — calls queue, time out, and the run dies. Set it to 1 before running:

export SEMAPHORE_LIMIT=1

On a GPU machine, or with the OpenAI path, leave the default alone.

3. Open the graph#

The Relate driver takes a file path. Pass ":memory:" and the graph is ephemeral — useful for tests, useless for a memory. Give it a real path and the graph persists as a single file you can copy, back up, or delete.

await graphiti.build_indices_and_constraints()

Call this once after constructing the client. It creates the indices and constraints the driver needs; the first run prints nothing except your own logging, but without it, ingestion fails.

The other concept to fix now is the group id. Graphiti partitions one graph into groups, and the natural group for an agent memory is one user, customer, or tenant. Every episode and every search in this tutorial uses group_id="maya-chen", so one customer's facts never leak into another customer's answers.

4. Feed it episodes: a customer whose facts keep changing#

An episode is one unit of experience — a chat message, a ticket update, a document — with a reference_time. That timestamp is the time the fact was true, not the time you ingested it, and it is what the validity windows are built from. Get it right: backfilling a chat log with today's date as the reference time would stamp every fact "true now," which defeats the point.

Four blank message blocks with arrows flowing into a glowing knowledge graph
AI-generated illustration for AI Frontier Post.

Our customer is Maya Chen, a fictional support user whose facts keep changing. Three episodes, one change per episode, each phrased plainly — short declarative sentences, one fact at a time. That phrasing is deliberate: with a small local model, crisp episodes extract far more reliably than chatty paragraphs, and stating a change explicitly ("no longer uses… now uses…") gives the contradiction detector the signal it needs.

from datetime import datetime, timezone
from graphiti_core.nodes import EpisodeType

EPISODES = [
    {
        "name": "Ticket opened",
        "episode_body": (
            "Maya Chen uses a MacBook Pro 14-inch. "
            "Maya Chen is on the Free plan."
        ),
        "reference_time": datetime(2026, 11, 20, 10, 0, tzinfo=timezone.utc),
    },
    {
        "name": "Laptop replaced",
        "episode_body": (
            "Maya Chen no longer uses a MacBook Pro 14-inch. "
            "Maya Chen now uses a ThinkPad X1 Carbon."
        ),
        "reference_time": datetime(2026, 11, 24, 15, 30, tzinfo=timezone.utc),
    },
    {
        "name": "Plan upgrade",
        "episode_body": (
            "Maya Chen is on the Pro plan. "
            "Maya Chen is no longer on the Free plan. "
            "Maya Chen asked whether the Pro plan covers accidental damage "
            "for her ThinkPad X1 Carbon."
        ),
        "reference_time": datetime(2026, 11, 26, 9, 15, tzinfo=timezone.utc),
    },
]

for ep in EPISODES:
    result = await graphiti.add_episode(
        name=ep["name"],
        episode_body=ep["episode_body"],
        source_description="support chat",
        reference_time=ep["reference_time"],
        source=EpisodeType.message,
        group_id="maya-chen",
    )
    print(f"episode '{ep['name']}': {len(result.nodes)} nodes, {len(result.edges)} edges")
    for edge in result.edges:
        print(f"  EDGE: {edge.fact} | valid_at={edge.valid_at} invalid_at={edge.invalid_at}")

Here is the real output from the local run, episode by episode. Episode 1 ingested cleanly, though imperfectly — the model extracted the laptop fact but missed the Free-plan fact entirely. Small models drop facts; note it and move on, because the important part is what happens next.

episode 'Ticket opened': 3 nodes, 1 edges
  EDGE: Maya Chen uses a MacBook Pro 14-inch. | valid_at=2026-11-20 10:00:00+00:00 invalid_at=None

Episode 2 is the one this tutorial exists for. The new ThinkPad fact arrives — and the episode-1 MacBook edge comes back with invalid_at set to exactly episode 2's reference time:

episode 'Laptop replaced': 9 nodes, 2 edges
  EDGE: Maya Chen uses a ThinkPad X1 Carbon instead of a MacBook Pro 14-inch | valid_at=2026-11-24 15:30:00+00:00 invalid_at=None
  EDGE: Maya Chen uses a MacBook Pro 14-inch. | valid_at=2026-11-20 10:00:00+00:00 invalid_at=2026-11-24 15:30:00+00:00

Read the second line carefully. The MacBook fact was not deleted. It now carries a validity window: true from November 20 at 10:00, false from November 24 at 15:30. The graph remembers that Maya used a MacBook, and knows she no longer does. That is the whole idea, working, on a 3B model running on a CPU.

Episode 3 extracted its facts correctly — the Pro plan, the end of the Free plan, and the accidental-damage question all became edges. But it also did something wrong, which Step 6 dissects: the dedupe step invalidated the still-true ThinkPad edge. Hold that thought; first, the queries.

episode 'Plan upgrade': 14 nodes, 4 edges
  EDGE: Maya Chen is on the Pro plan. | valid_at=2026-11-26 09:15:00+00:00 invalid_at=None
  EDGE: Maya Chen is no longer on the Free plan. | valid_at=2026-11-26 09:15:00+00:00 invalid_at=None
  EDGE: Maya Chen asked whether the Pro plan covers accidental damage for her ThinkPad X1 Carbon. | valid_at=2026-11-26 09:15:00+00:00 invalid_at=None
  EDGE: Maya Chen uses a ThinkPad X1 Carbon instead of a MacBook Pro 14-inch | valid_at=2026-11-24 15:30:00+00:00 invalid_at=2026-11-26 09:15:00+00:00

5. Ask it what changed#

Search takes a question and a group id, and returns edges — facts — with their validity windows attached. That is the interface your agent uses: search before answering, so the answer comes from the current facts, not from a stale passage.

for query in [
    "What laptop does Maya Chen use?",
    "What plan is Maya Chen on?",
]:
    edges = await graphiti.search(query, group_ids=["maya-chen"])
    print(f"Q: {query}")
    for edge in edges:
        print(f"  - {edge.fact} (valid {edge.valid_at} -> {edge.invalid_at})")

The laptop query returns the ThinkPad edge first — then the MacBook edge with its closed window. The plan query returns the Pro plan first, with no end date. This is the output your agent would ground its answer in:

Q: What laptop does Maya Chen use?
  - Maya Chen uses a ThinkPad X1 Carbon instead of a MacBook Pro 14-inch (valid 2026-11-24 15:30:00+00:00 -> 2026-11-26 09:15:00+00:00)
  - Maya Chen uses a MacBook Pro 14-inch. (valid 2026-11-20 10:00:00+00:00 -> 2026-11-24 15:30:00+00:00)
  - Maya Chen is on the Pro plan. (valid 2026-11-26 09:15:00+00:00 -> None)
  - Maya Chen asked whether the Pro plan covers accidental damage for her ThinkPad X1 Carbon. (valid 2026-11-26 09:15:00+00:00 -> None)
  - Maya Chen is no longer on the Free plan. (valid 2026-11-26 09:15:00+00:00 -> None)

Q: What plan is Maya Chen on?
  - Maya Chen is on the Pro plan. (valid 2026-11-26 09:15:00+00:00 -> None)
  - Maya Chen is no longer on the Free plan. (valid 2026-11-26 09:15:00+00:00 -> None)
  - Maya Chen asked whether the Pro plan covers accidental damage for her ThinkPad X1 Carbon. (valid 2026-11-26 09:15:00+00:00 -> None)
  - Maya Chen uses a MacBook Pro 14-inch. (valid 2026-11-20 10:00:00+00:00 -> 2026-11-24 15:30:00+00:00)
  - Maya Chen uses a ThinkPad X1 Carbon instead of a MacBook Pro 14-inch (valid 2026-11-24 15:30:00+00:00 -> 2026-11-26 09:15:00+00:00)

Two things to notice. First, search() returns every relevant edge, including invalidated ones — it does not filter to "currently true" for you. Your agent (or your code) reads the windows: an edge with invalid_at=None is current; an edge with an invalid_at is history. Second, the ThinkPad edge's window ends on November 26 — that is the false invalidation from episode 3, and it is why the laptop query's top result is technically expired. A reader who trusts the ranking alone would conclude Maya uses no laptop at all. Always read invalid_at before you trust a result, and read Step 6 before you ship this on a small model.

A split diagram: on the left two glowing nodes connected by an edge; on the right the old edge greyed out and a new glowing node connected
AI-generated illustration for AI Frontier Post.

For a broader view of the graph, search for nodes instead of edges. The NODE_HYBRID_SEARCH_RRF recipe combines BM25 keyword search, vector similarity, and graph traversal, then reranks with the cross-encoder:

from graphiti_core.search.search_config_recipes import NODE_HYBRID_SEARCH_RRF

results = await graphiti.search_(
    "Maya Chen", config=NODE_HYBRID_SEARCH_RRF, group_ids=["maya-chen"]
)
for node in results.nodes:
    print(f"  - {node.name} [{', '.join(node.labels)}]: {node.summary}")
NODE SEARCH 'Maya Chen':
  - Maya Chen [Entity]: Maya Chen uses a MacBook Pro 14-inch.
Maya Chen uses a ThinkPad X1 Carbon instead of a MacBook Pro 14-inch
Maya Chen is on the Pro plan.
Maya Chen is no longer on the Free plan.
Maya Chen asked whether the Pro plan covers accidental damage for her ThinkPad X1 Carbon.
  - Free plan [Entity]: Maya Chen is on the Free plan.
Maya Chen is no longer on the Free plan.
  - MacBook Pro 14-inch [Entity]: Maya Chen uses a MacBook Pro 14-inch.
Maya Chen uses a ThinkPad X1 Carbon instead of a MacBook Pro 14-inch
Maya Chen is on the Pro plan.
Maya Chen asked whether the Pro plan covers accidental damage for her ThinkPad X1 Carbon.

The Maya Chen node carries all five facts in its summary — that is the node a "tell me everything about this customer" query lands on. The Free-plan node's summary even contains the fact that episode 1 failed to extract as an edge ("Maya Chen is on the Free plan"), which is a useful reminder that extraction is lossy: facts can survive in node summaries without becoming queryable edges.

6. Where the small model bites#

This tutorial ran the same three episodes four times, and the first three runs failed in three different ways. That is not a complaint about Graphiti — it is the most useful thing this tutorial can teach you, because the failure modes are exactly what you will hit if you wire a small local model into this pipeline with default settings. Each one has a fix.

Failure 1: the model returned the schema instead of the data. With structured_output_mode="json_object", the 3B model answered the dedupe prompt by echoing back the JSON Schema — {'properties': {'duplicate_facts': …}, 'type': 'object'} — and episode 2 crashed with a Pydantic ValidationError: duplicate_facts: Field required. Fix: use json_schema (the default) with a server that enforces it. Ollama applies constrained decoding, so the model physically cannot emit a schema where data belongs.

Failure 2: temperature 1 hallucinated the graph. At the default temperature, the model produced nodes for "Jordan," "Nisha's cat," "Belmont Arts Center," "road cycling," and "Riverside Park" — people and places that appear nowhere in the episodes — while missing the laptop switch and the plan upgrade entirely. No contradiction was ever detected, so nothing was invalidated. Fix: temperature=0. Extraction is a precision task; sampling noise is not creativity here.

Failure 3: dates in the episode text broke the validity window. An earlier version of the episodes mentioned a project deadline ("December 15, 2026") in the text. The model emitted a date Graphiti's parser could not read — the log shows Error parsing valid_at date, skipping — and the resulting edge was born with valid_at=2020-01-01 and an invalid_at already set: dead on arrival. Fix: keep dates out of episode text and let reference_time carry the temporal information. If your episodes must contain dates, use a model that handles them reliably, and check the first edges you ingest.

Failure 4: the dedupe step over-fired. This one survived all the fixes, and it is in the final output above. Episode 3 mentions the ThinkPad in passing ("covers accidental damage for her ThinkPad X1 Carbon"), and the dedupe step decided the ThinkPad fact contradicted something — nothing in episode 3 contradicts it — and set invalid_at=2026-11-26 09:15 on the still-true edge. The plan facts extracted fine; the laptop answer went wrong as a side effect. Fix: a more capable model for the dedupe judgments, or a human review pass over invalid_at values after ingestion. What you must not do is ignore it: an invalid_at on a fact you know is still true is the signal your model is over-firing, and it is visible in the output if you look.

Two more observations from the final run, both worth knowing before you build on this. Node search returned hallucinated nodes with empty summaries — "Gamecube," "Mustang" (whose summary claims, helpfully, "Mustang is a car model produced by Ford"), "Trigger," "dog leash." Temperature 0 did not remove node hallucination; it only removed the worst of it. And the whole three-episode run took about 22 minutes on a 1.5-CPU machine, with individual LLM calls taking 30 seconds to three and a half minutes. Budget your time accordingly — or use the OpenAI path, which runs the same pipeline in about a minute.

7. Put it in front of your agent#

The pattern for production use is two lines of discipline, repeated every turn:

# Before answering: search the memory for this user.
edges = await graphiti.search(user_message, group_ids=[user_id])

# After the turn: store what just happened.
await graphiti.add_episode(
    name=f"chat {turn_id}",
    episode_body=turn_text,
    source_description="support chat",
    reference_time=datetime.now(timezone.utc),
    source=EpisodeType.message,
    group_id=user_id,
)

Three things to carry out of this tutorial. First, one group id per user or tenant — it is the only isolation boundary Relate gives you, and it is what keeps one customer's facts out of another customer's answers. Second, episodes are cheap to append and invalidation is automatic — you do not write update logic, you write new episodes and let the dedupe step do the work, but you do review the invalid_at values it produces. Third, mind the one Relate limitation in the README: identity_properties, which pins entity identity across episodes, is supported by Neo4j and FalkorDB only — not by Relate. If your entities need stable identity beyond what the LLM resolves, that is the point at which you graduate from the embedded database to a server.

Close the client when you are done — await graphiti.close() — or the Relate connection's teardown will complain loudly on interpreter exit.

Which approach should you use?#

Four tools, four different memories. The right one depends on what changes:

ApproachWhat it storesHandles changeSetup costBest for
Plain RAGPassagesNo — passages don't expireTrivialStatic documents
mem0Memories: facts and preferencesYes — rewrites memoriesManaged service or self-hostPersonal assistants that need preferences remembered
Microsoft GraphRAGDocument graph + community summariesBatch rebuildHeavyCorpus-wide questions over static docs
GraphitiTemporal graph: facts with validity windowsYes — automatic invalidation, history keptOne Python process with RelateAgents operating on evolving facts: support, ops, assistants

The distinguishing question is whether you need the history. If "what was true then?" is a question your agent will ever be asked — a support audit, a billing dispute, a "when did the customer switch plans?" — only the temporal graph answers it from the same data. The other approaches either lose the old value or require you to keep it somewhere else.

The takeaway#

A support agent that answers from a passage store will tell you, with full confidence, that Maya Chen uses a MacBook Pro — three days after she switched to a ThinkPad. A temporal knowledge graph does not have that failure mode, because the MacBook fact carries its own expiry: true from November 20, false from November 24, still in the graph for anyone who asks what changed.

Graphiti 0.32.1 makes that graph cheap to start: one file, one Python process, no database server. The local path is real — a 3B model on a CPU extracted the facts, caught the contradiction, and invalidated the old edge exactly — but it is honest work, not magic. Set temperature 0, use json_schema output, keep dates out of episode text, limit concurrency to what your hardware can take, and read the invalid_at values your model produces. The moment those settings are right, the demo in this tutorial runs end to end, and the memory your agent answers from finally knows what changed when.

Where to go next: the Graphiti repository ships a Model Context Protocol server that exposes search and ingestion to any MCP client, and a build_communities step that clusters the graph into topic communities for broader questions. Both are documented in the README; this tutorial's graph is the starting point for either.