This release has been yanked by its maintainers, and will be ignored by installers, except when explicitly specified.
Consider using release 2026.9.1 instead.
ZokLens Python SDK
LLM & Agent Observability via OpenTelemetry. Instrument supported LLM calls and the application spans you explicitly create.
Quick Start
pip install "zoklens>=2026.9.0,<2027"
For production, freeze or lock the resolved version before deploy.
import zoklens
# 1. Initialize
zoklens.init(
api_key="zok_xxx", # from ZokLens Console → API Keys
endpoint="https://api.zoklens.com", # or your self-hosted URL
project="my-agent",
max_export_batch_size=500, # default and hard maximum
)
# 2. Auto-instrument LLM SDKs (one line)
zoklens.instrument(providers=["openai-compatible", "anthropic"])
# 3. Your existing code — zero changes needed
import openai
client = openai.OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello!"}],
)
# ✅ Trace automatically captured: model, tokens, cost, latency
The Python SDK exports at most 500 spans in one OTLP request, matching the
server's atomic ingestion-unit limit. Values outside 1..500 fail during SDK
configuration; do not add a collector setting that recombines batches above
this limit.
Features
Typed Agent lifecycle and attempts
Use the typed API when ZokLens should measure application-owned Agent outcomes. It only emits content-free OTel evidence; it never changes routing, retries, models, tools, return values, exceptions, cancellation, or timeout behavior.
The 2026.9.0 release uses lifecycle V2 for Agent Runs when
zoklens.init(environment="development", ...) specifies a validated named
environment. Lifecycle and operation evidence retain the same scope. The default
unknown environment keeps V1 behavior; old rows are not relabeled. Start a new
Run rather than reusing an existing Run ID with a different identity schema.
run = zoklens.start_agent_run(
agent_id="support-agent",
agent_version="release-7",
session_id="opaque-session-1",
heartbeat_mode="instrumented",
heartbeat_interval_seconds=30,
progress_instrumented=True,
)
with run:
run.declare_architecture(
manifest_id="support-architecture",
manifest_version="v4",
coverage="complete",
relationships=(
zoklens.TopologyRelationship(
subject=zoklens.TopologyNodeRef(
"agent", "support-agent", "release-7"
),
predicate="enters_workflow",
object_ref=zoklens.TopologyNodeRef(
"workflow", "answer-flow", "v4"
),
),
),
)
run.delegate_to_agent("retrieval-agent", "release-3")
run.enter_workflow("answer-flow", "v4")
run.progress("step_completed")
answer = run.model_attempt(
"deepseek-chat",
actor=zoklens.TopologyNodeRef("workflow", "answer-flow", "v4"),
responding_model="deepseek-chat-2026-08",
provider_name="deepseek",
).execute(lambda: application_generate())
docs = run.tool_attempt(
"knowledge-search",
tool_version="schema-2",
tool_operation="search",
).execute(lambda: application_search())
Run IDs are run_<32 lowercase hex> from 128 bits of cryptographic randomness;
event and attempt IDs are UUIDv4. Retry and fallback lineage require an explicit
retry_of_attempt_id or fallback_of_attempt_id. Declared architecture is
observational metadata, not an execution graph. The SDK canonically sorts each
manifest's 1–100 unique relationships and emits a total count, stable
zero-based index, and one shared SHA-256 on every relationship Span. The server
honors coverage="complete" only after every indexed relationship arrives and
the full digest verifies; transport loss is shown as partial evidence. Change
manifest_version whenever relationships or coverage change. Prompt,
completion, tool arguments/results, PII, secrets, and chain-of-thought have no
typed constructor fields and content capture is declared prohibited.
Runtime Assurance evidence
Phase 4 identities are opaque, content-free values. Generate them with the SDK;
do not put names, prompts, customer identifiers, or conclusions in an ID. The
accepted kinds are harness_id, control_id, goal_id, continuation_id,
milestone_id, checkpoint_id, skill_id, server_id, tool_id, wait_id,
claim_id, and verifier_id. Runtime versions accept only v1, v1.2,
v1.2.3, or an ISO date such as 2026-08-29.
References are causal, not declarative links. A referenced lifecycle event, operation attempt, or runtime-evidence item must already be persisted for the same Run, or appear earlier in the same OTLP ingestion unit. Forward references reject the complete ingestion unit. In particular, finish an operation attempt before attributing a Skill/MCP call to it, and emit a claim or Harness decision before evidence that references it.
import uuid
import zoklens
goal_id = zoklens.generate_runtime_assurance_id("goal_id")
continuation_id = zoklens.generate_runtime_assurance_id("continuation_id")
checkpoint_id = zoklens.generate_runtime_assurance_id("checkpoint_id")
skill_id = zoklens.generate_runtime_assurance_id("skill_id")
mcp_server_id = zoklens.generate_runtime_assurance_id("server_id")
mcp_tool_id = zoklens.generate_runtime_assurance_id("tool_id")
claim_id = zoklens.generate_runtime_assurance_id("claim_id")
verifier_id = zoklens.generate_runtime_assurance_id("verifier_id")
with run:
run.authorize_goal_revision(goal_id=goal_id, revision=1)
run.bind_goal_continuation(
goal_id=goal_id, revision=1, continuation_id=continuation_id
)
run.checkpoint_context(
goal_id=goal_id,
revision=1,
continuation_id=continuation_id,
checkpoint_id=checkpoint_id,
)
run.discover_skill(skill_id=skill_id, skill_version="v1")
run.load_skill(skill_id=skill_id, skill_version="v1")
attempt = run.tool_attempt(
"knowledge-search", tool_version="v2", tool_operation="search"
)
docs = attempt.execute(lambda: application_search())
# The operation span is closed before either item references its attempt ID.
run.attribute_skill_use(
skill_id=skill_id, skill_version="v1", attempt_id=attempt.attempt_id
)
run.record_mcp_call(
server_id=mcp_server_id,
server_version="v1",
protocol_version="2026-08-29",
tool_id=mcp_tool_id,
call_id=str(uuid.uuid4()),
attempt_id=attempt.attempt_id,
)
claim_evidence_id = run.assert_claim(
claim_id=claim_id,
category="tool_outcome",
goal_id=goal_id,
revision=1,
)
run.verify_claim(
claim_id=claim_id,
verifier_id=verifier_id,
verdict="supported",
references=(
zoklens.RuntimeAssuranceReference(
"runtime_evidence", claim_evidence_id
),
),
)
If the application is Workflow-only, use start_workflow_run(...) with the
real Workflow identity. Do not create a synthetic Agent merely to populate an
Agent field; Workflow-root Runs support the same Runtime Assurance evidence.
Telemetry Data Safety
Prompt and reply content (2026.9.0)
Instrumented OpenAI and Anthropic calls send the prompt, system instructions and
reply on the LLM span (gen_ai.input.messages, gen_ai.system_instructions,
gen_ai.output.messages) so ZokLens can detect PII, secrets and prompt injection
in them. ZokLens masks them on arrival under your PII policy.
- Only on ordinary LLM spans: governance carriers and typed Agent spans stay content-free, and the SDK refuses content there before export.
- Images, audio and files are named by type; their bytes are never sent.
- Each text part is cut at 32 KiB, and every export request stays under 4 MiB (a larger batch is split, never dropped).
Turning content off. If your prompts or replies must not leave your service (for example regulated financial or health data), turn content off:
zoklens.init(api_key=..., project=..., capture_content=False)
or set the OpenTelemetry GenAI variable in the runtime environment:
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=false
- The argument wins over the variable. With neither set, content is on.
- A value that is not true or false (
true/1/yes/on,false/0/no/off), the empty string included, turns content off, so a typo never sends content. - The SDK's span processor also removes exception messages, stack traces and status descriptions before export, since they can quote a prompt or reply; the exception type is kept.
- Model, tokens, finish reasons, latency and status are still sent, so cost, latency and error views keep working.
- ZokLens then has no content to scan, so PII, secret and prompt-injection detection does not run on those calls.
Proving it. For a compliance review, make the setting mechanical rather than a convention:
- Set
ZOKLENS_REQUIRE_CONTENT_SETTING=truein every deployment (or passrequire_content_setting=True).init()then raisesValueErrorunlesscapture_contentorOTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENTis set, so a new service cannot inherit the default by omission. - Assert it at startup:
assert zoklens.content_capture_enabled() is False.zoklens.delivery_diagnostics()["capture_content"]reports the same value.
The legacy generic API still exports scalar metadata and caller-provided
user_id/session_id values as OTel attributes. It does not yet apply the V2
typed governance/content-policy contract to those legacy APIs.
- use opaque or tenant-approved pseudonymous correlation IDs, never email, patient/customer identity, secrets, or credentials;
- do not put raw Prompt/query/context/memory/tool bodies or hidden reasoning in
metadata; - treat generic spans/metadata as telemetry, not as validated Agent, Prompt, tool, policy, or authorization evidence.
Use the typed Agent API above for strict lifecycle evidence. Existing generic APIs continue at their honest lower coverage.
Version Compatibility
Do not auto-upgrade the SDK at runtime. Do not add startup-time package installs,
runtime self-updaters, or automatic pip install -U zoklens scripts to customer
applications. Add the SDK through your normal package manager, commit the
lockfile, and upgrade through an explicit dependency change with tests. The
2026.x SDK family is the current compatibility window; patch and minor
releases stay backward compatible for the telemetry protocol unless release
notes say otherwise.
Every trace includes SDK metadata so ZokLens can detect outdated clients:
zoklens.sdk.versionzoklens.sdk.languagezoklens.sdk.protocol_versionzoklens.sdk.compatibility_family
Auto-Instrumentation
Automatically patches LLM SDKs to capture traces — zero code changes to your LLM calls.
zoklens.instrument(providers=["openai-compatible"]) # OpenAI, DeepSeek, Gemini-compatible, custom gateways
zoklens.instrument(providers=["anthropic"]) # Anthropic SDK
zoklens.instrument(providers=["deepseek"]) # Alias for OpenAI-compatible DeepSeek setups
Captured attributes:
- Canonical GenAI:
gen_ai.request.model,gen_ai.response.model,gen_ai.provider.name,gen_ai.usage.input_tokens,gen_ai.usage.output_tokens,gen_ai.usage.total_tokens - Compatibility aliases:
llm.model,llm.request.model,llm.response.model,llm.provider,llm.tokens.input,llm.tokens.output,llm.tokens.total,llm.duration_ms
When both request and response models are present, ZokLens uses the response
model for display because it reflects the actual provider result. The SDK
preserves exact provider model strings and does not write "unknown" as a model.
Custom Spans
Track any operation in your agent pipeline:
with zoklens.span("retrieval", metadata={"retrieval_system": "support-kb", "top_k": 5}):
docs = retriever.search(query)
with zoklens.span("generation", metadata={"model": "gpt-4o"}):
response = llm.generate(prompt)
Session Tracking
Group related spans under a session with user context:
with zoklens.session(user_id="u123", session_id="s456"):
# All spans inside automatically get user_id and session_id
with zoklens.span("step-1"):
...
with zoklens.span("step-2"):
...
Shutdown
Flush pending spans before exit:
zoklens.shutdown()
How It Works
Your App ZokLens
┌─────────────────────┐ ┌──────────────┐
│ import zoklens │ │ │
│ zoklens.init(...) │ OTLP │ Trace Store │
│ zoklens.instrument()│────────→│ Cost Calc │
│ │ HTTP │ AI Copilot │
│ llm.chat(...) │ │ │
└─────────────────────┘ └──────────────┘
The SDK uses OpenTelemetry under the hood:
- Configures a
TracerProviderwith a customZokLensSpanExporter - Exports traces via OTLP/HTTP to
POST /api/v1/otel/v1/traces - Authenticates with
X-API-Keyheader for tenant isolation
SDK vs Proxy
| Proxy (Sprint 10) | SDK (Sprint 12) | |
|---|---|---|
| Setup | Change BASE_URL |
import zoklens |
| Code changes | Zero | 3 lines |
| Trace depth | HTTP layer | Span/chain level |
| Custom attributes | ❌ | ✅ user_id, session, metadata |
| Agent internals | ❌ | Typed lifecycle, Agent/Workflow topology, and Model/Tool attempts |
| Best for | Quick start | Agent developers |
Both can be used simultaneously.
Requirements
- Python ≥ 3.9
- OpenTelemetry SDK (installed automatically)
License
Apache-2.0
Metadata
Release files for zoklens 2026.9.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| zoklens-2026.9.0.tar.gz | 79.0 kB | Without provenance | Details for zoklens-2026.9.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| zoklens-2026.9.0-py3-none-any.whl | Python 3 | none | any | Details for zoklens-2026.9.0-py3-none-any.whl |
Total release size: 136.1 kB
Release files / zoklens-2026.9.0.tar.gz
| Download URL | zoklens-2026.9.0.tar.gz |
|---|---|
| Size | 79.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
79c7116201f2ef940289753df77db2035eb35d592189de7fcad8fb63d16a3248
|
|
BLAKE2b-256 checksum How to use checksums |
6f6b98831e2c03812bba90388b5bd6ef31c0afa41f6a1fe4feaa457abc028ef3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Release files / zoklens-2026.9.0-py3-none-any.whl
| Download URL | zoklens-2026.9.0-py3-none-any.whl |
|---|---|
| Size | 57.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4ec0c2fea1a677aa0fc00634d38bd046dad5a3cd4bd793ca1e7ece1c5d0b7de3
|
|
BLAKE2b-256 checksum How to use checksums |
b28aaf6ec51344f73c48a6dca69a40f929cdc0efd8e8c9eba5e1a3ecc91f02f2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Security for zoklens 2026.9.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.