LLM Assistant with Graph Memory
An LLM assistant for a private online community of a few dozen people, delivered through Discord and in use since its first day. A chat model answers members and calls tools through a harness written from scratch, with no agent framework. A cheaper model works in the background: it builds long-term memory, describes images, searches the web, reads pages and picks emoji reactions. What the assistant learns about people goes into a temporal knowledge graph, and members can see and remove what it knows about them.
It’s about 13,400 lines of Python with more than 2,300 automated tests behind it, built in two and a half weeks. I designed it spec-first and built it in Claude Code sessions: the design decisions and approvals are mine, the implementation and tests were written by Claude.
1. How a reply is put together
Three ideas run through the whole design, and each one shows up in the reply path.
- The model is untrusted. It reads hostile text and may write anything. Whatever has to hold (who gets pinged, which tools run, whose data is whose) is enforced in code, not asked for in a prompt.
- A reply is never held up. Memory, images, links and tools each have a time budget and a failure path, and the reply goes on without them.
- Cheap where possible. The stronger model only writes what people read. Everything else runs on a much cheaper one, with results cached.
chat platform events
-> plain event dataclasses
-> pipeline: one bounded queue and worker per handler
statistics handlers (no model)
memory handler -> message buffer (SQLite)
-> reply path:
rebuild the conversation as text the model can follow
+ recall from the knowledge graph (2 s budget)
+ cached image descriptions and link summaries
-> tool harness: chat model <-> tools, bounded
-> code turns names into mentions and emoji, then sends
background:
memory worker: buffer -> batches -> Graphiti -> FalkorDB
vision model: describe each image once -> cache
link model: fetch and digest pages -> cache
timers: reminders, birthdays, a daily digest of what was learnedThe conversation the model reads is rebuilt for it with explicit markers: who replied to whom, time gaps, image descriptions, file names, link summaries, and notes on messages that code posted. All prompt wording lives in 23 Markdown files that are re-read on every use, so a prompt changes with no restart, and the system prompt is assembled from sections included only when they’re true, so the model is never told about a feature that’s switched off. A test fails if the markers in code and the prompt that explains them drift apart.
2. The tool-calling harness
The harness is a loop of model and tools on OpenAI-style function calling. It exists to make a short list of guarantees hold whatever the model writes:
- only tools offered in that reply can run;
- arguments are validated against a Pydantic model, and unknown fields are refused;
- every call has a timeout and its output is capped;
- a reply is bounded to 4 rounds and 8 calls, after which the model must answer with tools off;
- a failing tool becomes an error message for the model, never an exception for the member.
The loop is short enough to read whole:
while True:
final = specs is not None and (rounds >= self._limits.max_rounds or calls_left <= 0)
result = await self._llm.complete(messages, own_names=own_names, tools=specs,
tool_choice="none" if final else None)
if not result.tool_calls:
return HarnessResult(result.text, result, tuple(outcomes))
if final:
log.warning("model %s called tools after being told not to; giving up", result.model)
return HarnessResult(result.text, result, tuple(outcomes))
rounds += 1
messages.append(_assistant_message(result))
for call in result.tool_calls:
if calls_left <= 0:
outcome = ToolOutcome(call.name, False, "Error: tool call limit for this reply reached.")
else:
calls_left -= 1
outcome = await self.execute(call, by_name, ctx, on_call)
outcomes.append(outcome)
messages.append({"role": "tool", "tool_call_id": call.id, "content": outcome.output})Every call goes through one execute method, which never raises. An unknown tool, invalid arguments, a timeout and a crash all come back to the model as an Error: ... result it can correct itself from, and a crash’s internals never reach it:
if tool is None: # the model can only run what it was offered
return failed(f"there is no tool named {call.name!r}.")
try:
args = tool.args.model_validate_json(call.arguments or "{}")
except ValidationError as exc:
# ... the problems are listed for the model
return failed(f"invalid arguments ({problems})", why=_invalid(tool, errors))
# ...
try:
output = await asyncio.wait_for(tool.run(ctx, args), timeout)
except ToolError as exc:
return failed(str(exc), activity, why=_raised_at(exc))
except TimeoutError:
return failed(f"the tool took longer than {timeout:g} s and was stopped.", activity, why="timed out")There are nine tools: web search, page reading, memory search, image questions, reminders, birthdays, timezones, the current time, and a self-knowledge lookup. The last one serves documentation about the assistant’s own features on demand, so that text isn’t carried in every prompt.
Tool use is visible to members as a status line while the assistant works and a one-line record with sources under the reply. Only code writes those lines, and they’re stripped from what the model reads back, so it can’t learn to imitate them.
3. Six model roles and their fallbacks
Six model roles and an embedding model share one gateway, OpenRouter, each with its own timeout and fallback policy:
| Role | Job | Policy |
|---|---|---|
| Chat | Writes replies, calls tools | A free-tier model once with a 15 s deadline, then the paid primary twice, then a paid fallback from another model family |
| Vision | Describes images, answers questions about one | Own fallback |
| Memory | Extracts entities and facts into the graph | No fallback; a failed batch is retried later |
| Web search | Answers a query from live results | One try per model, 15 s |
| Page reading | Fetches and digests a page | One try per model, 20 s |
| Reactions | Picks emoji with a forced tool call | The free-tier model first, then the cheaper paid model |
Tool requests are routed only to providers that support every parameter sent, because some silently ignore tool_choice. Memory and embedding requests go only to providers that retain no data.
3.1. Fallback triggers
The chain moves on to its next model on an error, on an empty answer, and on an answer that writes a tool call as plain text. The third trigger comes from a failure in production. One fallback reply came out as a tool call written in the model’s own template markup. The assistant then read that message back as its own words and copied the pattern in every later reply in that channel, until the history was cleared. Replies like that are now caught in the model layer and treated as no answer, so the next model is asked:
_TOOL_MARKUP = re.compile(r"<\s*[||]\s*DSML\s*[||]|<\s*[||]\s*tool[▁_ ]calls?[a-z▁_ ]*[||]\s*>|</?tool_call>",
re.IGNORECASE)
def writes_tool_markup(text: str) -> bool:
"""True for a reply that is (or contains) a tool call written as text: never something to post."""
return bool(_TOOL_MARKUP.search(text))The chat fallback itself was chosen by a trial. Candidates were replayed against a real failure and scored on whether they claimed an action that no tool had taken. Two of them did. I picked the one that didn’t, a stronger model from a different family than the paid primary.
3.2. Images are described once
The chat model never receives an image. A vision model describes each image once, the description is cached for 30 days, and the chat model reads it inline where the image was. When a description isn’t enough, the chat model asks the vision model one specific question through a tool. In the trial that decided this, answering from the description got the same five of six questions right as sending the image directly, at about $0.0005 per image.
The assistant’s own images are described the same way, with one difference in where the description goes. It’s shown in a system note before the assistant’s turn, never inside its own text, because models imitate their earlier messages and markers in assistant text get copied. That rule came out of a bug found by rebuilding the exact request the model had received, which showed an image the assistant had posted missing from it entirely.
4. Measuring and cutting the cost per reply
The chat model was 93% of a week’s spend, and nearly all of that was input. Its requests averaged about 9,800 prompt tokens against about 140 completion tokens, because the full prompt is resent on every request and every tool round. That changed the question from which cheaper model to use into how to pay less for input tokens, or send fewer.
Breaking a production prompt down by section showed about 6,000 tokens of fixed instructions and tool schemas against about 700 for 25 messages of history, so shrinking the history window was ruled out before anyone tried it. The first change was the plainest one. Emoji reactions were each a request to the most expensive model and came to about a tenth of its cost, by an estimate from the application’s own reaction statistics, so they moved to a cheaper role of their own.
4.1. A replay trial against production code
To compare options on real traffic, a trial script replays the assistant’s real replies from one channel through the production reply path, once per configuration. It runs inside the live container without touching production: it talks to the chat platform over HTTP only, so the live assistant keeps its session, it reads a snapshot of the database copied into memory, tool side effects go to stand-in channels, and long-term memory is off. It wraps the SDK client’s request method and records, for every request, the provider that served it, prompt tokens, cached tokens, completion tokens, the gateway’s billed cost and the latency.
Its limits first: six real replies per configuration. The trial decided between options and isn’t a benchmark.
| Configuration | Prompt cached | Cost per reply | Against baseline |
|---|---|---|---|
| Chat model, default provider routing | 54% | $0.00107 | 100% |
| Chat model with a session ID (sticky routing) | 95% | $0.00115 | 108% |
| Chat model, providers sorted by price | 82% | $0.00051 | 47% |
| Smaller model, default routing | 27% | $0.00064 | 60% |
- Routing variance was the waste. Default routing already sent most requests to the cheapest provider, but an occasional request went to a premium provider at about eight times the price. One such request cost more than the other five together. Sorting providers by price is what shipped, as a validated setting sent with every chat request.
- Prompt caching didn’t pay. The gateway keeps a conversation on one provider by a hash of the first system and first user message. The assistant’s system prompt changes on every reply (recall results, the date, the channel), so each reply looked like a new conversation. An explicit session ID raised the cache hit rate to 95% and saved nothing, because the cheapest provider prices cache reads almost the same as fresh input, and the session pinned itself to that provider’s dearer endpoint.
- A smaller model didn’t pay either. With both models sorted by price it was only 8% cheaper per reply, and two of its ten replies regressed. Output is so small a share of each request that much cheaper output hardly counts.
- Trimming the prompt wasn’t worth it. The largest single section, about 1,800 tokens, came to about $0.40 a month at the new prices, so it stayed.
4.2. A free-tier model first
The gateway offers a daily allowance of free requests on some models. The chat chain now starts with one of those, with the paid models behind it. Four free models went through two checks: a scripted five-turn tool-use scenario that compares real side effects with what the model claims, and a ten-reply tone replay.
| Free model | Reminders stored | Claims of an action not taken | Notes |
|---|---|---|---|
| Nemotron 3 Ultra | 4/4 | 0 | Kept the conversation’s tone in all ten replies; chosen |
| Nemotron 3.5 Super VL | 4/4 | 0 | Flatter replies, one failure in ten |
| Gemma 4 31B | 0/4 | 0 | The free endpoint answered HTTP 429 to nearly every request |
| ERNIE 5.5 Flash (preview) | 1/4 | 3 | Claimed reminders it never set |
Putting a free model first needed changes in the one class every model role goes through:
- A circuit breaker. After an HTTP 429 or a timeout, the free model is skipped for five minutes, so a spent or saturated free tier costs one fast refusal and not one per reply.
- A hard deadline. The free model gets 15 seconds, enforced in the application. The client’s own 30-second timeout didn’t stop a 34-second request in the trial, most likely because the gateway keeps the connection active while the model works. That explanation fits what was seen and isn’t confirmed.
- Spending-limit rules. The gateway’s spending limits don’t cover free models, so while the limit is spent, only free attempts are made, and members are told the assistant is out of credit only when those fail too.
- A latent bug fixed. Code inherited from a free-models-only period treated a spent free allowance as being out of requests, and would have silenced the assistant until the allowance reset even with paid models available. That now applies only when every model in the chain is free.
FREE_REST_SECONDS = 300
FREE_TIMEOUT_SECONDS = 15.0
# ... inside the model-layer class:
def _models_now(self) -> list[str]:
"""The models to try for this request. While the key's spending limit is spent only free ones, which it
doesn't cover; a resting free model is skipped while a paid one is left to try."""
attempts = list(self._attempts)
if self._free_resting and not self.free_only:
attempts = [m for m in attempts if not is_free(m)]
if self.budget_spent:
attempts = [m for m in attempts if is_free(m)]
return attemptsThe cost of the free tier is latency. The free model took 2.9 to 34 seconds per request in the trial, most between 3 and 11, against 0.9 to 2.1 for the paid primary. The deadline caps the worst case at roughly 17 seconds, and I accepted that.
Daily spend roughly halved in the first week after reactions moved, though traffic varies too, so not all of that is the change. The savings from price routing and the free tier are estimates from trial prices and haven’t been measured on a full day of production traffic yet. Spending limits themselves are set at the gateway, and memory pauses when the day’s spend passes 80% of the limit, so replies keep the rest.
5. Memory as a temporal knowledge graph
The assistant’s memory is a knowledge graph: people and things are nodes, and a fact is a sentence on an edge between two nodes, with an embedding and a link to the batch of messages it came from. It’s built by Graphiti, an open-source library for building knowledge graphs from text with an LLM, on FalkorDB, a graph database queried in Cypher.
It replaced a first version that ran in production for two weeks and learned 634 facts about 20 people: batched extraction of single-sentence facts, rule checks in code, a reconciliation step, and recall from SQLite full-text search. That version’s weakness was lexical search. A question about who owes money didn’t find a fact worded as a debt. I weighed five designs for its replacement: vectors in SQLite, Postgres with pgvector and a graph extension, Mem0, a self-built pipeline on FalkorDB, and Graphiti on FalkorDB. Graphiti needed the least project code and ran on the cheap memory model for fractions of a cent per batch. Its price is that what gets stored is decided by its extraction prompts, where the first version decided it with checks in code.
Graphiti does the extraction, the entity resolution, the end-dating of contradicted facts and the search. The project’s own work is everything around it.
- Identity in code. Authors, mentions and recognised names are rewritten to stable IDs before the memory model and the graph see them, and back to current names on the way out, so a rename changes nothing. (The chat model is a different case: it only ever sees names, as section 7 describes.) Five identity schemes were trialled against a rename and two similar names. This one kept one node per member, kept the similar names apart, and made old facts follow the rename.
- Batches, not single messages. Read one message at a time, the pipeline kept 3 or 4 of the 7 things worth keeping in a test chat, on every model tried. Read as two batches on the cheap model, it kept 7 and 6. A larger model didn’t fix the per-message numbers, at more than twice the price per message.
- Temporal facts. A fact that stops being true is kept and given an end date, not overwritten.
- Hybrid retrieval. Vector similarity plus BM25 (a keyword-relevance score) over full text, fused with reciprocal rank fusion (which merges the two result lists by rank), so a question can find a fact it shares no word with. Recall for a reply is one embedding request with a 2-second limit.
- Forgetting. A deleted or edited message has what was learned from it forgotten or re-read. Members remove facts about themselves, and a removal sticks.
- Privacy on disk. Raw text is blanked in the graph an hour after it’s read, and the database file is rewritten so the text leaves the disk. The database’s query logs and snapshots are switched off.
- One integration module. A single module talks to Graphiti and FalkorDB, and a test enforces that. The rest of the application sees a small interface with a stand-in for tests.
One problem came from the shape of the graph. Graphiti stores a fact as a link between two entities, so facts about one person alone, such as an allergy or a birthday, were being dropped. The fix was in the extraction instructions, and the first attempt at it made the model keep jokes.
The graph started empty when it went live on 30 November 2026. A one-off migration to carry a hand-picked 172 of the old 634 facts across is built, tested and rehearsed, and hasn’t been run yet.
6. Evaluating memory
Memory is measured by an evaluation set that drives the real pipeline, against a pass bar fixed before the results were in.
The set is 27 scripted conversations with 39 expected facts, 28 questions and 44 things that must not be stored, 6 of which count as hard failures. It covers group chat, private messages, jokes, a password, a fact that changes, a repaid debt, renames, similar names, a non-English chat, edited and deleted messages, and two adversarial cases: an instruction aimed at the extractor, and one person imitating another’s line. The runner drives the real worker, prompts and settings into a scratch graph on the real database, then asks the chat model the questions and scores the answers. A trace mode reports, in counts only, how the model answered each extraction step, which is how an empty batch is told apart from a truncated answer or a silently dropped fact.
Its limits first: the set is small and invented, nearly all in English, and run with tools off.
The bar is zero hard failures, at most two facts missed and at most two questions unanswered, three runs in a row. With the current instructions and the cheap memory model, the three full runs were:
| Run | Facts | Wrongly stored | Hard failures | Questions |
|---|---|---|---|---|
| 1 | 37/39 | 0 | 0 | 27/28 |
| 2 | 37/39 | 0 | 0 | 27/28 |
| 3 | 33/39 | 0 | 0 | 24/28 |
Two runs in three passed, so the bar wasn’t met, and I shipped the graph anyway. That was a deliberate trade: the technique was the point of the project, and the bar gets looked at again if memory turns out noticeably worse in use. It stays the measure for any change to the extraction prompt, the memory model or recall. A full run costs three to four cents.
One more undisturbed run on launch day scored 37 of 39 facts and 28 of 28 questions. The trace mode showed something the scores didn’t: the answer to the fact-extraction step ran into its length limit in 10 of 46 requests, and each was thrown away and asked again. Every one recovered, but it’s the likeliest cause of the batch lost in the failing run.
The first memory taught the lesson that makes this set worth having. In its first ten hours live it kept nothing from about 200 messages, though it passed every test, because the extraction prompt was too strict for real small talk. It was loosened to keep what a friend would remember, with new cases added to the set.
7. Treating the model as untrusted
The rules that protect members are implemented in code on both sides of the model, in what it’s shown and in what’s done with what it writes.
The chat model never sees a real user ID. People, emojis and channels reach it by name, and code supplies the IDs afterwards. The rule also fixed a bug: when it was shown emoji IDs, the model wrote emojis with IDs copied from other emojis.
Mentions are resolved by code from names the model writes, and only when a name belongs to exactly one member. The table of usable names is built by dropping every name that more than one person has:
unique = [(form, next(iter(ids))) for form, ids in owners.items() if len(ids) == 1]
return sorted(unique, key=lambda pair: -len(pair[0]))Mass pings and role pings are impossible whatever the model writes, because code never produces them.
Each message is flattened to one line before memory reads it, with its author written by code, so a message can’t fake a second speaker:
def flatten(text: str) -> str:
"""Every run of whitespace, line breaks included, as one space, so a message cannot start a second line
that reads as another speaker."""
return " ".join(text.split())Text from a member that imitates the system’s own markers is defused before the model reads it.
Web pages are hostile input too. A page is fetched by a separate model in a request that contains the address and nothing else, through the Responses API, chosen because it returns the fetch as a structured item that code can verify. The assistant opens only addresses that were given to it and are in view, never one it composed. An address also has to read as a real host name:
def _real_name(host: str) -> bool:
"""Whether a host reads as a name, not as an address a resolver would turn into an IP (`127.1`,
`0x7f.0.0.1`, `1.0x7f000001`) or a private name (`localhost.`): every dot-separated label is
non-empty and starts and ends with a letter or digit, and the last label (the TLD) is letters only,
or punycode (`xn--p1ai`). Digits in earlier labels are fine (`163.com`)."""
labels = host.split(".")
if not all(label and label[0].isalnum() and label[-1].isalnum() for label in labels):
return False
return labels[-1].isalpha() or labels[-1].startswith("xn--")A page becomes a stored digest keyed by a hash of its address, and a link taken from a page is kept only if the page’s text really holds it.
8. Privacy controls, tests and deployment
Members control what’s remembered about them. A slash command shows a member, privately, what the assistant remembers about them, when each thing was learned and where, and lets them remove one fact or all of them. Nobody can add or edit a memory by hand, admins included. Every evening the assistant posts a digest of what it learned that day in the shared channels, so members can see what it picks up. Nothing learned in private messages ever appears there.
Raw message text is kept only until it’s read, plus an hour, and never more than 72 hours. Logs carry IDs and counts, never message or fact text.
The tests, more than 2,300 of them, are concentrated on the harness, every tool, the model layer, memory, the event pipeline and the privacy rules, and about three dozen run against a real graph database. A new test is checked by breaking the rule it guards and seeing it fail. The larger features were preceded by 17 written design specs, and a decisions log records each product and design call with its date and reason.
It runs as two containers on a Linux VPS, the assistant and the graph database, deployed by a script over rsync and SSH. Both run as non-root with a read-only root filesystem, no Linux capabilities, no privilege escalation and no published ports. There’s no CI. Each deploy hands the new commits to the model, which posts a short release note for members, so commit messages are written with that audience in mind and checked by a hook for secrets and identifiers.