> ## Documentation Index
> Fetch the complete documentation index at: https://braintrust.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Cloudflare AI Chat

> Trace Cloudflare AI Chat agent conversations in Braintrust to debug chat turns, LLM calls, tool use, and errors

If you are a coding agent, prefer the Braintrust [`bt` CLI](/docs/reference/cli/quickstart) for repeatable, scriptable work: running evals, instrumenting code, querying logs, syncing data, managing functions, and configuring coding agents. Use the MCP server for reasoning over Braintrust data in conversation, such as ad-hoc lookups and exploration from your IDE.

[Cloudflare AI Chat](https://developers.cloudflare.com/agents/) (`@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.

<Note>
  For Cloudflare Workers deployments, use [manual instrumentation](#manual-instrumentation-typescript) with `wrapCloudflareAIChat()`. The `--import` auto-instrumentation hook only runs under Node, not in the Cloudflare Workers runtime (`workerd`). See the [Cloudflare setup guide](/docs/sdks/typescript/install-and-instrument#cloudflare) for enabling `nodejs_compat` and flushing traces with `ctx.waitUntil()`.
</Note>

<View title="TypeScript" icon="https://img.logo.dev/typescriptlang.org?token=pk_BdcHD9e5SCW3j1rnJkNyMQ">
  <h2 id="setup-typescript">
    Setup
  </h2>

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

  <Steps>
    <Step title="Install packages">
      <CodeGroup>
        ```bash pnpm theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
        pnpm add braintrust @cloudflare/ai-chat
        ```

        ```bash npm theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
        npm install braintrust @cloudflare/ai-chat
        ```
      </CodeGroup>
    </Step>

    <Step title="Set environment variables">
      ```bash title=".env" theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
      BRAINTRUST_API_KEY=<your-braintrust-api-key>

      # For organizations on the EU data plane, use https://api-eu.braintrust.dev
      # For self-hosted deployments, use your data plane URL
      # BRAINTRUST_API_URL=<your-braintrust-api-url>
      ```
    </Step>
  </Steps>

  <h2 id="manual-instrumentation-typescript">
    Manual instrumentation
  </h2>

  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.

  ```typescript title="cloudflare-ai-chat-manual.ts" theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
  import { initLogger, wrapCloudflareAIChat } from "braintrust";
  import * as aiChat from "@cloudflare/ai-chat";

  const { AIChatAgent } = wrapCloudflareAIChat(aiChat);

  export class MyAgent extends AIChatAgent {
    async onChatMessage(onFinish) {
      // Your chat handling logic here
    }
  }
  ```

  `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](/docs/sdks/typescript/install-and-instrument#cloudflare) for the full deployment configuration.

  <h2 id="auto-instrumentation-typescript">
    Auto-instrumentation
  </h2>

  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.

  <Steps>
    <Step title="Initialize Braintrust and define your agent">
      <CodeGroup>
        ```javascript title="cloudflare-ai-chat-auto.js" theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
        import { initLogger } from "braintrust";
        import { AIChatAgent } from "@cloudflare/ai-chat";

        initLogger({
          projectName: "cloudflare-ai-chat-example", // Replace with your project name
          apiKey: process.env.BRAINTRUST_API_KEY,
        });

        export class MyAgent extends AIChatAgent {
          async onChatMessage(onFinish) {
            // Your chat handling logic here
          }
        }
        ```
      </CodeGroup>
    </Step>

    <Step title="Run with the import hook">
      ```bash theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
      node --import braintrust/hook.mjs cloudflare-ai-chat-auto.js
      ```

      <Warning>
        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](#manual-instrumentation-typescript) with `wrapCloudflareAIChat()`.
      </Warning>

      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.

      <Note>
        If you're using a bundler, see [Trace LLM calls](/docs/instrument/trace-llm-calls#auto-instrumentation) for plugin and loader setup.
      </Note>
    </Step>
  </Steps>

  <h2 id="what-traced-typescript">
    What Braintrust traces
  </h2>

  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.

  <h2 id="resources-typescript">
    Resources
  </h2>

  * [Cloudflare Agents documentation](https://developers.cloudflare.com/agents/)
  * [`@cloudflare/ai-chat` on npm](https://www.npmjs.com/package/@cloudflare/ai-chat)
  * [Trace LLM calls](/docs/instrument/trace-llm-calls)
</View>
