Skip to main content

zespan

LLM observability for Python. Trace every AI call — latency, tokens, cost, errors — with one init().

Install

pip install zespan

Optional extras:

pip install "zespan[otel]"             # OpenTelemetry export
pip install "zespan[llamaindex]"       # LlamaIndex integration
pip install "zespan[haystack]"         # Haystack integration
pip install "zespan[semantic-kernel]"  # Semantic Kernel integration

Quick start

import zespan

zespan.init(
    api_key="zsp_your_key_here",
    project_id="your_project_id",
)
zespan.autopatch()

Get your API key and project ID from app.zespan.com → Project Settings → API Keys.

After init() + autopatch(), all calls to OpenAI, Anthropic, Google GenAI, and other installed providers are automatically traced.

Auto-instrumentation

autopatch() detects and patches every AI provider that is installed:

import zespan
import openai

zespan.init(api_key="zsp_...", project_id="proj_...")
zespan.autopatch()

client = openai.OpenAI()
# This call is automatically traced
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello"}],
)

Supported providers:

Function Provider
patch_openai() OpenAI
patch_anthropic() Anthropic
patch_google() Google Generative AI
patch_openrouter() OpenRouter
patch_bedrock() AWS Bedrock
patch_mistral() Mistral
patch_groq() Groq
patch_litellm() LiteLLM

Patch individual providers manually:

from zespan import patch_openai, patch_anthropic

patch_openai()
patch_anthropic()

Configuration

zespan.init(
    api_key="zsp_...",           # required
    project_id="proj_...",       # required — links traces to a project
    environment="production",    # default: "production"
    store_prompts=False,         # store prompt/completion text (default: False)
    redact_keys=["password", "secret", "token", "api_key"],  # keys to redact
    sample_rate=1.0,             # 0.0–1.0, fraction of events to send
    debug=False,                 # log SDK activity to console
    batch_size=50,               # events per batch flush
    flush_interval=2.0,          # seconds between batch flushes
)

User and session context

Tag traces with user ID, session ID, or custom metadata:

from zespan import with_zespan_context

with with_zespan_context(
    user_id="user_123",
    session_id="sess_abc",
    tags={"feature": "chat"},
):
    # All AI calls inside are tagged with this context
    client.chat.completions.create(...)

Works as a decorator too:

@with_zespan_context(user_id="user_123")
def handle_request():
    client.chat.completions.create(...)

Agent tracing

Group multi-step agent workflows into a single trace:

from zespan import with_agent

with with_agent(
    name="SupportAgent",
    role="specialist",
    framework="custom",
    tools=[{"name": "lookup_order", "description": "Look up order by ID"}],
) as agent:
    agent.log_plan(["Look up order", "Check policy", "Draft reply"])

    order = agent.trace_tool(
        "lookup_order",
        {"order_id": "123"},
        lambda: fetch_order("123"),
    )

    agent.delegate_to("RefundAgent", "refund requested")

    # Wrapped LLM calls inside here inherit agent context
    client.chat.completions.create(...)

Agent span types emitted:

span_kind When
agent Agent start/end
planning log_plan()
tool trace_tool()
handoff delegate_to()

Manual spans

Trace custom operations that aren't LLM calls:

from zespan import start_span

with start_span(name="document-retrieval", span_kind="retrieval") as span:
    docs = vector_store.search(query)
    span.end(status="success")

Framework integrations

LangChain

from zespan import ZespanCallbackHandler

handler = ZespanCallbackHandler()

chain = LLMChain(llm=llm, prompt=prompt, callbacks=[handler])

Google ADK

from zespan import ZespanADKTracer

tracer = ZespanADKTracer()
# pass tracer to your ADK runner

Or wrap a specific agent:

from zespan import wrap_adk_agent

traced_agent = wrap_adk_agent(my_agent, name="MyAgent")

LlamaIndex

from zespan import ZespanLlamaIndexCallbackHandler
from llama_index.core import Settings

handler = ZespanLlamaIndexCallbackHandler()
Settings.callback_manager.add_handler(handler)

Haystack

from zespan import ZespanHaystackTracer

tracer = ZespanHaystackTracer()
# use as Haystack tracer

Semantic Kernel

from zespan import instrument_semantic_kernel

instrument_semantic_kernel(kernel)

CrewAI

CrewAI uses OTEL-based instrumentation. Set the env vars Zespan exposes:

from zespan.integrations.crewai_handler import get_crewai_env_vars

env = get_crewai_env_vars()
# apply env to your process before launching CrewAI

AutoGen

from zespan import injectAutoGenContext, extractAutoGenContext

# Inject trace context into an AutoGen message
msg = injectAutoGenContext(msg, trace_id="trace_123")

# Extract it on the receiving end
ctx = extractAutoGenContext(msg)

Prompt management

Fetch versioned prompts from Zespan with 5-minute client-side cache:

import zespan

client = zespan.get_client()

# Latest version
prompt = await client.prompts.get("support-reply")

# Specific version or label
prompt = await client.prompts.get("support-reply", version=3)
prompt = await client.prompts.get("support-reply", label="production")

