Skip to main content

reasoning-ledger

Python SDK for the Reasoning Ledger — an append-only audit trail for AI agent reasoning.

Install

pip install reasoning-ledger

Requires Python 3.12+. Dependencies: pydantic>=2, httpx>=0.27.

Upgrading to schema 0.5

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 <domain>.<verb>, 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.

Upgrading from 0.3

  • 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.

Quick start

Every call needs the base URL of your Reasoning Ledger server as endpoint. There is no default.

1. Register an agent

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

from reasoning_ledger import LedgerClient, LedgerClientConfig

client = LedgerClient(LedgerClientConfig(
    api_key=os.environ["STAIRAI_API_KEY"],
    agent_id=agent_id,
    endpoint=ENDPOINT,
))

The constructor performs no network call. A missing endpoint raises ValidationError right away; the API key and agent ID are checked on the first request.

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 <domain>.<verb>
    "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).

5. Submit a batch

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"].


Content

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
  • Attesting.effects
  • Escalating.asked
  • Delegating.goal, Delegating.result
  • Memorizing.target
  • 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:

Value Uploaded as
str UTF-8, text/plain; charset=utf-8
bytes as is, application/octet-stream
any other JSON value (dict, list, number, bool, None) json.dumps(value, separators=(",", ":"), ensure_ascii=False), application/json

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.

Direct access.

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.

Encryption

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.

Behavior types

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.

Behavior Required fields (beyond base)
"Observing" trigger_source, trigger_type, trigger_description, trigger_payload_summary
"ToolCalling" tool_meta (with name), input_payload, output_payload, outcome
"Planning" goal, steps (optional contingencies, revision_of)
"Thinking" output_payload
"Acting" action_type (<domain>.<verb>), target_system, action_summary, execution_status, outcome (plus execution_id when target_system is "public-chain" and execution_status is "confirmed")
"Reflecting" inputs, output_payload
"Attesting" operator_id, disposition, gate_kind, written_by, outcome; executor must be "human" (plus reason when disposition is "reject"; outcome must be "timeout" when it is "no_response" and "cancelled" when it is "cancel")
"Escalating" kind, asked, outcome
"Delegating" kind, goal, outcome
"Memorizing" scope, target, op, outcome
"Other" label, data

Auto-filled fields

The SDK fills these if you omit them:

Field SDK default
record_id Fresh UUID v4
schema_version "0.5" (bundled constant)
client_ts_utc Current epoch milliseconds
agent_id From LedgerClientConfig.agent_id

Records read back also carry server_ts_utc and sequence, the server-assigned order.


Error handling

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

from reasoning_ledger import LedgerClientConfig

config = LedgerClientConfig(
    api_key="sl_...",
    agent_id="uuid-v4",

    # Base URL of your Reasoning Ledger server — required, no default
    endpoint="https://ledger.example.com",

    # Default model invocation stamped on every record unless overridden per-record
    default_model_invocation={
        "invocation_kind": "live",
        "provider": "anthropic",
        "model_name": "claude-opus-4-7",
        "tokens_in": 0,
        "tokens_out": 0,
    },

    # Retry: 3 total attempts with 500 ms / 1 s / 2 s backoff (these are the defaults)
    retry={"attempts": 3, "backoff_ms": [500, 1000, 2000]},

    # Custom HTTP transport — useful for tests
    http_transport=my_mock_transport,
)

The environment option and the ENDPOINTS constant were removed in 1.0 (their built-in hosts never resolved): pass endpoint. A trailing slash is trimmed.

Custom HTTP transport

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

Static / class methods

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 methods

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.

session.id → str

The bound session_id (read-only property).

Utility functions

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.


License

MIT

Metadata

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)

Source distribution for reasoning-ledger 2.3.0
File Size Uploaded Provenance Actions
reasoning_ledger-2.3.0.tar.gz 33.4 kB Without provenance Details for reasoning_ledger-2.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for reasoning-ledger 2.3.0
File Interpreter ABI Platform Actions
reasoning_ledger-2.3.0-py3-none-any.whl Python 3 none any Details for reasoning_ledger-2.3.0-py3-none-any.whl

Total release size: 71.7 kB

Release files / reasoning_ledger-2.3.0.tar.gz

Download URL reasoning_ledger-2.3.0.tar.gz
Size 33.4 kB
Tags Source
SHA-256 checksum
How to use checksums
deb58d8098f7de06461a817446d131c5187392a0a46c03dfa66ebf09384fb156
BLAKE2b-256 checksum
How to use checksums
43ecdbd910bcb03b550acfd6365086faad94524e730a3f6dfaf83ffcbc181573
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / reasoning_ledger-2.3.0-py3-none-any.whl

Download URL reasoning_ledger-2.3.0-py3-none-any.whl
Size 38.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5fb15b4cf85bb25d7b541aa59d4fc5efde4ba555c2ee6c67c09c0fe522538fed
BLAKE2b-256 checksum
How to use checksums
c00a04ab1e607c58c5e78bb8d16915dbe72f3513c83699d7b536677c1d1b6080
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for reasoning-ledger 2.3.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.

No provenance found

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.

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