Skip to main content

statejar (Python)

The Python client for the hosted StateJar memory API.

StateJar keeps conversational memory as structured, versioned state on the StateJar service. This package sends a message to the service, gets back the fields a question needs as memory_context, and hands that to your own model call. It never calls a language model and never sees your provider key.

What this package includes — and what it does not

Included Not included
StateJar, an HTTP client for /memory/ingest and /memory/query Any memory engine: extraction, canonicalization, handles and versioning all run on the StateJar service
Typed exceptions (StateJarError, StateJarAuthError, StateJarConnectionError) Any LLM client or provider integration
py.typed type information The StateJar backend, frontend or database code

The only runtime dependency is httpx. Until 0.4.1 this distribution also carried an embedded engine (statejar.LocalMemory); it was removed in 0.5.0 — see CHANGELOG.md.

Licence

Free to use with the StateJar service, under the StateJar SDK License in the LICENSE file included with this package. It is a proprietary licence, not an open-source one: you may install and use the unmodified package to access the service and redistribute unmodified copies; you may not distribute modified versions, use the package to build a competing service, or reverse engineer the service. Use of the service itself is governed by the terms at https://statejar.com/terms.

Install

pip install statejar

Requires Python 3.10+. No --pre and no version pin are needed. The one dependency, httpx, is capped below 1.0, so --pre (which applies to every dependency) cannot pull an httpx pre-release either.

Sign in from the terminal

pip install statejar        # or: pip install "statejar[keyring]" for the OS keychain
statejar login              # opens statejar.com/device; approve once
statejar whoami             # which account the stored key belongs to
statejar logout             # forget the key on this machine

statejar login works like gh auth login: the terminal shows a code, you approve it in the signed-in browser (two-factor included), and a one-year developer key is stored locally — in the OS keychain when keyring is installed, else in ~/.config/statejar/credentials.json with mode 0600 (%APPDATA%\statejar on Windows). Your password never passes through the terminal and the key is never shown in the browser.

StateJar() with no api_key then uses STATEJAR_API_KEY when it is set (a server, CI), else the stored key. STATEJAR_BASE_URL points the client at staging or a self-hosted server. The key reaches the memory API only; revoke it on the API Keys page.

Memory from the terminal

statejar init --scope my-project       # sign in if needed; my-project becomes the default scope
statejar add "I'm Kavya, I live in Bengaluru and my laptop budget is 80000 rupees."
statejar search "what is my budget?"   # only the fields the question needs, its handle, the audit id
statejar list                          # every fact in the scope's current state
statejar forget budget                 # a new version without it; history keeps it
statejar export --out memory.json      # every version, oldest first, with handles (mode 0600)
statejar status                        # the key's account, the scope, its newest handle

A scope is one session tag in your account (a project, an agent, a chat); the integrations each use their own (claude-code, codex, opencode, hermes, openclaw), and --scope reads any of them. Without --scope, the commands use STATEJAR_SCOPE, then the scope init saved, then default. add says what each fact became (stored, held until said again, or declined with its reason); --json on add, search, list and forget prints the API's answer as it came. Nothing prints the key.

Status and limits

  • Tested: the client's unit tests (HTTP mocked with respx), clean installs of the wheel on CPython 3.10 and 3.12 / Linux (with and without --pre), and end-to-end runs of the installed 0.7.0 wheel — the client and every statejar command — against a StateJar server run locally (rules tier, SQLite). The hosted API (api.statejar.com) is not exercised by this package's automated tests.
  • What the service extracts is the service's behaviour, not this client's. Extraction can misread a sentence. The service's measured figures, with their set sizes and limits, are on https://statejar.com/about; no accuracy figure is claimed in this package.

Quickstart

Get a key on the API Keys page of the console (keys look like sj_live_…). Then:

from statejar import StateJar

sj = StateJar(api_key="sj_live_...", session_tag="my-app")
turn = sj.turn("My name is Meera Nair and I prefer email")

turn["memory_context"]          # prompt-ready system message for YOUR model

memory_context goes into your own LLM call as the system message, with the user's text as the user message. With OpenAI, for example:

from openai import OpenAI

client = OpenAI()               # reads OPENAI_API_KEY — never sent to StateJar
reply = client.chat.completions.create(
    model="gpt-4o-mini",        # the example defaults to this via OPENAI_MODEL
    messages=[
        {"role": "system", "content": turn["memory_context"]},
        {"role": "user",   "content": "Book my delivery"},
    ],
)
print(reply.choices[0].message.content)

That is the whole integration.

Save tokens

