---
title: "LangChain"
description: "Learn about using Sentry for LangChain."
url: https://docs.sentry.io/platforms/python/agent-tracing/langchain/
---

# LangChain for Python

This integration connects Sentry with [LangChain](https://github.com/langchain-ai/langchain) in Python.

Once you've installed this SDK, you can use Sentry Agents Tracing, a Sentry dashboard that helps you understand what's going on with your AI requests. Sentry AI Observability will automatically collect information about prompts, tools, tokens, and models. Learn more about the [Agents Dashboard](https://docs.sentry.io/product/agents/dashboards.md).

In SDK `3.x`, and in stream mode in SDK `2.x`, this page's references to "transaction" apply to service spans instead. See [Streamed Spans](https://docs.sentry.io/platforms/python/tracing/streamed-spans.md) for more information.

## [Install](https://docs.sentry.io/platforms/python/agent-tracing/langchain.md#install)

Install `sentry-sdk` from PyPI:

```bash
pip install sentry-sdk
```

*Other available variations of the above snippet: uv*

## [Configure](https://docs.sentry.io/platforms/python/agent-tracing/langchain.md#configure)

If you have the `langchain` package in your dependencies, the LangChain integration will be enabled automatically when you initialize the Sentry SDK.

```python
import sentry_sdk
from sentry_sdk.integrations.langchain import LangchainIntegration
from sentry_sdk.integrations.openai import OpenAIIntegration

sentry_sdk.init(
    dsn="https://<key>@o<orgId>.ingest.sentry.io/<projectId>",
    environment="local",
    traces_sample_rate=1.0,
    # Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected
    data_collection={
        "gen_ai": {"inputs": True, "outputs": True},
    },
    debug=True,
    integrations=[
        LangchainIntegration(),
    ]
)
```

*Other available variations of the above snippet: Anthropic*

## [Verify](https://docs.sentry.io/platforms/python/agent-tracing/langchain.md#verify)

Verify that the integration works by starting a span and invoking an agent. In these examples, we're providing a function tool to roll a die.

```python
import random

from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.tools import tool

@tool
def roll_die(sides: int = 6) -> str:
    """Roll a die with a given number of sides"""
    return f"Rolled a {random.randint(1, sides)} on a {sides}-sided die."

# In SDK 2.x, use sentry_sdk.start_transaction(name="langchain-openai") instead
with sentry_sdk.start_span(name="langchain-openai"):
    model = init_chat_model(
        "gpt-4o-mini",
        model_provider="openai",
        model_kwargs={"stream_options": {"include_usage": True}},
    )
    tools = [roll_die]
    prompt = ChatPromptTemplate.from_messages(
        [
            SystemMessage(
                content="Greet the user and use the die roll tool. Do not terminate before using the tool."
            ),
            HumanMessage(content="{input}"),
            MessagesPlaceholder("agent_scratchpad"),
        ]
    )

    agent = create_openai_functions_agent(model, tools, prompt)
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

    result = agent_executor.invoke(
        {
            "input": "Hello, my name is Alice! Please roll a six-sided die.",
            "chat_history": [],
        }
    )
    print(result)
```

*Other available variations of the above snippet: Anthropic*

After running this script, the resulting data should show up in the `"AI Spans"` tab on the `"Explore" > "Traces"` page on Sentry.io, and in the [Agents Dashboard](https://docs.sentry.io/product/agents/dashboards.md).

It may take a couple of moments for the data to appear in [sentry.io](https://sentry.io).

## [Behavior](https://docs.sentry.io/platforms/python/agent-tracing/langchain.md#behavior)

* The LangChain integration will connect Sentry with all supported LangChain methods automatically.

* All exceptions are reported.

* By default, the SDK records LLM and tokenizer inputs and outputs, such as prompts, messages, and responses. Tool definitions, as well as tool calls passed in the model's invocation parameters, are recorded too; setting `inputs` to `False` in the `gen_ai` key removes them. To control this, use the `gen_ai` key of the [`data_collection` option](https://docs.sentry.io/platforms/python/configuration/options.md#data_collection), which lets you control inputs and outputs separately:

  ```python
  sentry_sdk.init(
      # ...
      data_collection={
          # Record LLM inputs, but not outputs
          "gen_ai": {"inputs": True, "outputs": False},
      },
  )
  ```

  In SDK versions prior to `3.0`, Sentry considers LLM and tokenizer inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. With `send_default_pii=True`, you can exclude them with the integration's `include_prompts=False` option, as shown in the [Options section](https://docs.sentry.io/platforms/python/agent-tracing/langchain.md#options) below.

## [Options](https://docs.sentry.io/platforms/python/agent-tracing/langchain.md#options)

Only available in SDK versions prior to `3.0`. In SDK `3.x`, `LangchainIntegration` doesn't accept any options. Use the `gen_ai` key of the [`data_collection` option](https://docs.sentry.io/platforms/python/configuration/options.md#data_collection) instead.

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

```python
import sentry_sdk
from sentry_sdk.integrations.langchain import LangchainIntegration

sentry_sdk.init(
    # ...
    # Add data like inputs and responses;
    # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
    send_default_pii=True,
    integrations=[
        LangchainIntegration(
            include_prompts=False,  # LLM inputs/outputs will be not sent to Sentry, despite send_default_pii=True
        ),
    ],
)
```

You can pass the following keyword arguments to `LangchainIntegration()`:

* `include_prompts`

  Whether LLM and tokenizer inputs and outputs should be sent to Sentry. If you use the [`data_collection` option](https://docs.sentry.io/platforms/python/configuration/options.md#data_collection), this option is ignored. Use the `gen_ai` key instead.

  Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`.

  The default is `True`.

## [Supported Versions](https://docs.sentry.io/platforms/python/agent-tracing/langchain.md#supported-versions)

* OpenAI: 1.0+
* Python: 3.9+
* langchain: 0.1.0+
