API Reference

The dense reference for the Peekr Python SDK. Requires Python 3.9+. Install with pip install peekr (or "peekr[openai]", "peekr[anthropic]", "peekr[all]").

peekr.instrument()

Call this once at the very top of your entrypoint. It patches the supported LLM SDKs at the class level, so every client you create afterward is traced automatically.

python
import peekr
peekr.instrument()  # default: console=True, writes traces.jsonl

Warning

Call-order rule: instrument() must run before you import any LLM SDK or create a client. Patching happens at import time — anything imported earlier is missed.

Full signature

python
peekr.instrument(
    console=True,                 # print spans to stdout
    storage="jsonl",              # "jsonl" | "sqlite" | "both"
    jsonl_path="traces.jsonl",    # path for JSONL storage
    db_path="traces.db",          # path for SQLite storage
    tenant_id=None,               # per-customer subdivision
    retention_class=None,         # default | short | long | pii
    alerts=[],                    # peekr.alert.* instances
    evaluators=[],                # peekr.eval.* instances
    guardrails=[],                # peekr.guard.* instances
    compliance=[],                # Cloud-only, e.g. ["HIPAA", "GDPR"]
    exporter=None,                # e.g. peekr.HTTPExporter(...)
)

Arguments

ArgumentDefaultDescription
consoleTruePrint spans to stdout as they finish.
storage"jsonl"Where to persist spans: "jsonl", "sqlite", or "both".
jsonl_path"traces.jsonl"File path used when storage includes JSONL.
db_path"traces.db"File path used when storage includes SQLite.
tenant_idNonePer-customer subdivision. Overridable per session() or via env.
retention_classNonedefault | short | long | pii. Controls retention policy.
alerts[]List of peekr.alert.* instances (ErrorRate, CostSpike, …).
evaluators[]List of peekr.eval.* instances (Rubric, Hallucination, …).
guardrails[]List of peekr.guard.* instances (PIIRedact, Blocklist, …).
compliance[]Cloud-only compliance packs. Requires HTTPExporter + Pro plan.
exporterNoneShip spans elsewhere, e.g. peekr.HTTPExporter(...) for Peekr Cloud.

Providers patched

instrument() patches these SDKs at the class level: OpenAI (sync + async, chat + embeddings), Anthropic, AWS Bedrock, and Google Gemini.

Connect to Peekr Cloud

Pass an HTTPExporter to stream spans to the hosted dashboard.

python
peekr.instrument(
    tenant_id="acme",
    exporter=peekr.HTTPExporter(
        endpoint="https://peekr.starkspherelabs.com",
        api_key="pk_live_…",
    ),
)
typescript
import { instrument } from "@peekr/sdk";

instrument({
  exporter: {
    type: "http",
    endpoint: "https://peekr.starkspherelabs.com",
    apiKey: "pk_live_…",
  },
});

@trace decorator

Wrap any function to record it as a span. Works on sync and async functions. The span name defaults to module.function.

python
from peekr import trace

# Basic — name defaults to module.function, captures I/O
@trace
def fetch_user(user_id: int) -> dict: ...

# With options
@trace(name="user.lookup", capture_io=True)
def fetch_user(user_id: int) -> dict: ...

# Async works identically
@trace
async def run_pipeline(query: str) -> str: ...

Arguments: name=None (defaults to module.function) and capture_io=True (store inputs and outputs on the span).

Manual spans

For full control, start and end spans yourself. start_span returns the span plus a token you must pass back to end_span.

python
from peekr import start_span, end_span, get_current_span

span, token = start_span("my.op")
span.attributes["k"] = "v"
span.status = "ok"          # "ok" | "error"
end_span(span, token)

# Reach the active span anywhere in the call stack
current = get_current_span()

Custom exporters

An exporter is any object with an export(self, span) method. Register it with add_exporter. The built-in JSONLExporter and ConsoleExporter are added automatically.

python
from peekr.exporters import add_exporter

class MyExporter:
    def export(self, span):
        data = span.to_dict()
        # ship it anywhere: a queue, webhook, your own store…
        ...

add_exporter(MyExporter())

CLI

The peekr command reads your trace files locally.

1

View a trace file

Print spans from a JSONL or SQLite file. Add --io to include inputs and outputs.

terminal
peekr view traces.jsonl
peekr view traces.db --io
2

Generate an HTML report

Render a self-contained dashboard from a SQLite database.

terminal
peekr dashboard traces.db -o report.html
3

Replay a single trace

Step through one trace by id from a SQLite database.

terminal
peekr replay <trace_id> --db traces.db

Storage modes

Choose where spans are written with the storage argument. "both" writes JSONL and SQLite simultaneously.

python
# Local SQLite — queryable
peekr.instrument(storage="sqlite", db_path="traces.db")

# JSONL and SQLite at once
peekr.instrument(storage="both")

SQLite uses WAL mode, so it is safe for concurrent writes from async agents. Spans land in the spans table, where attributes is stored as JSON.

sql
SELECT json_extract(attributes, '$.model') AS model,
       json_extract(attributes, '$.tokens_total') AS tokens
FROM spans
ORDER BY start_time DESC
LIMIT 20;

Environment variables

These override the matching instrument() arguments.

VariableDescription
PEEKR_TENANT_IDSets tenant_id when not passed explicitly.
PEEKR_RETENTION_CLASSSets retention_class: default | short | long | pii.

Span fields

Every span has top-level fields and an attributes JSON object.

Top-level fields

FieldDescription
trace_idGroups all spans from one agent run.
span_idUnique span identifier.
parent_idLinks to the parent span for nesting.
nameSpan name, e.g. openai.chat or your @trace name.
start_timeStart timestamp.
end_timeEnd timestamp.
duration_msWall-clock duration in milliseconds.
statusok | error.
tenant_idPer-customer subdivision.
retention_classdefault | short | long | pii.

attributes.*

FieldDescription
attributes.modelLLM model name.
attributes.tokens_inputPrompt token count.
attributes.tokens_outputCompletion token count.
attributes.tokens_totalTotal token count.
attributes.inputLLM prompt (when I/O capture is on).
attributes.outputLLM response (when I/O capture is on).
attributes.errorError message, if the span failed.
attributes.session_idSet inside a peekr.session() block.
attributes.user_idSet inside a peekr.session() block.
attributes.eval_scoresdict of evaluator name → score.
attributes.experiment_variantVariant name from @experiment.
attributes.featureCustom tag for dashboard filtering.
attributes.endpointRoute path, set by FastAPIMiddleware.

Note

The attributes field is stored as JSON. In SQLite, query nested values with json_extract(attributes, '$.model').