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

> Trace AI requests through Cloudflare AI Gateway and export Cloudflare Agents traces to Braintrust with OpenTelemetry

Braintrust integrates with Cloudflare in two ways: tracing LLM requests routed through [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/), and exporting traces from [Cloudflare Agents](https://developers.cloudflare.com/agents/) over OpenTelemetry. This page covers both.

<View title="TypeScript" icon="/images/sdk-icons/typescript.svg">
  <h2 id="cloudflare-ai-gateway-typescript">
    Cloudflare AI Gateway
  </h2>

  [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/) provides a unified interface to access multiple AI providers with observability, caching, and rate limiting. Braintrust traces requests routed through Cloudflare AI Gateway across all supported providers.

  <h3 id="setup-typescript">
    Setup
  </h3>

  Install the Braintrust SDK alongside the OpenAI client, then configure your environment variables.

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

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

    <Step title="Set environment variables">
      ```bash title=".env" theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
      OPENAI_API_KEY=<your-provider-api-key>
      CLOUDFLARE_ACCOUNT_ID=<your-cloudflare-account-id>
      CLOUDFLARE_AI_GATEWAY_NAME=<your-gateway-name>
      BRAINTRUST_API_KEY=<your-braintrust-api-key>
      ```
    </Step>
  </Steps>

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

  To trace requests routed through Cloudflare AI Gateway, wrap your OpenAI client with `wrapOpenAI` and point it at the gateway's OpenAI-compatible endpoint.

  <CodeGroup>
    ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
    import { OpenAI } from "openai";
    import { initLogger, wrapOpenAI } from "braintrust";

    // Initialize Braintrust logging
    initLogger({
      projectName: "My Project",
      apiKey: process.env.BRAINTRUST_API_KEY,
    });

    // Create OpenAI client configured for Cloudflare AI Gateway
    const client = wrapOpenAI(
      new OpenAI({
        // OpenAI SDK automatically adds /chat/completions
        baseURL: `https://gateway.ai.cloudflare.com/v1/${process.env.CLOUDFLARE_ACCOUNT_ID}/${process.env.CLOUDFLARE_AI_GATEWAY_NAME}/compat`,
        apiKey: process.env.OPENAI_API_KEY,
      }),
    );

    // This request will be automatically traced by Braintrust
    const result = await client.chat.completions.create({
      model: "openai/gpt-4o",
      messages: [{ role: "user", content: "What is 1+1?" }],
    });

    console.log(result);
    ```
  </CodeGroup>

  <h4 id="switching-providers-typescript">
    Switching providers
  </h4>

  Cloudflare AI Gateway's unified API allows you to easily switch between different AI providers by changing the `model` parameter and corresponding API key. All requests are automatically traced by Braintrust regardless of which provider you use.

  <CodeGroup>
    ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
    import { OpenAI } from "openai";
    import { wrapOpenAI } from "braintrust";

    // Switch to Anthropic
    const client = wrapOpenAI(
      new OpenAI({
        baseURL: `https://gateway.ai.cloudflare.com/v1/${process.env.CLOUDFLARE_ACCOUNT_ID}/${process.env.CLOUDFLARE_AI_GATEWAY_NAME}/compat`,
        apiKey: process.env.ANTHROPIC_API_KEY, // Use Anthropic's API key
      }),
    );

    const result = await client.chat.completions.create({
      model: "anthropic/claude-sonnet-4-5-20250929", // Use Anthropic model
      messages: [{ role: "user", content: "Hello!" }],
    });
    ```
  </CodeGroup>

  Cloudflare AI Gateway supports OpenAI, Anthropic, Google AI Studio, Groq, Mistral, Cohere, Perplexity, DeepSeek, Cerebras, xAI, and Workers AI. See the [Cloudflare documentation](https://developers.cloudflare.com/ai-gateway/usage/chat-completion/) for the complete list.

  <h3 id="ai-gateway-resources-typescript">
    AI Gateway resources
  </h3>

  * [Cloudflare AI Gateway documentation](https://developers.cloudflare.com/ai-gateway/).
  * [Supported providers](https://developers.cloudflare.com/ai-gateway/usage/chat-completion/).
</View>

<View title="Python" icon="/images/sdk-icons/python.svg">
  <h2 id="cloudflare-ai-gateway-python">
    Cloudflare AI Gateway
  </h2>

  [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/) provides a unified interface to access multiple AI providers with observability, caching, and rate limiting. Braintrust traces requests routed through Cloudflare AI Gateway across all supported providers.

  <h3 id="setup-python">
    Setup
  </h3>

  Install the Braintrust SDK alongside the OpenAI client, then configure your environment variables.

  <Steps>
    <Step title="Install packages">
      ```bash theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
      pip install braintrust openai
      ```
    </Step>

    <Step title="Set environment variables">
      ```bash title=".env" theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
      OPENAI_API_KEY=<your-provider-api-key>
      CLOUDFLARE_ACCOUNT_ID=<your-cloudflare-account-id>
      CLOUDFLARE_AI_GATEWAY_NAME=<your-gateway-name>
      BRAINTRUST_API_KEY=<your-braintrust-api-key>
      ```
    </Step>
  </Steps>

  <h3 id="manual-instrumentation-python">
    Manual instrumentation
  </h3>

  To trace requests routed through Cloudflare AI Gateway, wrap your OpenAI client with `wrap_openai` and point it at the gateway's OpenAI-compatible endpoint.

  <CodeGroup>
    ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
    import os
    import openai
    from braintrust import init_logger, wrap_openai

    # Initialize Braintrust logging
    logger = init_logger(project="My Project")

    # Create OpenAI client configured for Cloudflare AI Gateway
    client = wrap_openai(
        # OpenAI client automatically adds /chat/completions
        openai.OpenAI(
            base_url=f"https://gateway.ai.cloudflare.com/v1/{os.getenv('CLOUDFLARE_ACCOUNT_ID')}/{os.getenv('CLOUDFLARE_AI_GATEWAY_NAME')}/compat",
            api_key=os.getenv("OPENAI_API_KEY"),
        )
    )

    # This request will be automatically traced by Braintrust
    result = client.chat.completions.create(
        model="openai/gpt-4o",
        messages=[{"role": "user", "content": "What is 1+1?"}],
    )

    print(result)
    ```
  </CodeGroup>

  <h4 id="switching-providers-python">
    Switching providers
  </h4>

  Cloudflare AI Gateway's unified API allows you to easily switch between different AI providers by changing the `model` parameter and corresponding API key. All requests are automatically traced by Braintrust regardless of which provider you use.

  <CodeGroup>
    ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
    import os
    import openai
    from braintrust import wrap_openai

    # Switch to Anthropic
    client = wrap_openai(
        openai.OpenAI(
            base_url=f"https://gateway.ai.cloudflare.com/v1/{os.getenv('CLOUDFLARE_ACCOUNT_ID')}/{os.getenv('CLOUDFLARE_AI_GATEWAY_NAME')}/compat",
            api_key=os.getenv("ANTHROPIC_API_KEY"),  # Use Anthropic's API key
        )
    )

    result = client.chat.completions.create(
        model="anthropic/claude-sonnet-4-5-20250929",  # Use Anthropic model
        messages=[{"role": "user", "content": "Hello!"}],
    )
    ```
  </CodeGroup>

  Cloudflare AI Gateway supports OpenAI, Anthropic, Google AI Studio, Groq, Mistral, Cohere, Perplexity, DeepSeek, Cerebras, xAI, and Workers AI. See the [Cloudflare documentation](https://developers.cloudflare.com/ai-gateway/usage/chat-completion/) for the complete list.

  <h3 id="ai-gateway-resources-python">
    AI Gateway resources
  </h3>

  * [Cloudflare AI Gateway documentation](https://developers.cloudflare.com/ai-gateway/).
  * [Supported providers](https://developers.cloudflare.com/ai-gateway/usage/chat-completion/).
</View>

## Cloudflare Agents

[Cloudflare Agents](https://developers.cloudflare.com/agents/) instrument each agent run with OpenTelemetry spans that follow the [GenAI semantic conventions](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-spans.md). Because Braintrust ingests OpenTelemetry data, you can export these spans to Braintrust from Cloudflare's [Workers Observability](https://developers.cloudflare.com/workers/observability/exporting-opentelemetry-data/) without adding the Braintrust SDK to your Worker. Braintrust maps the incoming spans to `LLM` and tool spans automatically.

<Steps>
  <Step title="Get your Braintrust credentials">
    Create an API key in **<Icon icon="settings-2" /> Settings > [<Icon icon="key-square" /> API keys](https://www.braintrust.dev/app/~/configuration/org/api-keys)**. Find your project ID using the **Copy project ID** button at the bottom of the project's configuration page.
  </Step>

  <Step title="Add a tracing destination in Cloudflare">
    In the Cloudflare dashboard, go to your account's **Workers Observability** section and add a destination pointing at Braintrust's OpenTelemetry endpoint. Name it `braintrust` so you can reference it in the next step:

    * **Name**: `braintrust`.
    * **OTLP endpoint**: `https://api.braintrust.dev/otel/v1/traces`.
    * **Custom headers**:
      * `Authorization`: `Bearer <BRAINTRUST_API_KEY>`.
      * `x-bt-parent`: `project_id:<BRAINTRUST_PROJECT_ID>`.

    The `x-bt-parent` header sets the project or experiment that receives the traces. For other parent formats and the full attribute mapping, see the [OpenTelemetry integration](/docs/integrations/sdk-integrations/opentelemetry#otlp-configuration).

    <Note>
      If your organization is on the EU data plane, use `https://api-eu.braintrust.dev/otel/v1/traces` instead. Self-hosted deployments should use their stack's API URL followed by `/otel/v1/traces`. See [Data plane region](/docs/admin/organizations#data-plane-region).
    </Note>
  </Step>

  <Step title="Enable trace export in wrangler">
    In your Worker's `wrangler.jsonc`, enable trace export and reference the `braintrust` destination you created by name:

    ```json title="wrangler.jsonc" theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
    {
      "observability": {
        "traces": {
          "enabled": true,
          "destinations": ["braintrust"]
        }
      }
    }
    ```

    Deploy your Worker. Agent runs now appear as traces in Braintrust.
  </Step>
</Steps>

### Cloudflare Agents resources

* [Cloudflare Agents tracing](https://developers.cloudflare.com/agents/runtime/operations/observability/tracing/#exporting-traces).
* [Exporting OpenTelemetry data from Workers](https://developers.cloudflare.com/workers/observability/exporting-opentelemetry-data/).
* [Braintrust OpenTelemetry integration](/docs/integrations/sdk-integrations/opentelemetry).
