Skip to main content Switch to mobile version reasoning-ledger 2.3.0 Python SDK for the Reasoning Ledger, an append-only audit trail for AI agent reasoning.
pip install reasoning-ledger==2.3.0 Copy PIP instructions
Python SDK for the Reasoning Ledger — an append-only audit trail for AI agent reasoning.
pip install reasoning-ledger Requires Python 3.12+. Dependencies: pydantic>=2, httpx>=0.27.
Records use schema 0.5; the server accepts no older schema on write.
Planning keeps its 0.4 fields (goal, steps, contingencies) and gains revision_of, the earlier plan it revises. Thinking.prompt and Thinking.inputs are optional.
New behaviors: Escalating (the agent hands a decision to a person), Delegating (it hands a goal to another agent) and Memorizing (it writes memory, rules, skills or settings that outlive the cycle).
outcome is required on Acting, Attesting, Escalating, Delegating and Memorizing, as on ToolCalling, and may be "cancelled". submit_attesting does not fill it in.
Acting: dry_run is gone, parameters is optional, and action_type is a namespaced . , e.g. answer.final or git.commit.
Attesting: evidence_refs is gone (use sources). disposition may be "cancel", which needs outcome: "cancelled", or "no_response", which needs outcome: "timeout". channel and seen_completeness are new.
ToolCalling.tool_meta needs a name; description is optional; effect is new.
Gone: parent_record_id, model_invocation.model_version, Observing.external_trigger_id. verdict.decided_by takes one of "human", "model", "rule", "policy", "classifier", "config", "consensus".
New on every record: error_type, written_by, on_behalf_of_agent_id, classification. New in model_invocation: invocation_kind, replay_of, cache_read_tokens, cache_creation_tokens, request_id; provider and model_name may be None on a replay or a simulation.
endpoint is required — in LedgerClientConfig, RegisterAgentOpts and ResolveAgentOpts. The environment option and the ENDPOINTS constant are gone (their built-in hosts never resolved).
Records use schema 0.4: every record needs executor and record_phase; ToolCalling.success is replaced by outcome.
Prompts, payloads and internal reasoning are content references. Pass raw values and the SDK uploads them (see Content); SIZE_LIMITS no longer caps them.
New: submit_attesting, put_content, get_content. agent_wallet_address may be None.
Every call needs the base URL of your Reasoning Ledger server as endpoint. There is no default.
Agent registration is idempotent on (owner, name) — calling it again with the same name returns the existing agent.
import os from reasoning_ledger import LedgerClient, RegisterAgentOpts ENDPOINT = os.environ["LEDGER_ENDPOINT"] # e.g. "https://ledger.example.com" reg = LedgerClient.register_agent(RegisterAgentOpts( api_key=os.environ["STAIRAI_API_KEY"], endpoint=ENDPOINT, name="my-agent", )) agent_id = reg["agent_id"] # Store agent_id — you'll need it every time you construct LedgerClient. If you already have an agent_id (e.g. stored in config), skip registration. To look up an agent ID by name at startup:
from reasoning_ledger import LedgerClient, ResolveAgentOpts agent_id = LedgerClient.resolve_agent_id(ResolveAgentOpts( api_key=os.environ["STAIRAI_API_KEY"], endpoint=ENDPOINT, name="my-agent", )) 2. Create a client
3. Open a session and submit records
A Session pins a session_id so you don't have to pass it on every record. It is purely local sugar — there is no server-side session lifecycle.
Every record states executor ("ai", "det" or "human": who performed the step) and record_phase ("pre_execution", "concurrent" or "post_execution": when the record was written relative to the step). The SDK does not default them.
session = client.new_session() # auto-generates a session_id # Observing — the trigger that woke your agent obs = session.submit({ "behavior": "Observing", "executor": "det", "record_phase": "post_execution", "trigger_source": "sportradar", "trigger_type": "signal_trigger", "trigger_description": "Match update: Spain vs Morocco, minute 47", "trigger_payload_summary": "Spain xG 0.41, possession 62%, shots 8-2", }) # ToolCalling — payloads may be raw values; the SDK uploads them (see Content) tool = session.submit({ "behavior": "ToolCalling", "executor": "det", "record_phase": "post_execution", "upstream_record_id": [obs["record_id"]], "tool_meta": {"name": "polymarket_api", "tool_type": "http"}, "description": "Fetch current Spain win odds", "input_payload": {"market": "esp_mar"}, "output_payload": {"spain_win": 0.73}, "outcome": "success", }) # Thinking — analysis and decision session.submit({ "behavior": "Thinking", "executor": "ai", "record_phase": "post_execution", "upstream_record_id": [tool["record_id"]], "prompt": "Given xG 0.41 and odds 0.73, should I adjust the position?", "inputs": [{"input_record_id": tool["record_id"], "input_payload": "odds 0.73"}], "output_payload": "Hold: confidence 0.81", }) # Acting — the commitment that closes the cycle session.submit({ "behavior": "Acting", "executor": "det", "record_phase": "post_execution", "action_type": "position.hold", # namespaced . "target_system": "broker-api", "action_summary": "Hold current Spain win position", "parameters": {"symbol": "ESP_WIN"}, "execution_status": "confirmed", "outcome": "success", }) 4. Ask a person and record the decision (Escalating, Attesting)
When the agent hands a decision to a person, it writes an Escalating record once the wait is over; the person's disposition is an Attesting record that lists it in upstream_record_id. submit_attesting sets behavior to "Attesting", executor to "human" and, unless you pass one, record_phase to "concurrent".
ask = session.submit({ "behavior": "Escalating", "executor": "ai", "record_phase": "post_execution", "kind": "permission", # "question" | "permission" | "plan" | "handoff" "asked": "Hold the Spain win position?", # content; may be a raw value "options": ["hold", "close"], "outcome": "success", # answered; "timeout" if nobody did "duration_ms": 42_000, # how long it waited }) session.submit_attesting({ "upstream_record_id": [ask["record_id"]], "operator_id": "reviewer-7", "disposition": "approve", # "approve" | "reject" | "edit" | "cancel" | "no_response" "outcome": "success", # "timeout" with no_response, "cancelled" with cancel "gate_kind": "permission", "decision": {"action": "hold"}, # any JSON value "written_by": {"component": "review-ui", "credential": "svc-reviewer"}, }) A "reject" needs a reason, a "no_response" needs outcome: "timeout" and a "cancel" needs outcome: "cancelled"; the SDK checks these before sending. Optional fields: decision, reason, patch, seen_digest, seen_completeness, channel, policy_snapshot, effects (content; may be a raw value).
batch_ack = session.submit_batch([record_a, record_b]) for result in batch_ack["results"]: if "code" in result: print("Record failed:", result["record_id"], result["code"], result["message"]) Up to 50 records per batch. Per-record validation runs locally before the network call; only locally-valid records are sent. Partial server-side failure does not raise — inspect BatchAck["results"].
Raw text never goes into a record. Content positions hold a ContentRef — {"sha256", "bytes", "media_type"} — pointing at bytes stored in the server's content library:
ToolCalling.input_payload, ToolCalling.output_payload
Thinking.prompt, Thinking.output_payload, Thinking.inputs[].input_payload
Reflecting.output_payload, Reflecting.inputs[].input_payload
Delegating.goal, Delegating.result
model_invocation.internal_reasoning
model_invocation.replay_of, unless it names a record: a string in UUID form is a record id and is left as given
Raw values. In submit, submit_batch and the Session submit methods, a content position may hold a raw value instead. The SDK uploads it, puts the returned ContentRef in its place, then validates and submits:
A dict whose keys are exactly sha256 (64 lowercase hex), bytes (non-negative int) and media_type (str) counts as a ContentRef and is left alone. Uploads happen before the record request; a failed upload fails the submit (for a batch, before the batch is posted). To leave an optional position empty, omit the key — None is JSON null and gets uploaded.
ref = client.put_content("full prompt text") # text/plain; charset=utf-8 ref = client.put_content(png_bytes, media_type="image/png") # bytes default to application/octet-stream data: bytes = client.get_content(ref) # or client.get_content(ref["sha256"]) Uploads are idempotent by hash: content already stored answers with its existing reference. The server enforces the content size limit (HTTP 413 → ValidationError). Reading content that does not exist or was deleted raises NotFoundError.
Content can be encrypted on this machine before it is uploaded, so the ledger holds ciphertext it cannot open. Give the client a ContentEncryption built from a master key that stays in a file only you can read:
from reasoning_ledger import ContentEncryption, generate_master_key, load_master_key, save_master_key path = "~/.stair/master.key" # made once; back it up: without it the content cannot be read try: master_key = load_master_key(path) except FileNotFoundError: master_key = generate_master_key() save_master_key(path, master_key) # 0600 client = LedgerClient(LedgerClientConfig( agent_id=agent_id, api_key=api_key, endpoint=endpoint, encryption=ContentEncryption(master_key=master_key, agent_id=agent_id), )) Every content position is then uploaded as AES-256-GCM ciphertext under a data key, one per session; the data key is wrapped with the master key and registered at PUT /v1/content-keys/{key_id} before any record names it. The reference carries enc: the cipher, the key id, and the plaintext's digest, size and media type. The structure of the record (behavior, timing, outcome, tool names) stays readable; the text does not.
client.open_content(ref) reads a reference back and decrypts it with the client's encryption (ValidationError without one; ValueError when another master key wrapped the key).
client.put_content_key(key_id, body), client.get_content_key(key_id), client.list_content_keys(session_id=..., after=..., limit=...) are the key endpoints; ContentEncryption.wrapped(data_key) makes a body. Rotating the master key is reading every key, unwrapping, re-wrapping and registering it again under the same id.
master_key_fragment(master_key) is the key as the trace viewer's sign-in link carries it (#k=...): the browser decrypts with it and never sends it.
All behaviors extend the base record fields. The "behavior" key is the discriminant. Every record requires executor and record_phase. Optional on every record: outcome (required where the table says so), duration_ms, error_type, sources, verdict, written_by, on_behalf_of_agent_id, classification, model_invocation, upstream_record_id, notes, tags.
The SDK fills these if you omit them:
Records read back also carry server_ts_utc and sequence, the server-assigned order.
All errors inherit from LedgerError and carry a stable code string:
from reasoning_ledger import ( AuthError, IdempotencyConflictError, LedgerError, NetworkError, NotFoundError, RateLimitError, ServerError, ValidationError, ) try: session.submit({...}) except ValidationError as e: # Local schema check failed — never reached the network print(e.details.get("field"), e.details.get("reason")) except RateLimitError as e: wait_ms = e.details.get("retry_after_ms") # back off and retry except LedgerError as e: print(e.code, e) Class code When ValidationError validation_failed Local check failed (record never sent), missing endpoint, server 400, or content too large (413) AuthError auth_invalid API key rejected RateLimitError rate_limited Server rate-limited the request NetworkError network_failed Request never reached the server after retries ServerError server_5xx Non-retryable 5xx from server IdempotencyConflictError record_id_conflict Same record_id submitted with different body NotFoundError not_found Lookup target does not exist (404), or content was deleted (410) Configuration
Inject any object implementing the HttpTransport protocol to intercept or mock network calls. Request bodies are str for JSON calls and bytes for content uploads; set body_bytes on the response to return binary content (the default HttpxTransport always does):
from reasoning_ledger import HttpRequest, HttpResponse, HttpTransport class LoggingTransport: def request(self, req: HttpRequest) -> HttpResponse: print(req["method"], req["url"]) # delegate to real httpx ... API reference
LedgerClient.register_agent(opts) → AgentRegistration
Register a new agent. Idempotent on (owner, name).
opts = RegisterAgentOpts( api_key="sl_...", endpoint="https://ledger.example.com", name="my-agent", metadata=AgentMetadata(description="...", tags=["tag1"]), wallet=AgentWalletInput(address="0x..."), # BYOW only ) LedgerClient.resolve_agent_id(opts) → str
Look up an agent_id by human-readable name.
opts = ResolveAgentOpts(api_key="sl_...", endpoint="https://ledger.example.com", name="my-agent") Instance methods
client.submit(record) → RecordAck
Submit one record. Raw values at content positions are uploaded first.
client.submit_attesting(record) → RecordAck
Submit an Attesting record; behavior, executor and the default record_phase are set for you. Pass outcome yourself.
client.submit_batch(records) → BatchAck
Submit up to 50 records in one request.
client.put_content(data, media_type=None) → ContentRef
Upload str or bytes to the content library.
client.get_content(ref) → bytes
Download content by ContentRef or sha256.
client.get_record(record_id) → dict
Fetch a single stored record.
client.get_session(session_id) → SessionFetch
Fetch every record in a session, in the order the server received them (sequence ascending).
client.get_trace(opts?) → TracePage
Paginated read of the agent's full trace, newest first. Pass the previous page's next_cursor as before; it is None on the last page.
from reasoning_ledger import GetTraceOpts page = client.get_trace(GetTraceOpts(limit=100)) older = client.get_trace(GetTraceOpts(before=page["next_cursor"], limit=100)) client.new_session(session_id=None) → Session
Create a local session handle. Generates a session_id if not supplied.
session.submit(record) / session.submit_attesting(record) → RecordAck
Same as the client methods; session_id is auto-injected.
session.submit_batch(records) → BatchAck
Same as client.submit_batch; session_id is auto-injected on each record.
The bound session_id (read-only property).
from reasoning_ledger import is_valid_record_id, new_record_id, now_epoch_ms new_record_id() # → fresh UUID v4 string now_epoch_ms() # → current epoch milliseconds (int) is_valid_record_id("...") # → bool — is the string a valid UUID v4? Use new_record_id() when a record must reference one not yet submitted, via upstream_record_id, approved_by or revision_of.
MIT View SPDX License List
ai-agents audit-trail audit-log reasoning llm
Development Status 5 - Production/Stable
Intended Audience Developers
Programming Language Python :: 3
Release files for reasoning-ledger 2.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
Built distribution (wheel)
Total release size: 71.7 kB
Release files / reasoning_ledger-2.3.0.tar.gz
Security for reasoning-ledger 2.3.0
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.
None of the files in this release were uploaded with provenance metadata.
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
Nov 12, 2026 2 release files No provenance
Nov 10, 2026 2 release files No provenance
Sep 23, 2026 2 release files No provenance
Sep 20, 2026 2 release files No provenance
Jun 2, 2026 2 release files No provenance
May 11, 2026 2 release files No provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation




