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
Callzespan.init() once at startup before making any LLM calls. All parameters are keyword arguments.
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.
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)
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.
Google GenAI (new SDK — recommended)
Thegoogle-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:- LangChain —
ZespanCallbackHandlertraces chains, agents, tools, and retrievers. See LangChain. - LlamaIndex —
ZespanLlamaIndexCallbackHandlertraces query engines and retrievers. See LlamaIndex. - AutoGen / AG2 —
wrap_autogen_agenttracesConversableAgentreplies. See AutoGen. - CrewAI —
wrap_crewtraces crew task execution. See CrewAI. - Google ADK —
wrap_adk_agent(orZespanADKTracer) traces ADK agent runs. See Google ADK. - Haystack —
ZespanHaystackTracertraces pipeline components. See Haystack. - Semantic Kernel —
instrument_semantic_kerneltraces kernel function invocations. See Semantic Kernel.
Context enrichment
Usewith_zespan_context to attach a user_id, session_id, or custom tags to all traces generated within a function scope.
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 spanagent.trace_tool(name, args, callable)— wraps a callable, records args and return value as a tool spanagent.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
ThePromptClient fetches versioned prompts from the Zespan prompt library at runtime. Results are cached locally for 5 minutes.
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
UseDatasetsClient (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.
method
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.Flushing in serverless environments
In short-lived processes such as AWS Lambda, Vercel Functions, or Cloud Run, callzespan.get_client().flush() explicitly before the handler returns to guarantee delivery.
PII redaction
Zespan automatically redacts values fromtags 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:
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)
Setredact_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). Passguardrails=True to any patch function to enable both phases.
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 bothproject_id and enable_zespan_pilot=True are set at init:
ConfigClient API.
