Skip to main content
The Zespan Python SDK instruments your Python LLM application with a single init() call. It uses a background daemon thread to flush events without blocking your application, and registers an atexit handler to flush on process exit.

Installation

Initialization

Call zespan.init() once at startup before making any LLM calls. All parameters are keyword arguments.
Parameters:
string
required
Your Zespan API key. Must start with zsp_. Find this in your project settings.
string
default:"production"
Environment label attached to every event. Use "staging" or "development" to separate traces by environment.
boolean
default:"True"
When True (default), prompt and completion text are stored alongside traces with PII redaction applied before transmission. Set to False to disable prompt storage entirely.
float
default:"1.0"
Fraction of events to send, between 0.0 and 1.0. Set to 0.1 to trace 10% of calls.
list[str]
Keys whose values are redacted before any data is stored. Applied regardless of store_prompts. Passing this option replaces the default list rather than adding to it — see PII redaction below.
boolean
default:"False"
Opt-in pattern-based PII detection (emails, SSNs, credit cards, and similar) layered on top of key-based redact_keys matching. Tune it with pii_preset, pii_redaction_mode, pii_whitelist, pii_categories, and pii_confidence_threshold.
int
default:"50"
Number of events to accumulate before flushing.
float
default:"2.0"
Seconds between automatic flushes. The SDK also flushes on process exit.
int
default:"1000"
Maximum number of events held in the in-memory queue. Once exceeded, the oldest queued event is dropped to make room for new ones.
string
default:"https://api.zespan.com/v1/ingest"
Full ingest URL. Prompts, datasets, and guardrail checks all derive their base URL from this value. Override it for self-hosted deployments.
string
default:"https://api.zespan.com"
Root API URL used only by the config-propagation client (see Config propagation). For a self-hosted deployment, set this to the same host as endpoint.
string
Your Zespan project ID. Required, together with enable_zespan_pilot=True, to receive live config changes pushed from ZespanPilot or the dashboard.
boolean
default:"False"
When True and project_id is set, the SDK applies config changes (model overrides, sample rate, guardrail toggles) pushed from ZespanPilot or the dashboard. See Config propagation.
boolean
default:"False"
When True, also exports spans to an OpenTelemetry-compatible backend. Requires otel_endpoint.
string
OTel collector endpoint URL. Required when enable_otel=True.
string
default:"zespan-sdk"
Service name attached to exported OTel spans.
boolean
default:"False"
When True, logs internal flush errors to stdout. Enable during integration testing.

Auto-patching all providers

autopatch() detects which LLM libraries are installed and patches them all in one call. Use this instead of calling individual patch functions.
Covers: OpenAI, Anthropic, Google Generative AI (legacy google-generativeai package), AWS Bedrock, Mistral, Groq, LiteLLM — whichever of these packages are importable in your environment.
autopatch() does not patch the new Google GenAI SDK (google-genai) or OpenRouter. Call zespan.patch_google_genai() or zespan.patch_openrouter() explicitly for those.

Provider patches

OpenAI

Anthropic

Google Generative AI (legacy SDK)

Also patches genai.embed_content() automatically — embedding calls emit span_kind: embedding. Image generation models (e.g. gemini-3.1-flash-image) are detected from the response and emit span_kind: image_gen. The google-genai package is Google’s current Python SDK. patch_google_genai() patches Client.__init__ so every client instance you create is automatically traced.

AWS Bedrock

Mistral

Groq

LiteLLM

OpenRouter

Framework and agent integrations

Beyond the direct provider patches above, the SDK integrates with popular agent and orchestration frameworks. Each has its own dedicated guide:
  • LangChainZespanCallbackHandler traces chains, agents, tools, and retrievers. See LangChain.
  • LlamaIndexZespanLlamaIndexCallbackHandler traces query engines and retrievers. See LlamaIndex.
  • AutoGen / AG2wrap_autogen_agent traces ConversableAgent replies. See AutoGen.
  • CrewAIwrap_crew traces crew task execution. See CrewAI.
  • Google ADKwrap_adk_agent (or ZespanADKTracer) traces ADK agent runs. See Google ADK.
  • HaystackZespanHaystackTracer traces pipeline components. See Haystack.
  • Semantic Kernelinstrument_semantic_kernel traces kernel function invocations. See Semantic Kernel.

Context enrichment

Use with_zespan_context to attach a user_id, session_id, or custom tags to all traces generated within a function scope.
Set user_id and session_id on every request that involves a logged-in user. This enables per-user cost breakdown and session replay in the Zespan dashboard.