Do not resend the whole chat on every model call: send the last few messages plus memory_context as the system message.

# 0.8.0: ingest + recall, then the system message (yours, then the memory) and the last 2 messages
messages = sj.build_messages(history, question, last_n=2, system="You are a helpful assistant.")
reply = my_llm(messages)                         # instead of sending the whole `history`
history += [{"role": "user", "content": question}, {"role": "assistant", "content": reply}]

compose_messages(history, question, memory_context, last_n=2) does the same without the network call.

Older turns reach the model only as the facts StateJar stored from them. The memory block is capped at 200 tokens, holds the facts the current message needs, and is empty ("") for small talk, so it adds nothing then. Measured on 3 Nov 2026 with tiktoken cl100k_base (user turns only, no replies): the 17-turn demo sent 2,169 tokens in total with the full history against 1,652 with the last 3 turns plus StateJar (23.8% fewer, every turn cheaper from turn 9); the 40-turn demo 9,874 against 5,161 (47.7% fewer, from turn 16). The first turns of a chat still cost more. POST /memory/token-compare counts your own chat the same way. The method and per-turn tables: https://statejar.com/docs/save-tokens.html

Statements without questions

For a message that needs no answer, skip retrieval entirely:

turn = sj.turn("Budget is under 25000 and the deadline is 20 September", ask=False)
# one request made; turn["memory_context"] is None

Working with the turn payload

turn["handle"]           # the state handle this turn produced
turn["declined"]         # values extraction refused, with reasons (e.g. a
                         # quantity offered to a money field) — never guessed
turn["subset_keys"]      # exactly which fields were disclosed, e.g. ["facts.name"]
turn["retrieval_mode"]   # field_match | intent_map | full_state | …
turn["audit_id"]         # the disclosure is audited; replay it from the console

Lower-level access

stored = sj.ingest("I'm from Pune")                # full ingest response
got = sj.recall("Where am I from?", audit=False)   # subset + metadata;
                                                   # audit=True pins the
                                                   # disclosure to the trail

recall(audit=True) writes the disclosure to the server-side audit trail, so you can prove later what was sent — the same trail the console's Audit page shows. turn() audits by default; turn(text, audit=False) skips it.

API

Method Endpoint Returns
ingest(text, *, review=False, wait=True, wait_timeout=600, poll_interval=2, background=False) POST /memory/ingest handle, parent_handle, stored, state, conflicts, extraction_*, confirmations, and extraction from an extraction-v3 server; the job (job_id, status, status_url) with wait=False on a long message or with background=True
ingest_job(job_id) GET /memory/ingest/jobs/{job_id} status (queued, running, done, failed) and, when done, result
wait_for_job(job_id, *, wait_timeout=600, poll_interval=2) the same, polled the job's result: the body a direct ingest returns
confirm(confirmation_id, accept=True) POST /memory/confirm status (confirmed or rejected), stored, and the new version's handle when accepted
recall(query, audit=False) POST /memory/query memory_context, subset, handle_used, metadata, audit_id
turn(text, ask=True, audit=True, background=False) both, ingest first (recall first with background=True) all of the above, plus declined, subset_keys, retrieval_mode, extraction; with background=True, ingest_job and pending_ingest

A long message (over 3,000 characters on an extraction-v3 server) is read in the background: ingest waits for it and returns the same body a short message gets, or raises StateJarJobTimeout (its job_id names the job, which keeps running) after wait_timeout seconds.

handle and handle_used are None while a session has no stored facts. Auth is sent as X-API-Key; use one session_tag per conversation thread. The client holds a connection pool — close it, or use it as a context manager:

with StateJar(api_key="sj_live_...", base_url="http://localhost:8000/api/v1") as sj:
    sj.turn("I prefer email")

How it works

Every turn is two API calls, in this order, then yours:

  1. Ingest — POST /memory/ingest commits the message's facts: extracted, canonicalized, sealed into SHA-256 content-addressed state.
  2. Recall — POST /memory/query returns the stored fields the question needs, formatted as memory_context. While a session's state is small (under the service's threshold) the whole state is returned instead — metadata.retrieval_mode says which.
  3. Your LLM call — memory_context as the system message. Your provider, your key, your code; StateJar is not in it.

Two guarantees live in that ordering:

  • BYOK — your key stays yours. The provider key is used inside your process, in step 3, and is never sent to StateJar. No transcript is stored either: the server sees one message at a time and keeps the facts it extracts, not the message.
  • Ingest commits before recall runs, so the context you send already contains the turn that asked the question. Reversing the order retrieves state from before that message existed — and the failure is invisible, because you still get a fluent answer, just one built on stale memory. turn() gets the order right by construction; call ingest() and recall() yourself only when you have a reason to.

