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

# LangChain.js

> Trace LangChain.js chains and agents with OpenInference and send spans to Arize AX for LLM observability.

[LangChain.js](https://github.com/langchain-ai/langchainjs) is the JavaScript/TypeScript port of LangChain — a framework for composing LLM calls, tools, and retrieval into chains and agents. Arize AX captures every chain, prompt, tool call, and LLM call by manually instrumenting the `@langchain/core/callbacks/manager` module via the [`@arizeai/openinference-instrumentation-langchain`](https://github.com/Arize-ai/openinference/tree/main/js/packages/openinference-instrumentation-langchain) package.

## Prerequisites

* Node.js 18+
* An Arize AX account ([sign up](https://arize.com/sign-up/))
* An `OPENAI_API_KEY` from the [OpenAI Platform](https://platform.openai.com/api-keys)

## Launch Arize AX

1. Sign in to your [Arize AX account](https://app.arize.com/).
2. From **Space Settings**, copy your **Space ID** and **API Key**. You will set them as `ARIZE_SPACE_ID` and `ARIZE_API_KEY` below.

## Install

```bash theme={null}
npm install @langchain/core @langchain/openai \
  @arizeai/openinference-instrumentation-langchain \
  @arizeai/openinference-semantic-conventions \
  @opentelemetry/api \
  @opentelemetry/exporter-trace-otlp-proto \
  @opentelemetry/instrumentation \
  @opentelemetry/resources \
  @opentelemetry/sdk-trace-base \
  @opentelemetry/sdk-trace-node \
  @opentelemetry/semantic-conventions
```

## Configure credentials

```bash theme={null}
export ARIZE_SPACE_ID="<your-space-id>"
export ARIZE_API_KEY="<your-api-key>"
export ARIZE_PROJECT_NAME="langchain-js-tracing-example"
export OPENAI_API_KEY="<your-openai-api-key>"
```

## Setup tracing

```typescript theme={null}
// instrumentation.ts
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
import {
  SEMRESATTRS_PROJECT_NAME,
} from "@arizeai/openinference-semantic-conventions";
import {
  LangChainInstrumentation,
} from "@arizeai/openinference-instrumentation-langchain";
import * as CallbackManagerModule from "@langchain/core/callbacks/manager";

const projectName =
  process.env.ARIZE_PROJECT_NAME ?? "langchain-js-tracing-example";

export const provider = new NodeTracerProvider({
  resource: resourceFromAttributes({
    [ATTR_SERVICE_NAME]: projectName,
    [SEMRESATTRS_PROJECT_NAME]: projectName,
  }),
  spanProcessors: [
    new SimpleSpanProcessor(
      new OTLPTraceExporter({
        url: "https://otlp.arize.com/v1/traces",
        headers: {
          "arize-space-id": process.env.ARIZE_SPACE_ID ?? "",
          "arize-api-key": process.env.ARIZE_API_KEY ?? "",
        },
      }),
    ),
  ],
});

provider.register();

const instrumentation = new LangChainInstrumentation();
instrumentation.manuallyInstrument(CallbackManagerModule);

console.log("Arize AX tracing initialized for LangChain.js.");
```

## Run LangChain.js

```typescript theme={null}
// example.ts

// Importing instrumentation first ensures tracing is set up before any
// LangChain client is created.
import { provider } from "./instrumentation";

import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";

// ChatOpenAI reads OPENAI_API_KEY from the environment.
const model = new ChatOpenAI({ model: "gpt-5" });
const prompt = ChatPromptTemplate.fromTemplate(
  "Answer the question concisely.\nQuestion: {question}\nAnswer:",
);
const chain = prompt.pipe(model).pipe(new StringOutputParser());

const result = await chain.invoke({
  question: "Why is the ocean salty? Answer in two sentences.",
});

console.log(result);

// Flush any pending spans before the process exits.
await provider.forceFlush();
```

### Expected output

```text wrap theme={null}
Arize AX tracing initialized for LangChain.js.
The ocean is salty because rivers continuously dissolve mineral salts from rocks and soil and carry them to the sea, where they accumulate over millions of years. Water leaves the ocean through evaporation but the salts remain, steadily concentrating until reaching today's roughly 3.5% salinity.
```

## Verify in Arize AX

1. Open your Arize AX space and select project **`langchain-js-tracing-example`**.
2. You should see a new trace within \~30 seconds containing a `RunnableSequence` parent span (CHAIN) wrapping `ChatPromptTemplate` (CHAIN), `ChatOpenAI` (LLM, model `gpt-5`), and `StrOutputParser` (CHAIN) child spans, with the prompt, response, and token usage attached to the LLM span.
3. If no traces appear, see [Troubleshooting](#troubleshooting).

## Span filter

The basic setup above exports every span the tracer provider receives. When LangChain runs alongside other instrumentations (`@opentelemetry/instrumentation-http`, Next.js's built-in tracing, framework HTTP middleware), those instrumentations emit `POST` / `GET` spans for every fetch, and the LangChain spans nest under those HTTP roots. OpenInference-tagged spans carry an `openinference.span.kind` attribute that the LangChain instrumentor sets — checking for it is enough to drop non-OpenInference spans. Swap `SimpleSpanProcessor` in `instrumentation.ts` for a filtering subclass:

```typescript theme={null}
import {
  ReadableSpan,
  SimpleSpanProcessor,
} from "@opentelemetry/sdk-trace-base";
import { SemanticConventions } from "@arizeai/openinference-semantic-conventions";

function isOpenInferenceSpan(span: ReadableSpan): boolean {
  return (
    typeof span.attributes[SemanticConventions.OPENINFERENCE_SPAN_KIND] ===
    "string"
  );
}

class OpenInferenceFilteringSpanProcessor extends SimpleSpanProcessor {
  onEnd(span: ReadableSpan): void {
    if (!isOpenInferenceSpan(span)) return;
    super.onEnd(span);
  }
}

// then in spanProcessors:
new OpenInferenceFilteringSpanProcessor(
  new OTLPTraceExporter({ /* ... */ }),
);
```

The trade-off: filtering removes the HTTP root spans, which orphans the surviving LangChain spans on the **Traces** tab (no parent to anchor them) — they remain visible on the **Spans** tab. If you also need a clean trace tree on the Traces tab, swap the filter for a span processor that promotes the first LangChain span to root by clearing its parent ID:

```typescript theme={null}
// root-aware-processor.ts
import { Context } from "@opentelemetry/api";
import {
  BatchSpanProcessor,
  ReadableSpan,
  Span,
  SpanExporter,
} from "@opentelemetry/sdk-trace-base";
import { getSession } from "@arizeai/openinference-core";
import {
  SemanticConventions,
  SESSION_ID,
} from "@arizeai/openinference-semantic-conventions";
import { LRUCache } from "lru-cache";

// Top-level LangChain / LangGraph runnable names. `LangGraph` is the
// `lc_name()` of a compiled Pregel graph (returned by `createReactAgent`
// and friends), `RunnableSequence` is the typical chain root for
// `prompt.pipe(model).pipe(parser)`-style chains, and `AgentExecutor`
// covers legacy LangChain agents. Match on the first whitespace-delimited
// token so suffixed run names (e.g. `RunnableSequence my-chain`) still hit.
const ROOT_OI_SPAN_PREFIXES = [
  "LangGraph",
  "RunnableSequence",
  "AgentExecutor",
];

function isRootOISpanByName(spanName: string): boolean {
  const head = spanName.split(" ")[0];
  return ROOT_OI_SPAN_PREFIXES.some(
    (prefix) => head === prefix || head.startsWith(prefix + " "),
  );
}

function isOpenInferenceSpan(span: ReadableSpan): boolean {
  return (
    typeof span.attributes[SemanticConventions.OPENINFERENCE_SPAN_KIND] ===
    "string"
  );
}

interface RootAwareConfig {
  exporter: SpanExporter;
  /** LRU size for tracking which traces have a promoted root. */
  cacheSize?: number;
}

/**
 * Filters non-OpenInference spans (HTTP, fetch, etc.) and promotes the
 * first LangChain span in each trace to root by clearing its parent IDs.
 * Also propagates session ids from context onto every emitted span.
 */
export class RootAwareOpenInferenceProcessor extends BatchSpanProcessor {
  private traceIds: LRUCache<string, boolean>;

  constructor(config: RootAwareConfig) {
    super(config.exporter);
    this.traceIds = new LRUCache({ max: config.cacheSize ?? 1000 });
  }

  onStart(span: Span, parentContext: Context): void {
    const session = getSession(parentContext);
    if (session?.sessionId) {
      span.setAttribute(SESSION_ID, session.sessionId);
    }

    const traceId = span.spanContext().traceId;
    if (
      isRootOISpanByName(span.name) &&
      !this.traceIds.has(traceId)
    ) {
      // parentSpanId is readonly on the public Span type; cast to clear.
      (span as unknown as { parentSpanId?: string }).parentSpanId =
        undefined;
      (span as unknown as { parentSpanContext?: unknown })
        .parentSpanContext = undefined;
      this.traceIds.set(traceId, true);
    }

    super.onStart(span, parentContext);
  }

  onEnd(span: ReadableSpan): void {
    if (!isOpenInferenceSpan(span)) return;
    super.onEnd(span);
  }

  shutdown(): Promise<void> {
    this.traceIds.clear();
    return super.shutdown();
  }
}
```

Wire it in by replacing the `OpenInferenceFilteringSpanProcessor` in `instrumentation.ts`:

```typescript theme={null}
import { RootAwareOpenInferenceProcessor } from "./root-aware-processor";

spanProcessors: [
  new RootAwareOpenInferenceProcessor({
    exporter: new OTLPTraceExporter({
      url: "https://otlp.arize.com/v1/traces",
      headers: {
        "arize-space-id": process.env.ARIZE_SPACE_ID ?? "",
        "arize-api-key": process.env.ARIZE_API_KEY ?? "",
      },
    }),
  }),
],
```

The recipe needs two additional dependencies: `npm install @arizeai/openinference-core lru-cache`.

## Troubleshooting

* **No traces in Arize AX.** Confirm `ARIZE_SPACE_ID` and `ARIZE_API_KEY` are set in the same shell that runs `example.ts`. Enable OpenTelemetry debug logs with `export OTEL_LOG_LEVEL=debug` and re-run.
* **LangChain spans missing but other spans present.** `instrumentation.manuallyInstrument(CallbackManagerModule)` must run before any code creates a LangChain client. Make sure `import { provider } from "./instrumentation"` (or a side-effect-only `import "./instrumentation"`) is the first import in your entry point.
* **`401` from OpenAI.** Verify `OPENAI_API_KEY` is set and has access to `gpt-5`. Swap for a model your key can call.
* **Process exits before spans flush.** Spans are exported asynchronously; always `await provider.forceFlush()` (or `provider.shutdown()`) before the process exits to avoid losing trailing spans.
* **LangChain spans orphaned on the Traces tab.** Expected when `isOpenInferenceSpan` is the only filter — see [Span filter](#span-filter) above for the `RootAwareOpenInferenceProcessor` recipe that promotes the first LangChain span to root.

### Version compatibility

Instrumentation `>=1.0.0` supports both attribute masking and context attribute propagation. The matrix below tracks instrumentor support across LangChain core releases:

| Instrumentation Version | LangChain ^0.3.0 | LangChain ^0.2.0 | LangChain ^0.1.0 |
| ----------------------- | ---------------- | ---------------- | ---------------- |
| `>=1.0.0`               | Yes              | Yes              | Yes              |
| `>=0.2.0`               | No               | Yes              | Yes              |
| `>=0.1.0`               | No               | No               | Yes              |

## Resources

<CardGroup>
  <Card icon="book-open" href="https://js.langchain.com/docs/" title="LangChain.js Documentation" horizontal />

  <Card icon="terminal" href="https://github.com/Arize-ai/openinference/tree/main/js/packages/openinference-instrumentation-langchain" title="OpenInference LangChain Instrumentor (JS/TS)" horizontal />

  <Card icon="github" href="https://github.com/langchain-ai/langchainjs" title="LangChain.js GitHub" horizontal />
</CardGroup>
