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

# OpenAI

> Auto-instrument OpenAI API calls

Automatically capture all OpenAI Chat Completions and Responses API calls.

## Setup

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import traceroot
    from traceroot import Integration

    traceroot.initialize(integrations=[Integration.OPENAI])
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import OpenAI from 'openai';
    import { TraceRoot } from '@traceroot-ai/traceroot';

    TraceRoot.initialize({
      instrumentModules: { openAI: OpenAI },
    });

    const openai = new OpenAI();
    ```
  </Tab>
</Tabs>

## Usage

<Tabs>
  <Tab title="Python">
    Once initialized, all OpenAI calls are captured automatically:

    ```python theme={null}
    import openai

    client = openai.OpenAI()

    # This call is automatically traced
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "What is the capital of France?"},
        ],
    )

    print(response.choices[0].message.content)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import OpenAI from 'openai';

    const openai = new OpenAI();

    // This call is automatically traced
    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      messages: [
        { role: 'system', content: 'You are a helpful assistant.' },
        { role: 'user', content: 'What is the capital of France?' },
      ],
    });

    console.log(response.choices[0].message.content);
    ```
  </Tab>
</Tabs>

## What Gets Captured

| Attribute | Description                                   |
| --------- | --------------------------------------------- |
| Model     | `gpt-4o`, `gpt-4o-mini`, `o3`, etc.           |
| Messages  | Input messages array                          |
| Response  | Completion content                            |
| Tokens    | Prompt, completion, and total tokens          |
| Cost      | Calculated from token usage and model pricing |
| Latency   | Request duration                              |

## Run the example

Clone the repo and run a complete agent end-to-end.

<CardGroup cols={2}>
  <Card title="Python" icon="python" href="https://github.com/traceroot-ai/traceroot/tree/main/examples/python/openai-tool-agent">
    Run the Python example
  </Card>

  <Card title="TypeScript" icon="js" href="https://github.com/traceroot-ai/traceroot/tree/main/examples/typescript/openai">
    Run the TypeScript example
  </Card>
</CardGroup>
