# Python

Zhanla offers to add tracing when it sets up your agent. Use this page to do it by hand. The `zhanla` package needs Python 3.10 or later.

**Diagram: One request becomes one trajectory**

```text
observe: your request handler (the user's message and the reply)
  model call
  tool call
  your observed helper
    model call
```

## Install and configure

```sh
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.

## 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 `observe`d helpers — is recorded under it.

### A plain function

```python
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 "Set the session id" below
    zhanla.set_user_id(user_id)
    return answer(message)
```

### An async function

The same decorator. Concurrent requests keep their own session and user.

```python
@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

```python
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

```python
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.

## 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.

```python
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 `observe`d 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.

## Streaming replies

When your `observe`d 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's `choices[0].delta.content`, Anthropic's `delta.text`, `{"type": "text-delta", "delta": …}` (the AI SDK's UI message stream and OpenAI's Responses API), and a plain `delta`, `textDelta`, `text` or `content` string. A `data:` 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 its `0:` 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.

## Check that it works

1. Set `ZHANLA_API_KEY` and start your app. `print(zhanla.init(...))` should list your model client. If stderr says `zhanla: production tracing is off`, the key is not set in that process.
2. Send it one test request, and then a second one with the same session id.
3. 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()`.
4. 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](https://zhanla.vercel.app/docs/sdk/troubleshooting).

## 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.

---

Source: https://zhanla.vercel.app/docs/sdk/python
Updated 2026-11-24. Checked against release candidate b60cdc94.