Agent tracing with with_agent

Use the with_agent context manager to trace a multi-step agent workflow. It creates an agent span and exposes methods to log plans, trace tool calls, and record handoffs to other agents.
with_agent parameters:
string
required
Display name for this agent in traces and the agent registry.
string
default:"specialist"
Role label such as "coordinator", "specialist", or "planner".
string
default:"custom"
Framework name, e.g. "custom", "langchain", "google-adk".
object[]
List of tool definition objects with name and description fields.
AgentContext methods:
  • agent.log_plan(steps: list[str]) — records a planning span
  • agent.trace_tool(name, args, callable) — wraps a callable, records args and return value as a tool span
  • agent.delegate_to(target_name, reason) — records a handoff span

Manual spans with start_span

Use start_span to instrument any function as a custom span and attach evaluation scores. It returns a ManualSpan — enter span.run() to propagate trace context to nested calls, then call span.end() when the work completes to emit the event.

Prompt management

The PromptClient fetches versioned prompts from the Zespan prompt library at runtime. Results are cached locally for 5 minutes.
See the Prompt management page for the full API reference — the Python PromptClient exposes the same methods: get, list, create, update_labels, compile, and clear_cache. get() also accepts a fallback dict so calls degrade gracefully if the prompt library is unreachable, and compile() accepts a placeholders dict for prompts that splice in reusable message-list segments.
In Python, method and parameter names use snake_case: update_labels, clear_cache, prompt_type, commit_message, placeholders, fallback.

Dataset experiment runs

Use DatasetsClient (client.datasets) to run your own pipeline against a Zespan dataset, link each result back to Zespan via the trace ID your code already produces, then score and compare runs in the dashboard.
DatasetsClient methods:
method
Lists a dataset’s items by dataset name.
method
Creates or fetches a named run against a dataset. Idempotent — safe to call every time a job starts. Returns a run handle.
Run handle methods:
Links a dataset item to this run via a trace ID your own code already produced. Pass observation_id to link a specific span instead of the whole trace.
This links raw traces to a run — it doesn’t score or compare anything itself. See Datasets for the full dashboard-side walkthrough of scoring linked runs and comparing them against each other.

Flushing in serverless environments

In short-lived processes such as AWS Lambda, Vercel Functions, or Cloud Run, call zespan.get_client().flush() explicitly before the handler returns to guarantee delivery.
Omitting zespan.get_client().flush() in serverless environments is the most common cause of missing traces. Always call it before your handler returns.

PII redaction

Zespan automatically redacts values from tags and metadata fields before they leave your application. The key is preserved; the value is replaced with "[REDACTED]". Default redacted keys (applied whenever redact_keys is not passed at all): password, secret, token, api_key. Pass your own redact_keys list at initialization to protect additional fields:
redact_keys replaces the default list rather than adding to it. If you pass your own list, include password, secret, token, and api_key explicitly if you still want them redacted.
Key-based redaction applies to tags and metadata fields, and to stored prompt and completion text. Prompt storage is on by default — set store_prompts=False to disable it entirely.

Pattern-based PII detection (opt-in)

Set redact_pii=True to layer pattern-based detection (emails, SSNs, credit cards, and similar) on top of key-based redact_keys matching:
string
Named bundle of PII categories to detect, e.g. "gdpr" or "hipaa".
list[str]
Explicit list of PII categories to detect, as an alternative to pii_preset.
string
default:"placeholder"
How matched values are redacted: "placeholder" (replace entirely), "mask-middle", or "mask-all".
list[str]
Values that should never be redacted even if they match a PII pattern.
float
default:"0.7"
Minimum detector confidence, between 0.0 and 1.0, required before a match is redacted.

Guardrails

Guardrails run content safety checks before sending a prompt to the LLM (pre-check) and before returning the completion (post-check). Pass guardrails=True to any patch function to enable both phases.
See Guardrails for the full reference — parameter defaults, all fields, the direct check_guardrails() API, and a multi-wrapper example.

Config propagation

Zespan can push configuration changes — model overrides, fallback models, retry/timeout policies, sample rate, guardrail toggles, and more — to your running application without a redeployment. Changes made via ZespanPilot or the dashboard are picked up on the next event flush (default every 2 seconds), as long as both project_id and enable_zespan_pilot=True are set at init:
See Config propagation for the full list of rule types and the programmatic ConfigClient API.