MenuTypeScript

Zhanla offers to add tracing when it sets up your agent. Use this page to do it by hand. The @zhanla/sdk package needs Node 20 or later.

  1. observe: your request handlerthe user's message and the reply
  2. model call
  3. tool call
  4. your observed helper
  5. model call
One request becomes one trajectory

Install and configure

Terminal
npm install @zhanla/sdk

You need two values:

where to get ithow to pass it
API keyZhanla 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 idthe agent's page in the web app: the id at the end of its address, …/agents/<agent id>init({ agent: "<agent id>" })

Trajectories go to Zhanla's hosted ingest by default (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 wrap the function that handles one request in observe: 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 (async) function

JavaScript
import OpenAI from "openai";
import { init, observe, setSessionId, setUserId } from "@zhanla/sdk";

await init({ agent: process.env.ZHANLA_AGENT_ID }); // resolves to the libraries it traced, e.g. [ 'openai' ]
const client = new OpenAI();

const answer = observe(async function answer(message) {
  const completion = await client.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: message }] });
  return completion.choices[0].message.content;
});

async function handleRequest({ sessionId, userId, message }) {
  setSessionId(sessionId); // see "Set the session id" below
  setUserId(userId);
  return answer(message);
}

observe wraps synchronous functions too. A span is named after its function, so give it a named function, or pass { name: "answer" } as the second argument.

In Express or a Node http server, call your observed function from the route handler with the message and send what it returns. If you wrap the handler itself, a Node request is recorded as the body a framework already parsed onto it (Express's req.body), or else its method and path.

A web Response handler (Next.js route, Hono, Bun, Deno…)

JavaScript
const encoder = new TextEncoder();

const reply = observe(async function reply(message) {
  const stream = await client.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: message }], stream: true });
  const body = new ReadableStream({
    async start(controller) {
      for await (const chunk of stream) {
        const delta = chunk.choices[0]?.delta?.content;
        if (delta) controller.enqueue(encoder.encode(`data: ${JSON.stringify({ delta })}\n\n`));
      }
      controller.enqueue(encoder.encode("data: [DONE]\n\n"));
      controller.close();
    },
  });
  return new Response(body, { headers: { "content-type": "text/event-stream" } });
});

export async function POST(request) {
  const { sessionId, userId, message } = await request.json();
  setSessionId(sessionId);
  setUserId(userId);
  return reply(message);
}

Read the body in the handler and pass observe the message. A web Request passed to an observed function is recorded only as its method and path, because its body is a stream that belongs to your handler.

The AI SDK

JavaScript
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

const reply = observe(async function reply(message) {
  const result = streamText({ model: openai("gpt-4o-mini"), prompt: message });
  return result.toUIMessageStreamResponse(); // recorded as the text it streams, not the raw events
});

The AI SDK's own model calls are traced from version 7 on, through its registerTelemetry.

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.

JavaScript
setSessionId(conversationId);   // required in practice
setUserId(userId);              // who is talking
setTags(["beta", "mobile"]);    // a list of strings
setMetadata({ plan: "pro" });   // each value is sent as JSON text; replaces earlier metadata

Each one applies to every span started after it in the same async flow, so concurrent requests keep their own values. Call them in the request handler, before you call your observed function.

Streaming replies

When your observed function returns a stream — a Response with a body, a ReadableStream, an async iterable, or a generator — the request stays open until the stream has been read to the end (or cancelled). 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 strings or bytes, such as toTextStreamResponse(): the chunks joined as they are.
  • Chunks that are not strings or bytes (objects): the list of chunks as JSON.

Check that it works

  1. Set ZHANLA_API_KEY and start your app. console.log(await 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 ends on its own. In a script or test, let the process end on its own or await 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.

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>, and only an observed function that is given the request reads it (there is no middleware in TypeScript). So for Zhanla to run evals against a TypeScript server, wrap the handler that receives the request — export const POST = observe(async function POST(request) { … }) — at the cost of its recorded input being the request's method and path. Production does not need this.

The SDK never writes to stdout and never stops your agent: a failed export is said once on stderr.

Updated Nov 24, 2026. Checked against release candidate b60cdc94. For AI agents: llms.txt.