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

# LangChain

> Build LLM applications with LangChain and Adaline.

# LangChain

Use the Adaline LangChain callback handler to send LangChain runs into Adaline without changing the chain logic itself. The integration attaches at the callback layer and maps model, chain, tool, and retriever events into Adaline traces and spans.

## Prerequisites

Before you start, make sure you have:

* An [Adaline account](https://app.adaline.ai/sign-up?utm_source=adaline.ai).
* A **workspace API key** — create one under **Settings → API keys**.
* Your **project ID** — copy it from **Monitor → Copy Project ID**.

See [Integrate your AI Agent](/docs/get-started/integrate-your-ai-agent) for a full walkthrough.

Set both as environment variables before running the examples on this page:

```bash theme={null}
export ADALINE_API_KEY="your-api-key"
export ADALINE_PROJECT_ID="your-project-id"
```

## Install

<Tabs>
  <Tab title="TypeScript">
    ```bash theme={null}
    npm install @adaline/client @adaline/langchain @langchain/core @langchain/openai
    ```
  </Tab>

  <Tab title="Python">
    ```bash theme={null}
    pip install adaline-client adaline-langchain langchain-core langchain-openai
    ```
  </Tab>
</Tabs>

## Initialize Adaline

Create an Adaline client, then initialize a monitor for the target project.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    import { Adaline } from "@adaline/client";

    const adaline = new Adaline({ apiKey: process.env.ADALINE_API_KEY! });
    const monitor = adaline.initMonitor({ projectId: process.env.ADALINE_PROJECT_ID! });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import os

    from adaline import Adaline

    adaline = Adaline(api_key=os.environ["ADALINE_API_KEY"])
    monitor = adaline.init_monitor(project_id=os.environ["ADALINE_PROJECT_ID"])
    ```
  </Tab>
</Tabs>

<Note>
  For production guidance — buffering, batching, retries, serverless flushing, and graceful shutdown — see [Instrument with the Adaline SDK](/docs/instrument/with-adaline-sdks).
</Note>

## Attach the LangChain callback handler

Add the Adaline callback handler to the LangChain call path. Your application code can keep using the same chain, model, tool, and retriever APIs.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    import { AdalineLangChainCallbackHandler } from "@adaline/langchain";

    const handler = new AdalineLangChainCallbackHandler({ monitor });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from adaline_langchain import AdalineLangChainCallbackHandler

    handler = AdalineLangChainCallbackHandler(monitor=monitor)
    ```
  </Tab>
</Tabs>

## Basic example

This example keeps the integration intentionally small: one `ChatOpenAI` call with the Adaline callback handler attached.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    import { ChatOpenAI } from "@langchain/openai";
    import { AdalineLangChainCallbackHandler } from "@adaline/langchain";

    const handler = new AdalineLangChainCallbackHandler({ monitor });

    const model = new ChatOpenAI({
      modelName: "gpt-4o-mini",
      maxTokens: 20,
      callbacks: [handler],
    });

    const result = await model.invoke("Say hello in one word.");
    await monitor.flush();
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import asyncio

    from langchain_openai import ChatOpenAI
    from adaline_langchain import AdalineLangChainCallbackHandler

    async def main():
        handler = AdalineLangChainCallbackHandler(monitor=monitor)
        llm = ChatOpenAI(model="gpt-4o-mini", max_tokens=20, callbacks=[handler])
        result = await llm.ainvoke("Say hello in one word.")
        await monitor.flush()


    asyncio.run(main())
    ```
  </Tab>
</Tabs>

## Use an existing parent trace or span

If you already created a trace or span in Adaline, you can attach LangChain work underneath it instead of letting the handler create a new root trace.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    const parentTrace = monitor.logTrace({
      name: "langchain-run",
      referenceId: "langchain-run-1",
    });

    const handler = new AdalineLangChainCallbackHandler({
      monitor,
      parentTrace,
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    parent_trace = monitor.log_trace(
        name="langchain-run",
        reference_id="langchain-run-1",
    )

    handler = AdalineLangChainCallbackHandler(
        monitor=monitor,
        parent_trace=parent_trace,
    )
    ```
  </Tab>
</Tabs>

Pass either `parentTrace` / `parent_trace` or `parentSpan` / `parent_span`, but not both.

## Global handler

LangChain can also use a global Adaline handler instead of passing callbacks manually on every invocation.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    import {
      AdalineLangChainCallbackHandler,
      setGlobalHandler,
    } from "@adaline/langchain";

    setGlobalHandler(new AdalineLangChainCallbackHandler({ monitor }));
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from adaline_langchain import AdalineLangChainCallbackHandler, set_global_handler

    set_global_handler(AdalineLangChainCallbackHandler(monitor=monitor))
    ```
  </Tab>
</Tabs>

Use `clearGlobalHandler()` or `clear_global_handler()` to remove it.

## What the handler captures

The callback handler is designed to map LangChain run trees into Adaline observations, including:

* chain runs
* chat model and LLM runs
* tool runs
* retriever runs
* nested child runs under a shared parent run

This page focuses on how to wire the handler in. The exact span shape depends on which LangChain components your application uses and which callbacks they emit.

## Next steps

<CardGroup cols={2}>
  <Card title="Instrument with the Adaline SDK" icon="code" href="/docs/instrument/with-adaline-sdks">
    Monitor lifecycle, buffering and batching, retries, serverless flushing, and graceful shutdown.
  </Card>

  <Card title="SDK reference" icon="braces" href="/docs/reference/sdk/v2/overview">
    Full class and type reference for the TypeScript and Python SDKs.
  </Card>

  <Card title="All integrations" icon="layout-grid" href="/docs/integrations/introduction">
    Browse every framework and AI-provider integration Adaline supports.
  </Card>

  <Card title="View your logs" icon="line-chart" href="https://app.adaline.ai">
    Open Adaline to see traces and spans land in your project.
  </Card>
</CardGroup>
