Metadata-Version: 2.5
Name: zhanla
Version: 0.2.1
Summary: Tracing SDK for Zhanla, the terminal agent that tests AI agents with simulated users, finds the failing step and proposes the fix as a draft pull request.
Project-URL: Homepage, https://zhanla.vercel.app
Requires-Python: >=3.10
Requires-Dist: openinference-instrumentation-anthropic
Requires-Dist: openinference-instrumentation-crewai; python_version < '3.13'
Requires-Dist: openinference-instrumentation-langchain
Requires-Dist: openinference-instrumentation-litellm
Requires-Dist: openinference-instrumentation-llama-index
Requires-Dist: openinference-instrumentation-openai
Requires-Dist: openinference-instrumentation-openai-agents
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27
Requires-Dist: opentelemetry-sdk>=1.27
Provides-Extra: test
Requires-Dist: anthropic>=0.40; extra == 'test'
Requires-Dist: fastapi>=0.110; extra == 'test'
Requires-Dist: langchain-openai>=0.3; extra == 'test'
Requires-Dist: openai>=1; extra == 'test'
Requires-Dist: pydantic-ai-slim>=1; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Requires-Dist: uvicorn>=0.29; extra == 'test'
Description-Content-Type: text/markdown

# zhanla

Send your LLM agent's production traffic to [Zhanla](https://zhanla.vercel.app). 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](#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

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

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

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

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

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

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

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

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](#troubleshooting).

## What leaves your app, and how long it is kept

For each request: the input and output of each `observe`d 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`:

```python
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 called `init`.
- `zhanla: could not send trajectories (the export failed)` on stderr, usually after an OpenTelemetry line such as `Failed 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 call `zhanla.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 twice` raises: 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 `observe`d 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](#4-streaming-replies) (for example `data: {"delta": "Hi"}`), or have the `observe`d 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.
