Skip to main content
Cloudflare AI Chat (@cloudflare/ai-chat) provides a chat-agent base class built on the Cloudflare Agents platform. Braintrust traces each onChatMessage call, capturing the conversation history, LLM turns, tool calls, and errors.
For Cloudflare Workers deployments, use manual instrumentation with wrapCloudflareAIChat(). The --import auto-instrumentation hook only runs under Node, not in the Cloudflare Workers runtime (workerd). See the Cloudflare setup guide for enabling nodejs_compat and flushing traces with ctx.waitUntil().

Setup

Install Braintrust alongside @cloudflare/ai-chat, then set your API keys. Requires @cloudflare/ai-chat v0.9.0 or later.
1

Install packages

2

Set environment variables

.env

Manual instrumentation

Manual instrumentation is the recommended approach for Cloudflare Workers. Wrap the module with wrapCloudflareAIChat() at module scope, then extend the wrapped AIChatAgent class so all instances receive Braintrust tracing.
cloudflare-ai-chat-manual.ts
wrapCloudflareAIChat() accepts the module namespace (import * as aiChat from "@cloudflare/ai-chat") and returns a proxy. Extend the wrapped AIChatAgent export to ensure instances receive Braintrust tracing.Initialize the logger with your env bindings and flush traces with ctx.waitUntil(logger.flush()) inside your Worker’s fetch handler. Deploying to Cloudflare Workers also requires the nodejs_compat compatibility flag and storing BRAINTRUST_API_KEY as a Wrangler secret. See the Cloudflare setup guide for the full deployment configuration.

Auto-instrumentation

Auto-instrumentation patches the SDK at runtime without modifying your application code, but the --import hook only runs under Node (local development or tests), not in the Cloudflare Workers runtime. For a deployed Worker, use manual instrumentation above.
1

Initialize Braintrust and define your agent

2

Run with the import hook

The --import hook only patches the SDK when your code runs under Node, such as local development or tests. It does not run in the Cloudflare Workers runtime (workerd), so a Worker deployed with Wrangler stays uninstrumented. To trace a deployed Worker, use manual instrumentation with wrapCloudflareAIChat().
The auto-instrumentation example uses plain JavaScript so node --import can run the file directly. The Braintrust APIs work the same in TypeScript projects — compile your TypeScript to JavaScript, then run the compiled file with the import hook.
If you’re using a bundler, see Trace LLM calls for plugin and loader setup.

What Braintrust traces

Braintrust captures:
  • Task spans for each AIChatAgent.onChatMessage call, with the conversation history as input and the response message as output.
  • Nested LLM spans for underlying AI SDK calls, with messages, model, and token usage.
  • Tool call spans for any tools invoked during the conversation.
  • Errors captured on the span if the chat turn fails or the stream encounters an error.

Resources