zhanla
Send your LLM agent's production traffic to Zhanla. Each request your agent handles becomes one trajectory — the user's message, every model call and tool call it made, and the reply — so Zhanla can find what real users do that your evals do not cover yet.
The same package also traces your agent while Zhanla runs its evals; that part needs no setup (see Eval runs). When Zhanla sets your agent up, it offers to add init and observe for you, as a diff you accept.
Requires Python 3.10 or later.
1. Install and configure
pip install zhanla
Versions before 0.2.0 of this name on PyPI were an earlier Zhanla command-line tool, unrelated to this SDK.
You need two values:
| where to get it | how to pass it | |
|---|---|---|
| API key | Zhanla web app → Settings → API Keys → Create a key. It is shown once: copy it then. A key can only send trajectories. Rotate keeps the old secret working for a day; Revoke stops it at once. | the ZHANLA_API_KEY environment variable |
| Agent id | the agent's page in the web app: the id at the end of its address, …/agents/<agent id> |
zhanla.init(agent="<agent id>") |
Trajectories go to Zhanla's hosted ingest by default (zhanla.DEFAULT_INGEST_URL). Set ZHANLA_INGEST_URL only if you were given another address. Without ZHANLA_API_KEY production tracing is off and init prints one line on stderr.
2. Wrap the function that handles one request
Call init once at startup, then put @zhanla.observe on the function that handles one request: its argument is recorded as the user's message and its return value as the reply. Everything it calls — model clients, frameworks, your own observed helpers — is recorded under it.
A plain function
import os
import zhanla
from openai import OpenAI
zhanla.init(agent=os.environ["ZHANLA_AGENT_ID"]) # returns the libraries it traced, e.g. ['openai']
client = OpenAI()
@zhanla.observe
def answer(message: str) -> str:
completion = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": message}])
return completion.choices[0].message.content
def handle_request(session_id: str, user_id: str, message: str) -> str:
zhanla.set_session_id(session_id) # see step 3: do not skip this
zhanla.set_user_id(user_id)
return answer(message)
An async function
The same decorator. Concurrent requests keep their own session and user.
@zhanla.observe
async def answer(message: str) -> str:
completion = await client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": message}])
return completion.choices[0].message.content
async def handle_request(session_id: str, user_id: str, message: str) -> str:
zhanla.set_session_id(session_id)
zhanla.set_user_id(user_id)
return await answer(message)
FastAPI, Starlette or another ASGI app
import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
app = FastAPI()
app.add_middleware(zhanla.ASGIMiddleware)
class Ask(BaseModel):
session_id: str
user_id: str
message: str
@zhanla.observe
async def reply(message: str) -> StreamingResponse:
stream = await client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": message}], stream=True) # client = AsyncOpenAI()
async def events():
async for chunk in stream:
delta = chunk.choices[0].delta.content if chunk.choices else None
if delta:
yield f"data: {json.dumps({'delta': delta})}\n\n"
yield "data: [DONE]\n\n"
return StreamingResponse(events(), media_type="text/event-stream")
@app.post("/chat")
async def chat(ask: Ask):
zhanla.set_session_id(ask.session_id)
zhanla.set_user_id(ask.user_id)
return await reply(ask.message)
Flask or another WSGI app
import json
from flask import Flask, Response, request
app = Flask(__name__)
app.wsgi_app = zhanla.WSGIMiddleware(app.wsgi_app)
@zhanla.observe
def reply(message: str) -> Response:
stream = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": message}], stream=True)
def events():
for chunk in stream:
delta = chunk.choices[0].delta.content if chunk.choices else None
if delta:
yield f"data: {json.dumps({'delta': delta})}\n\n"
yield "data: [DONE]\n\n"
return Response(events(), mimetype="text/event-stream")
@app.post("/chat")
def chat():
body = request.get_json()
zhanla.set_session_id(body["session_id"])
zhanla.set_user_id(body["user_id"])
return reply(body["message"])
ASGIMiddleware and WSGIMiddleware change nothing in production. They let Zhanla's eval runs send many test items to one running server and keep each item's trajectory apart. Add them now, and the same server works for evals too.
In the examples above the route reads the request and passes observe the message itself, so the recorded input is the user's message. You can also put @zhanla.observe on the route: a pydantic model is recorded as its fields, a dataclass as its fields, and a framework request object as the body the app has already read, or else its method and path.
Recent FastAPI versions (0.162, for one) record their own spans for routing and dependencies. They are sent with your request's spans.
3. Set the session id on every request
This is the step that makes production traffic useful. Zhanla reads all the requests that share a session id as one conversation, turn by turn. That is how it sees what a user did after a reply: asked again, corrected the agent, gave up. Without a session id, every request is a one-turn conversation, and Zhanla cannot tell how users reacted to any reply.
Use the conversation or thread id your app already has: the same value on every turn of one conversation, a new value for a new one.
zhanla.set_session_id(conversation_id) # required in practice
zhanla.set_user_id(user_id) # who is talking
zhanla.set_tags(["beta", "mobile"]) # a list of strings
zhanla.set_metadata({"plan": "pro"}) # each value is sent as JSON text; replaces earlier metadata
Each one applies to every span started after it in the same request (the same thread or async task), so call them at the start of the request, before you call your observed function. Set them on every request: a worker thread that serves request after request keeps the last value it was given until you replace it.
4. Streaming replies
When your observed function returns a stream — a generator, an async generator, a StreamingResponse (anything with a body_iterator), or a streamed Flask response — the request stays open until the stream has been read to the end. A response that is not streamed (a JSONResponse, Flask's jsonify) is recorded as its body. The reply recorded is:
- Server-sent events: the text the events carry, not the raw
data:lines. Recognised: OpenAI'schoices[0].delta.content, Anthropic'sdelta.text,{"type": "text-delta", "delta": …}(the AI SDK's UI message stream and OpenAI's Responses API), and a plaindelta,textDelta,textorcontentstring. Adata:line that is not JSON counts as text.[DONE], comments, and events whose type or name mentions reasoning, thinking, tools, arguments, errors, start, done, complete, finish or stop are left out. - The AI SDK's data stream (lines like
0:"Hello"): the text of its0:parts. - Anything else made of text or bytes: the chunks joined as they are.
- Chunks that are not text or bytes (dicts, objects): the list of chunks as JSON.
5. What is traced on its own
init instruments the libraries installed in your environment and returns their names:
| library | name in init's return value |
|---|---|
| OpenAI | openai |
| Anthropic | anthropic |
| LangChain | langchain_core |
| LlamaIndex | llama_index |
| LiteLLM | litellm |
| CrewAI (Python 3.12 and earlier) | crewai |
| OpenAI Agents SDK | agents |
| Pydantic AI | pydantic_ai |
For anything else, record steps by hand:
@zhanla.observe / @zhanla.observe(name=...) |
a span per call (sync or async) with its arguments and result |
with zhanla.span(name, kind=None): |
a span of its own; kind="subagent" or "skill" says what it is |
zhanla.generation(model, input).end(output, input_tokens, output_tokens, thinking, thinking_tokens) |
a model call |
zhanla.tool(name, arguments, mcp=None, kind=None).end(result) |
a tool call; mcp="server" marks an MCP call |
Frameworks and their clients. When LangChain, LlamaIndex or CrewAI calls a model through a client that is also traced (OpenAI, Anthropic, LiteLLM), the call is recorded once, by the framework. Calls your own code makes on the client are always kept. Early builds of this SDK switched a client's instrumentor off whenever a framework that covers it was merely installed (OpenAI and Anthropic under LangChain or LlamaIndex, OpenAI and LiteLLM under CrewAI), and lost the calls your code made on the client directly. If init's return value lists the framework but not your client, upgrade zhanla.
A library that cannot be traced is reported once on stderr (zhanla: <library> will not be traced (…)) and left out of init's return value. Your agent still runs. To make that an error instead, name the library: zhanla.init(agent=…, instrument={"openai": openai}) raises if it cannot instrument it.
6. Check that it works
- Set
ZHANLA_API_KEYand start your app.print(zhanla.init(...))should list your model client. If stderr sayszhanla: production tracing is off, the key is not set in that process. - Send it one test request, and then a second one with the same session id.
- Spans are sent in the background every few seconds, and when the process exits. In a script or test, let the process end on its own or call
zhanla.flush(). - Open Zhanla in your terminal in the repository the agent belongs to. The first production trajectories for a repository bring up a Production trajectories have arrived card that asks whether Zhanla should watch them. You can also ask in chat, for example "show me the latest production trajectories for my support agent". Production trajectories are not shown in the web app.
If nothing arrives, see Troubleshooting.
What leaves your app, and how long it is kept
For each request: the input and output of each observed call; each model call's model name, messages, reply and token counts; each tool call's name, arguments and result; error messages and stack traces; the session id, user id, tags and metadata you set; the agent id; and span names and timings. Spans that installed frameworks create on their own (for example FastAPI's) are sent too.
To redact data before it leaves the process, pass mask:
zhanla.init(agent=…, mask=lambda value: redact_emails(value))
mask runs on every input, output, message, tool argument and result, and error message. What it returns is what gets sent. It does not run on session ids, user ids, tags, metadata, model names or tool names.
Production trajectories are kept with no automatic deletion at the moment. A trajectory over 5 MB is refused and not stored.
Troubleshooting
Nothing arrives.
zhanla: production tracing is off: set ZHANLA_API_KEY…on stderr: the key is not in the environment of the process that calledinit.zhanla: could not send trajectories (the export failed)on stderr, usually after an OpenTelemetry line such asFailed to export spans batch code: 401, reason: Unauthorized: the key is wrong, revoked, or rotated more than a day ago. Copy a current key from Settings → API Keys. A 400 means the agent id is not an agent of the key's organization. The SDK says this once per reason and never stops your agent.- The process was killed before the background send ran. A process that calls
os._exit, or is killed, loses what was waiting. A server that stops on a signal should callzhanla.flush()first. - A streamed reply that is never read to the end keeps its request open, so that request is never sent.
zhanla.init was called twiceraises: call it once per process.
Spans with no root. If your model calls arrive but there is no request around them, your code is not running inside an observed function. Each model call then becomes its own trajectory: there is no user message, no reply, and nothing that ties the calls of one request together. Put @zhanla.observe on the function that handles the request, and call the model from inside it.
A streamed reply recorded raw. If the reply shows as the raw body (for example {"token": "Hi"} lines) instead of its text, your stream is in a format the SDK does not read. Use server-sent events with one of the fields listed in Streaming replies (for example data: {"delta": "Hi"}), or have the observed function return the finished text. A list of JSON objects means the stream yields objects: yield text or bytes instead.
Serverless functions
On AWS Lambda, Vercel, Netlify, Google Cloud Functions and Cloud Run, and Azure Functions, the outermost observe sends its request's spans as it ends, before it returns, so a frozen function loses nothing. init(serverless=True) turns this on anywhere else, and serverless=False turns it off.
Eval runs
When Zhanla runs your agent for an eval, it starts it with ZHANLA_TRACE_ENDPOINT and ZHANLA_TRACE_ITEM set, and spans go there instead of to production. There is nothing to configure. A request Zhanla sends to a server you run carries baggage: zhanla.item=<id>, which the middleware above reads.
The SDK never writes to stdout and never stops your agent: a failed export is said once on stderr.
Metadata
Release files for zhanla 0.2.1
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 |
|---|---|---|---|---|
| zhanla-0.2.1.tar.gz | 28.3 kB | Without provenance | Details for zhanla-0.2.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| zhanla-0.2.1-py3-none-any.whl | Python 3 | none | any | Details for zhanla-0.2.1-py3-none-any.whl |
Total release size: 45.4 kB
Release files / zhanla-0.2.1.tar.gz
| Download URL | zhanla-0.2.1.tar.gz |
|---|---|
| Size | 28.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a496ab346f6a9f37f0a56f5f8e882fbc53274899603b016e0106db4711bf55da
|
|
BLAKE2b-256 checksum How to use checksums |
0219e3beaf2f64090876c85980c61727934e8737ccbdfb87ce25761cc76c38e7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.10.2 {"installer":{"name":"uv","version":"0.10.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / zhanla-0.2.1-py3-none-any.whl
| Download URL | zhanla-0.2.1-py3-none-any.whl |
|---|---|
| Size | 17.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
402115bc665c433229bfb6a29422d80108847adc3aa4ae3cf4fc956d9a1696b6
|
|
BLAKE2b-256 checksum How to use checksums |
39f78bd21e1908d6c4cff3501f78cb159f6055103fa8dd31b72bf15a4dbd2dec
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.10.2 {"installer":{"name":"uv","version":"0.10.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for zhanla 0.2.1
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.