OpenAI

This integration connects Sentry with the OpenAI Python SDK. The integration has been confirmed to work with OpenAI 1.13.3.

Install sentry-sdk from PyPI with the openai extra:

Copied
pip install --upgrade 'sentry-sdk[openai]'

If you have the openai package in your dependencies, the OpenAI integration will be enabled automatically when you initialize the Sentry SDK.

An additional dependency, tiktoken, is required if you want to calculate token usage for streaming chat responses.

Copied
from openai import OpenAI

import sentry_sdk

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    enable_tracing=True,
    traces_sample_rate=1.0,
)

client = OpenAI()

Verify that the integration works by inducing an error. The error and performance transaction should appear in your Sentry project.

Copied
from openai import OpenAI
import sentry_sdk

sentry_sdk.init(...)  # same as above

client = OpenAI(api_key="a bad API key")
with sentry_sdk.start_transaction(op="ai-inference", name="The result of the AI inference"):
    response = (
        client.chat.completions.create(
            model="some-model", messages=[{"role": "system", "content": "hello"}]
        )
        .choices[0]
        .message.content
    )
    print(response)

After running this script, a transaction will be created in the Performance section of sentry.io. Additionally, an error event (about the bad API key) will be sent to sentry.io and will be connected to the transaction.

It takes a couple of moments for the data to appear in sentry.io.

  • The OpenAI integration will connect Sentry with all supported OpenAI methods automatically.

  • All exceptions leading to an OpenAIException are reported.

  • The supported modules are currently chat.completions.create and embeddings.create.

  • Sentry is configured not to consider LLM and tokenizer inputs/outputs as PII. If you want to include them, set send_default_pii=True in the sentry_sdk.init() call. To explicitly exclude prompts despite send_default_pii=True, configure the integration with include_prompts=False like in the Options section.

By adding OpenAIIntegration to your sentry_sdk.init() call explicitly, you can set options for OpenAIIntegration to change its behavior:

Copied
import sentry_sdk
from sentry_sdk.integrations.openai import OpenAIIntegration

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    enable_tracing=True,
    send_default_pii=True,
    traces_sample_rate=1.0,
    integrations = [
        OpenAIIntegration(
            include_prompts=False, # LLM/tokenizer inputs/outputs will be not sent to Sentry, despite send_default_pii=True
        ),
    ],
)

  • OpenAI: 1.0+
  • tiktoken: 0.6.0+
  • Python: 3.9+
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").