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

# Vercel AI SDK (v6 and earlier)

> Trace Vercel AI SDK v6 calls (generateText, streamText, generateObject) with OpenInference and send spans to Arize AX for LLM observability.

[Vercel AI SDK](https://github.com/vercel/ai) (3.3+) provides high-level helpers — `generateText`, `streamText`, `generateObject` — for calling LLMs from TypeScript apps. Arize AX captures every AI SDK call by ingesting the SDK's native OpenTelemetry spans through the [`@arizeai/openinference-vercel`](https://github.com/Arize-ai/openinference/tree/main/js/packages/openinference-vercel) span processor.

## 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)
* Vercel AI SDK 3.3 or higher

## 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

Pick the tab for your runtime — both install the same `@arizeai/openinference-vercel` processor and differ only in the OpenTelemetry registration helper.

<Note>
  This guide targets **AI SDK v6 and earlier** (`ai@^6` with `@ai-sdk/openai@^3`). AI SDK v7 reworked how `experimental_telemetry` emits OpenTelemetry spans, so the wiring shown here does not produce spans on `ai@7` — for v7, use the [Vercel AI SDK v7](/ax/integrations/ts-js-agent-frameworks/vercel/vercel-ai-sdk-v7-tracing) guide instead.

  Pin the processor to **`@arizeai/openinference-vercel@^2`** as shown below. The latest major (`@arizeai/openinference-vercel@3`) targets AI SDK v7: it peer-depends on `ai@^7` and `@ai-sdk/otel`, requires Node.js 22+, and ships ESM-only, so it does not work with this v6 setup.
</Note>

<Tabs>
  <Tab title="Node.js">
    ```bash theme={null}
    npm install ai@^6 @ai-sdk/openai@^3 \
      @arizeai/openinference-vercel@^2 \
      @arizeai/openinference-semantic-conventions \
      @opentelemetry/api \
      @opentelemetry/exporter-trace-otlp-proto \
      @opentelemetry/resources \
      @opentelemetry/sdk-trace-node
    ```
  </Tab>

  <Tab title="Next.js">
    ```bash theme={null}
    npm install ai@^6 @ai-sdk/openai@^3 \
      @arizeai/openinference-vercel@^2 \
      @arizeai/openinference-semantic-conventions \
      @vercel/otel \
      @opentelemetry/api \
      @opentelemetry/exporter-trace-otlp-proto
    ```
  </Tab>
</Tabs>

<Note>
  Both runtimes wire the same `OpenInferenceSimpleSpanProcessor` from `@arizeai/openinference-vercel` — they differ only in how OpenTelemetry is registered, shown in the matching tab under [Setup tracing](#setup-tracing). See [Troubleshooting](#troubleshooting) for the version-pinning rules.
</Note>

## Configure credentials

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

## Setup tracing

Pick the tab that matches your runtime. The processor's `spanFilter` and `reparentOrphanedSpans` options control which spans reach Arize and how each trace is rooted — see [Span filter](#span-filter).

<Tabs>
  <Tab title="Node.js">
    ```typescript theme={null}
    // instrumentation.ts
    import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
    import { resourceFromAttributes } from "@opentelemetry/resources";
    import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
    import {
      isOpenInferenceSpan,
      OpenInferenceSimpleSpanProcessor,
    } from "@arizeai/openinference-vercel";
    import { SEMRESATTRS_PROJECT_NAME } from "@arizeai/openinference-semantic-conventions";

    const projectName =
      process.env.ARIZE_PROJECT_NAME ?? "vercel-ai-sdk-v6-tracing-example";

    export const provider = new NodeTracerProvider({
      resource: resourceFromAttributes({
        [SEMRESATTRS_PROJECT_NAME]: projectName,
        model_version: "1.0.0",
      }),
      spanProcessors: [
        new OpenInferenceSimpleSpanProcessor({
          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 ?? "",
            },
          }),
          spanFilter: isOpenInferenceSpan,
          reparentOrphanedSpans: true,
        }),
      ],
    });

    provider.register();

    console.log("Arize AX tracing initialized for Vercel AI SDK.");
    ```
  </Tab>

  <Tab title="Next.js">
    In Next.js, use `@vercel/otel`'s `registerOTel` from `instrumentation.ts`. Put the file where Next.js looks for it: **`src/instrumentation.ts` if your app has a `src/` directory** (e.g. `src/app/…`), otherwise `instrumentation.ts` at the project root (next to `package.json`). A file in the wrong place is silently ignored — Next.js never calls `register()` and no spans are emitted. Next.js automatically calls the exported `register()` function **once on the server, before any request** — so you do **not** create a `NodeTracerProvider` or call `forceFlush()` yourself. Modern Next.js (13.4+) runs this file automatically; you no longer need `experimental.instrumentationHook` in `next.config.js`.

    Install `@vercel/otel` in place of `@opentelemetry/sdk-trace-node`:

    ```bash theme={null}
    npm install @vercel/otel \
      @arizeai/openinference-vercel@^2 \
      @arizeai/openinference-semantic-conventions \
      @opentelemetry/api \
      @opentelemetry/exporter-trace-otlp-proto
    ```

    ```typescript theme={null}
    // instrumentation.ts (project root)
    import { registerOTel } from "@vercel/otel";
    import {
      isOpenInferenceSpan,
      OpenInferenceSimpleSpanProcessor,
    } from "@arizeai/openinference-vercel";
    import { SEMRESATTRS_PROJECT_NAME } from "@arizeai/openinference-semantic-conventions";
    import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";

    export function register() {
      registerOTel({
        serviceName: process.env.ARIZE_PROJECT_NAME ?? "vercel-ai-sdk-v6-tracing-example",
        // Arize AX routes spans to a project by the project-name resource attribute. Without it,
        // the app emits spans but they never appear under your project. `serviceName` alone is
        // not sufficient — set the project-name attribute here just as the Node.js example does.
        attributes: {
          [SEMRESATTRS_PROJECT_NAME]: process.env.ARIZE_PROJECT_NAME ?? "vercel-ai-sdk-v6-tracing-example",
        },
        spanProcessors: [
          new OpenInferenceSimpleSpanProcessor({
            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 ?? "",
              },
            }),
            spanFilter: isOpenInferenceSpan,
            reparentOrphanedSpans: true,
          }),
        ],
      });
    }
    ```

    There's no `provider`/`forceFlush()` to import in your app code — once this file is in place, just enable telemetry at each AI SDK call site (see below).

    <Note>
      **Serverless flushing.** `OpenInferenceSimpleSpanProcessor` exports each span synchronously as it ends, so it does not depend on a process-exit flush — this is what makes it safe on short-lived serverless routes (Vercel functions, edge) where you can't call `forceFlush()`. Keep `SimpleSpanProcessor` rather than `BatchSpanProcessor` in those environments; batching can drop spans when the function freezes between invocations.
    </Note>
  </Tab>
</Tabs>

## Run Vercel AI SDK

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

// Importing instrumentation first ensures tracing is set up before the
// AI SDK is used.
import { provider } from "./instrumentation";

import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";

// `experimental_telemetry: { isEnabled: true }` is the AI SDK opt-in
// flag — without it, no spans are emitted no matter how OTel is wired.
const { text } = await generateText({
  model: openai("gpt-5.5"),
  prompt: "Why is the ocean salty? Answer in two sentences.",
  experimental_telemetry: { isEnabled: true },
});

console.log(text);

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

<Note>
  This is a standalone Node script. In **Next.js**, you don't import `provider` or call `forceFlush()` — the root `instrumentation.ts` registers tracing automatically. Just add `experimental_telemetry: { isEnabled: true }` to the `generateText`/`streamText` calls inside your route handlers or server actions; that opt-in flag is the only app-code change needed.
</Note>

### Expected output

```text wrap theme={null}
Arize AX tracing initialized for Vercel AI SDK.
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 **`vercel-ai-sdk-v6-tracing-example`**.
2. You should see a new trace within \~30 seconds containing an `ai.generateText` parent span wrapping an `ai.generateText.doGenerate` LLM child span (with prompt, response, and token usage attached).
3. If no traces appear, see [Troubleshooting](#troubleshooting).

### Check from the skill, CLI, or SDK

Confirm spans are actually reaching your Arize AX project. Use whichever fits your workflow — the skill and CLI work for any framework; the SDK check is shown for each language.

<Tabs>
  <Tab title="Arize skill (agent)">
    Install the [Arize Skills](https://github.com/Arize-ai/arize-skills) plugin and let your coding agent check for you:

    ```bash theme={null}
    npx skills add Arize-ai/arize-skills
    ```

    Then prompt your agent:

    > Use the `arize-trace` skill to export and analyze recent traces from my project. Confirm spans are arriving, and summarize any errors or latency issues.
  </Tab>

  <Tab title="AX CLI">
    Export recent spans for your project — any rows mean traces are landing:

    ```bash theme={null}
    ax spans export "$ARIZE_PROJECT_NAME" --space "$ARIZE_SPACE_ID" \
      --limit 5 --stdout | jq 'length'
    ```

    A non-zero count confirms spans reached Arize AX. Run `ax auth login` first if you have not authenticated. See the [`ax spans` reference](/api-clients/cli/spans).
  </Tab>

  <Tab title="SDK">
    Query the project's spans and check that at least one came back.

    <CodeGroup>
      ```python Python theme={null}
      import os
      from arize import ArizeClient

      client = ArizeClient(api_key=os.environ["ARIZE_API_KEY"])
      resp = client.spans.list(
          project=os.environ["ARIZE_PROJECT_NAME"],
          space=os.environ["ARIZE_SPACE_ID"],
          limit=5,
      )
      count = len(resp.spans)
      print(
          f"{count} span(s) found" if count else "No spans yet — recheck setup"
      )
      ```

      ```typescript TypeScript theme={null}
      // Reads ARIZE_API_KEY from the environment.
      import { listSpans } from "@arizeai/ax-client";

      const { data: spans } = await listSpans({
        project: process.env.ARIZE_PROJECT_NAME!,
        space: process.env.ARIZE_SPACE_ID!,
        limit: 5,
      });
      const count = spans.length;
      console.log(
        count ? `${count} span(s) found` : "No spans yet — recheck setup",
      );
      ```

      ```go Go theme={null}
      client, err := arize.NewClient(
          arize.Config{APIKey: os.Getenv("ARIZE_API_KEY")},
      )
      if err != nil {
          log.Fatal(err)
      }
      resp, err := client.Spans.List(ctx, spans.ListRequest{
          Project: os.Getenv("ARIZE_PROJECT_NAME"),
          Space:   os.Getenv("ARIZE_SPACE_ID"),
          Limit:   5,
      })
      if err != nil {
          log.Fatal(err)
      }
      fmt.Printf("%d span(s) found\n", len(resp.Spans))
      ```
    </CodeGroup>

    SDK span references: [Python](/api-clients/python/version-8/client-resources/spans) · [TypeScript](/api-clients/typescript/version-1/client-resources/spans) · [Go](/api-clients/go/version-2/client-resources/spans).
  </Tab>
</Tabs>

## Span filter

Other instrumentations registered alongside the AI SDK (`@opentelemetry/instrumentation-http`, `@vercel/otel`, Next.js's built-in tracing) emit `POST` / `GET` spans for every fetch, and the AI SDK's spans nest under those HTTP roots. Two options on the processor control which spans reach Arize and how they're rooted:

* **`spanFilter: isOpenInferenceSpan`** keeps only the AI spans and drops the rest — the raw HTTP/fetch spans those other instrumentations emit.
* **`reparentOrphanedSpans: true`** re-roots any AI span left orphaned when the filter drops its parent, so the highest-level AI SDK span (`ai.generateText`, `ai.streamText`, …) becomes a clean trace root instead of pointing at a parent that was never exported.

```typescript theme={null}
new OpenInferenceSimpleSpanProcessor({
  exporter,
  spanFilter: isOpenInferenceSpan,
  reparentOrphanedSpans: true, // default: false
});
```

## Troubleshooting

* **No traces in Arize AX.** Every AI SDK call needs `experimental_telemetry: { isEnabled: true }` set on it — without that flag, the SDK never emits spans. Also 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.
* **`401` from OpenAI.** Verify `OPENAI_API_KEY` is set and has access to `gpt-5.5`. Swap `openai("gpt-5.5")` for a model your key can call.
* **Process exits before spans flush.** Always `await provider.forceFlush()` (or `provider.shutdown()`) before the process exits, otherwise trailing spans are dropped.
* **Next.js / Vercel runtime.** Use `@vercel/otel`'s `registerOTel(...)` instead of `NodeTracerProvider`, and pin versions: `@vercel/otel@1.x` requires `@opentelemetry/*` `1.x` (`0.1.x` for unstable APIs); `@vercel/otel@2.x` requires `@opentelemetry/*` `2.x` (`0.2.x`). Mismatches surface as silent missing traces.
* **AI SDK spans orphaned on the Traces tab.** Happens when `isOpenInferenceSpan` drops the HTTP root without re-rooting its children. Set `reparentOrphanedSpans: true` on the processor as shown in [Span filter](#span-filter), and confirm `@arizeai/openinference-vercel` is **2.8.0 or later on the v2 line** (`@arizeai/openinference-vercel@^2`). The v3 major targets AI SDK v7 and will not emit spans for this v6 setup.

## Resources

<CardGroup>
  <Card icon="book-open" href="https://sdk.vercel.ai/docs" title="Vercel AI SDK Documentation" horizontal />

  <Card icon="terminal" href="https://github.com/Arize-ai/openinference/tree/main/js/packages/openinference-vercel" title="OpenInference Vercel Span Processor" horizontal />

  <Card icon="github" href="https://github.com/vercel/ai" title="Vercel AI SDK GitHub" horizontal />
</CardGroup>
