StateJar docs

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 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):

ConversationFull historyLast 1 + StateJarLast 3 + StateJarLast 5 + StateJar
17-turn demo, total input tokens2,1691,236 (43.0%)1,652 (23.8%)2,028 (6.5%)
40-turn demo, total input tokens9,8744,266 (56.8%)5,161 (47.7%)6,007 (39.2%)

Per turn, at N=3, the 17-turn demo:

TurnFull historyMemory contextLast 3 + StateJarSaved
1193958-205.3%
5784184-7.7%
9128376946.1%
131836511139.3%
172261872202.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:

TurnFull historyMemory contextLast 3 + StateJarSaved
1193958-205.3%
10138407148.6%
16200659552.5%
2023718020911.8%
26308619967.9%
3034519622534.8%
34390609475.9%
4046719723449.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