Reply first, update memory right after

On a server that reads messages with extraction v3 (a cloud model provider proposes facts first, and StateJar's own rules and checks decide what is stored), reading a message takes seconds or more, and in the order above every reply waits for it. turn(text, background=True) turns the order around:

  1. Recall for text — the server first waits, a few seconds at most, for the session's previous message to be stored.
  2. Ingest in the background — the message is sent with "async": true and read after this returns; ingest_job names the job.
  3. Your LLM call at once. Your model reads text itself, so a fact stated in it is used in this reply; the next turn's recall finds it stored.

When the previous message was still being read after the wait, the context comes from the version before it and says so: pending_ingest is True. A session's messages are always stored in the order they were sent.

Confirm before store

When a message carries a value the server is unsure of — "i have 5000 rs" (money with no stated purpose), "under 50000" (no currency), "my slary was 80000rs" (a concept that exists only because a typo was corrected) — nothing is stored for it. A server on the rules tier returns a question at once. A server running extraction v3 (the hosted service) asks no question unless you pass review=True: a fact it is unsure of is held until it is said again (extraction["pending"]) or declined with its reason, and review=True turns the held ones into questions. A rules-tier server accepts review and ignores it. The answer below is the rules tier's:

r = jar.ingest("go goa i have 5000rs ruppes", review=True)
r["confirmations"]
# [{"id": 12, "path": "constraints.budget.max",
#   "value": {"value": 5000, "currency": "INR"},
#   "reason": "funds_on_hand", "question": "Is ₹5,000 your budget?"}]
jar.confirm(12)          # yes: a new version with the budget; jar.confirm(12, accept=False) discards it

A pending value is never part of a handle and never sent to a model.

Errors

Everything raised is a StateJarError:

from statejar import (StateJar, StateJarError,
                      StateJarAuthError, StateJarConnectionError)

try:
    turn = sj.turn("hi")
except StateJarAuthError:        # HTTP 401 — bad/revoked key
    ...
except StateJarConnectionError:  # unreachable host or timeout — nothing was
    ...                          # stored, so retrying ingest is safe
except StateJarError as e:       # anything else; e.status_code, e.body
    print(e.status_code, e.body)  # (decoded JSON or text) and e.response_text

StateJarJobTimeout (a StateJarError) is raised when a long message is still being read after wait_timeout; e.job_id names the job, which keeps running — read it later with ingest_job(). A background reading that failed raises StateJarError with the job as e.body.

A missing api_key raises at construction as a StateJarAuthError that is also a ValueError, so code written against either earlier client still catches it.

Pointing at a local instance

sj = StateJar(api_key="sj_live_...", base_url="http://localhost:8000/api/v1")

Development

cd sdk && pip install -e ".[dev]" && pytest     # ".[test]" is the same set

The tests mock HTTP with respx at the httpx client seam — no network, no server needed.

Copyright (c) 2026 StateJar. All rights reserved. Rights not granted by the licence are reserved; see section 3 of LICENSE.

Metadata

Release files for statejar 0.8.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for statejar 0.8.0
File Size Uploaded Provenance Actions
statejar-0.8.0.tar.gz 39.3 kB With provenance Details for statejar-0.8.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for statejar 0.8.0
File Interpreter ABI Platform Actions
statejar-0.8.0-py3-none-any.whl Python 3 none any Details for statejar-0.8.0-py3-none-any.whl

Total release size: 69.2 kB

Release files / statejar-0.8.0.tar.gz

Download URL statejar-0.8.0.tar.gz
Size 39.3 kB
Tags Source
SHA-256 checksum
How to use checksums
9fe7e7feb4ab988a26981dcde2d2950519a96abf7c693f2c530ea9113f8d12da
BLAKE2b-256 checksum
How to use checksums
b7374982939a75f2b02ec92790d7ae2bf42d4b83282302f8f6bb1053b05f7a2c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

Release files / statejar-0.8.0-py3-none-any.whl

Download URL statejar-0.8.0-py3-none-any.whl
Size 29.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
186c1b61d87f4b2e21e77f5f2c20dd546f7006e33fc1f090d3bcae184eb88fef
BLAKE2b-256 checksum
How to use checksums
3261e091413794aed47f460dc82969b6a48a10382c41ef1c6698d6f3c98807ec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

Security for statejar 0.8.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for statejar-0.8.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.8.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page