Save tokens
Send the last few turns plus StateJar's memory_context as the system message, not the whole history. How to do it in Python and Node, how to count the tokens it saves, and the measured result on the 17- and 40-turn demos, including the first turns, where it still costs more.
The short answer
- The pattern. Keep your chat as you do now. For each model call, send StateJar's
memory_contextas the system message and only the last N messages, instead of the whole history. StateJar holds the facts, so older turns no longer have to travel with every request. - What StateJar adds per turn. Since 3 November 2026 the memory block is capped at 200 tokens (the server's context budget tokens setting), carries the facts the current message needs, and is left out entirely when nothing stored is relevant: small talk such as "hey, how are you?" adds 0 tokens. In the demos below it cost 37 to 198 tokens on the turns that sent one, and nothing on 2 of the 57 turns.
- The measured result. With the last 3 turns plus StateJar the 17-turn demo sent 1,652 tokens in total against 2,169 for the full history (23.8% fewer), cheaper at every turn from turn 9 on; the 40-turn demo sent 5,161 against 9,874 (47.7% fewer), from turn 16 on. The first turns of a chat still cost more than their short history.
- Before the cap (31 October 2026, the same demos) the block cost 110 to 287 tokens and the 17-turn demo sent more than the full history at every turn: 4,165 tokens with N=3 (-92.0%), and the 40-turn demo 10,401 (-5.3%).
- A question about a small memory still gets all of it, up to the cap, because narrowing questions by their words lost answers on memory-QA; a statement gets only the fields it bears on. Measure your own chat: the call in the code below returns both numbers.
- What is counted. Input tokens, with tiktoken
cl100k_base. Not counted: your own system prompt, the model's reply, or the few tokens a provider's chat format adds per message. It estimates input tokens; it is not an invoice.
The code
Python, with the statejar package from the Python SDK page:
import os
import httpx
from statejar import StateJar
sj = StateJar(session_tag="user-42")
# Your app keeps the chat in whatever message format your model provider uses.
history = [
{"role": "user", "content": "I'm Meera from Pune and I prefer email."},
{"role": "assistant", "content": "Nice to meet you, Meera. I'll keep to email."},
{"role": "user", "content": "My budget is ₹3,500."},
{"role": "assistant", "content": "Noted: a budget of ₹3,500."},
{"role": "user", "content": "I'm travelling to Goa in December."},
{"role": "assistant", "content": "Goa in December, got it."},
]
for m in history:
if m["role"] == "user":
sj.ingest(m["content"]) # StateJar keeps the facts, not the transcript
question = "What is my budget?"
history.append({"role": "user", "content": question})
N = 3 # how many of the latest messages to still send
memory = sj.recall(question, audit=True) # only the fields this question needs
# What goes to YOUR model: StateJar's context as the system message + the last N messages,
# instead of the whole history. The context is "" when nothing stored is relevant (small talk):
# then there is no system message at all. (statejar 0.8.0 and later does this in one call:
# messages = sj.build_messages(history[:-1], question, last_n=N - 1).)
system = [{"role": "system", "content": memory["memory_context"]}] if memory["memory_context"] else []
messages = [*system, *history[-N:]]
# reply = client.chat.completions.create(model="...", messages=messages) # your provider here
# Count it: input tokens (tiktoken cl100k_base) of the full history vs what you send now.
base = os.environ.get("STATEJAR_BASE_URL", "https://api.statejar.com/api/v1").rstrip("/")
body = {"messages": history, "memory_context": memory["memory_context"], "window": N}
t = httpx.post(f"{base}/memory/token-compare", json=body, headers={"X-API-Key": sj.api_key}).json()
print(f"full history: {t['full_history_tokens']} tokens")
print(f"last {N} + StateJar: {t['tokens_with_statejar']} tokens ({t['recent_tokens']} recent + {t['context_tokens']} memory)")
print(f"saved: {t['saved_pct']}% (negative while the chat is short)")
Node, with the statejar package from the Node SDK page:
import { StateJarClient } from "statejar";
const baseUrl = process.env.STATEJAR_BASE_URL ?? "https://api.statejar.com/api/v1";
const sj = new StateJarClient({ baseUrl }); // STATEJAR_API_KEY is read automatically in Node
const tag = "user-42";
// Your app keeps the chat in whatever message format your model provider uses.
const history = [
{ role: "user", content: "I'm Meera from Pune and I prefer email." },
{ role: "assistant", content: "Nice to meet you, Meera. I'll keep to email." },
{ role: "user", content: "My budget is ₹3,500." },
{ role: "assistant", content: "Noted: a budget of ₹3,500." },
{ role: "user", content: "I'm travelling to Goa in December." },
{ role: "assistant", content: "Goa in December, got it." },
];
for (const m of history) {
if (m.role === "user") await sj.ingest({ sessionTag: tag, text: m.content }); // facts, not the transcript
}
const question = "What is my budget?";
history.push({ role: "user", content: question });
const N = 3; // how many of the latest messages to still send
const memory = await sj.recall({ sessionTag: tag, query: question, audit: true });
// What goes to YOUR model: StateJar's context as the system message + the last N messages,
// instead of the whole history. The context is "" when nothing stored is relevant (small talk):
// then there is no system message at all. (statejar 0.4.0 and later does this in one call:
// sj.buildMessages({ sessionTag: tag, history: history.slice(0, -1), userMessage: question, lastN: N - 1 }).)
const system = memory.memory_context ? [{ role: "system", content: memory.memory_context }] : [];
const messages = [...system, ...history.slice(-N)];
// const reply = await yourModel(messages); // your provider here
// Count it: input tokens (tiktoken cl100k_base) of the full history vs what you send now.
const res = await fetch(`${baseUrl}/memory/token-compare`, {
method: "POST",
headers: { "X-API-Key": process.env.STATEJAR_API_KEY, "Content-Type": "application/json" },
body: JSON.stringify({ messages: history, memory_context: memory.memory_context, window: N }),
});
const t = await res.json();
console.log(`full history: ${t.full_history_tokens} tokens`);
console.log(`last ${N} + StateJar: ${t.tokens_with_statejar} tokens (${t.recent_tokens} recent + ${t.context_tokens} memory)`);
console.log(`saved: ${t.saved_pct}% (negative while the chat is short)`);
Both run against a real account and print three lines: the full history in tokens, what you now send (recent turns plus memory), and the saving. POST /memory/token-compare does the counting on the server with the same tokenizer as the benchmark, reads and writes no memory, calls no model and stores nothing you send it. The Playground shows the same numbers live, turn by turn, as you chat.
Choose N from your own chats. A larger N keeps more of the conversation's wording but spends more tokens.
Measured on the demos
Run on 3 November 2026 by StateJar's offline window benchmark (the same pipeline, demo conversations and tokenizer as the token benchmark; the run before the cap is kept beside it). No model is called, so the conversations hold the user's turns only: each turn is rendered as the line user: followed by its text, with no assistant replies and no system prompt on either side. "Last N + StateJar" is the memory context for that turn (as POST /memory/query returns it, the update notice included) plus the last N user turns, the current one included. Savings are not clamped: a negative figure means StateJar sent more.
Total input tokens over the whole conversation (every turn's request added up):
| Conversation | Full history | Last 1 + StateJar | Last 3 + StateJar | Last 5 + StateJar |
|---|---|---|---|---|
| 17-turn demo, total input tokens | 2,169 | 1,236 (43.0%) | 1,652 (23.8%) | 2,028 (6.5%) |
| 40-turn demo, total input tokens | 9,874 | 4,266 (56.8%) | 5,161 (47.7%) | 6,007 (39.2%) |
Per turn, at N=3, the 17-turn demo:
| Turn | Full history | Memory context | Last 3 + StateJar | Saved |
|---|---|---|---|---|
| 1 | 19 | 39 | 58 | -205.3% |
| 5 | 78 | 41 | 84 | -7.7% |
| 9 | 128 | 37 | 69 | 46.1% |
| 13 | 183 | 65 | 111 | 39.3% |
| 17 | 226 | 187 | 220 | 2.7% |
Turn 17 is the demo's one question, so it gets the whole memory up to the cap (187 tokens); every other turn is a statement and gets only the fields it names. At N=3 the 40-turn demo:
| Turn | Full history | Memory context | Last 3 + StateJar | Saved |
|---|---|---|---|---|
| 1 | 19 | 39 | 58 | -205.3% |
| 10 | 138 | 40 | 71 | 48.6% |
| 16 | 200 | 65 | 95 | 52.5% |
| 20 | 237 | 180 | 209 | 11.8% |
| 26 | 308 | 61 | 99 | 67.9% |
| 30 | 345 | 196 | 225 | 34.8% |
| 34 | 390 | 60 | 94 | 75.9% |
| 40 | 467 | 197 | 234 | 49.9% |
Every turn is cheaper than the full history from turn 16 of the 40-turn demo at N=3 (turn 10 at N=1, 18 at N=5); on the 17-turn demo from turn 9 at N=3 and 5 at N=1, while at N=5 its last turn still costs more. The large figures (about 200 tokens) are the question turns, which get the whole small memory up to the cap; the small ones are statements.
What this does not show: how the saving behaves with assistant replies, which these runs leave out, or with your own prompts; for that, count your own chat. These conversations are terse, form-like logs (12 to 13 tokens a turn on average), a short-message extreme. A percentage means nothing without its baseline: here it is the full history of the same turns.
Questions
Why is the saving negative at first? The memory block costs more than the first few messages it replaces. A saving needs a history longer than the block plus your N turns; with the cap that comes within the first few turns.
Does this lose context? The last N turns still go to the model word for word. Older turns reach it only as the facts StateJar stored from them, so something said once and never stored as a fact is gone from the request. Raise N if your chats lean on exact wording.
Do I still need audit=True? It writes the disclosure to your audit log, so you can show later what the model was sent. It does not change what is sent.
Where do the numbers in the Playground come from? From the same call, with the chat you see on screen, including the assistant's replies.
This page as Markdown: /docs/save-tokens.md