# Compile variables
text = client.prompts.compile(prompt, {"user_name": "Alice", "product": "Pro"})

Guardrails

Check content against your configured guardrail rules before or after LLM calls:

import zespan

check = zespan.check_guardrails(
    text=user_message,
    phase="pre",
)

if not check["allowed"]:
    return "Request blocked by content policy."

response = client.chat.completions.create(...)

post_check = zespan.check_guardrails(
    text=response.choices[0].message.content,
    phase="post",
)

return post_check["modifiedText"] or response.choices[0].message.content

Confirm before a destructive call

If you declared a tool destructive, a require_confirmation policy rule can flag a call to it that has no confirmation recorded by your app. Record one after your own confirmation step (a person pressed confirm in your UI), never straight from model output:

import zespan

result = zespan.confirm_tool_call(
    "issue_refund",
    args={"order_id": "4412", "amount": 50},  # the exact arguments that were confirmed
    ref=confirm_card_id,                      # optional: your own id
)

It never raises. One confirmation unlocks one call, in the same session, and the rule decides how long it lasts (default 10 minutes). Zespan checks that your app recorded it; it does not verify what the end user agreed to, and an app that records one without asking defeats the rule. The ledger is per client and per process: when the confirmation and the tool call are in different processes, pass it with with zespan.with_zespan_context(session_id=..., confirmations=[{"tool_name": ..., "args": ..., "ref": ...}]):. With tool capture off, argument hashes are keyed with a random per-client key, so they compare only inside this client. Called outside any context it returns no_context (the span is recorded, nothing is ledgered). A cross-process confirmation rebuilt on a job retry can be reused on each retry: use one confirmation per attempt. After a fork, create a new client in the child (it would share the ledger and key). With redaction on, hashes are keyed too. ZESPAN_CONFIRMATION_LEDGER=off stops it. client.await_approval(tool_name, args, session_id=...) waits for a decision in the dashboard (needs project_id; raises ApprovalRejectedError or ApprovalTimeoutError); an approved one is also recorded, and counts only for a rule that names human_review and reviewer in accept. See the docs page "Confirmations".

Flush on exit

The SDK flushes automatically on process exit via atexit. For short-lived scripts or serverless functions, flush manually:

import zespan

zespan.get_client().flush()

Async support

All SDK methods work in async contexts. Context propagation uses Python's contextvars so async tasks inherit their parent's trace context automatically.

import asyncio
import zespan
from zespan import with_zespan_context

zespan.init(api_key="zsp_...", project_id="proj_...")
zespan.autopatch()

async def main():
    with with_zespan_context(user_id="user_123"):
        response = await async_openai_client.chat.completions.create(...)

asyncio.run(main())

OpenTelemetry

Enable native OTEL export alongside Zespan:

zespan.init(
    api_key="zsp_...",
    enable_otel=True,
    otel_endpoint="http://localhost:4318",
    otel_service_name="my-service",
)

Metadata

Release files for zespan 1.7.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 zespan 1.7.0
File Size Uploaded Provenance Actions
zespan-1.7.0.tar.gz 1.3 MB Without provenance Details for zespan-1.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for zespan 1.7.0
File Interpreter ABI Platform Actions
zespan-1.7.0-py3-none-any.whl Python 3 none any Details for zespan-1.7.0-py3-none-any.whl

Total release size: 1.7 MB

Release files / zespan-1.7.0.tar.gz

Download URL zespan-1.7.0.tar.gz
Size 1.3 MB
Tags Source
SHA-256 checksum
How to use checksums
5c0cd1ca6b73073aea977e18fe9edc17df31ff93292f49086f3ff5c76cece4d6
BLAKE2b-256 checksum
How to use checksums
6c1a22f7b6aeb109ec35b8de10b46e5544fcb750de79f512e97ed591d5e5878d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via Hatch/1.18.2 {"ci":null,"cpu":"arm64","distro":{"name":"macOS","version":"27.0.1"},"implementation":{"name":"CPython","version":"3.12.15"},"installer":{"name":"hatch","version":"1.18.2"},"openssl_version":"OpenSSL 3.5.9 29 Sep 2026","python":"3.12.15","system":{"name":"Darwin","release":"27.0.0"}} HTTPX2/2.16.0

Release files / zespan-1.7.0-py3-none-any.whl

Download URL zespan-1.7.0-py3-none-any.whl
Size 399.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a9fbae1a3d140d203d434eb2d383732b50feeaacc65a490476935efc1701f5a1
BLAKE2b-256 checksum
How to use checksums
b0ec380b71f83f434a54c5f1c8b4ebe6415681a0120a44032b75dc1044c7c6b5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via Hatch/1.18.2 {"ci":null,"cpu":"arm64","distro":{"name":"macOS","version":"27.0.1"},"implementation":{"name":"CPython","version":"3.12.15"},"installer":{"name":"hatch","version":"1.18.2"},"openssl_version":"OpenSSL 3.5.9 29 Sep 2026","python":"3.12.15","system":{"name":"Darwin","release":"27.0.0"}} HTTPX2/2.16.0

Security for zespan 1.7.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