Facet
All docs

Vercel AI SDK — Integration Guide

Step-by-step developer guide for instrumenting a Vercel AI SDK application.

Vercel AI SDK Integration Guide (Developer)

This is the complete, step-by-step guide for a developer instrumenting a real Vercel AI SDK (ai npm package) application with ADG — the first and, today, only Node.js/TypeScript framework adapter. It reflects the adapter as actually validated against a real, independently-maintained open-source application (vercel/ai-chatbot) — not just this project's own hand-built demos — see "Real-world validation" below for what that means in practice.

Everything in this guide is Node.js/TypeScript. If your application is Python, see the equivalent Python framework guides instead — the ontology, env var names, and config precedence are identical field-for-field (only naming convention differs: camelCase here, snake_case in Python).

For the conceptual question "which of my own objects/calls should become a Trace vs. an Activity vs. an Artifact vs. a Resource?" — see the Ontology Mapping Decision Guide first (written against Python examples, but the ontology reasoning is language-neutral). This guide assumes you already know the answer and shows the Vercel-AI-SDK-specific mechanics of acting on it.

If you have no framework at all — plain, direct calls to an OpenAI-shaped client — see §6 below ("No framework: the direct-LLM adapter") instead; it is a separate, smaller adapter in the same package.


1. The one-line integration (true zero-code)

The AI SDK (v7+) ships its own native, global telemetry registration hook, registerTelemetry(), exported from "ai" itself — not an ADG invention. Calling it once, at process startup, observes every generateText/streamText call anywhere in the process afterward, with zero changes to the call sites themselves:

// instrumentation.ts (Next.js loads this automatically before any
// route handler runs)
import { registerTelemetry } from "ai";
import { adgTelemetry } from "@adg/sdk-node/ai-sdk";

export function register() {
  registerTelemetry(adgTelemetry());
}

In a non-Next.js Node.js process, call this once at the top of your entry point, before the first generateText/streamText call.

This is not a theoretical API. Direct inspection of vercel/ai-chatbot (Vercel's own official reference app) confirms its own instrumentation.ts already calls registerTelemetry(new OpenTelemetry()) globally with no per-route wiring — registerTelemetry() is additive and accepts multiple integrations at once, so adgTelemetry() coexists cleanly alongside an already-registered OpenTelemetry integration:

registerTelemetry(new OpenTelemetry(), adgTelemetry());

Per-call override (optional)

A specific call can opt out, or substitute a different integration, via the AI SDK's own per-call experimental_telemetry.integrations option (takes precedence over the globally registered integrations for that one call only):

await generateText({
  model,
  prompt: "...",
  experimental_telemetry: {
    integrations: [adgTelemetry({ application: "special-flow" })],
  },
});

No separate instrument_* call needed

Unlike every Python adapter (instrument_graph, instrument_kernel, instrument_agent, ...), there is no adgTelemetry(...)-wrapping function to call around your own graph/agent object — adgTelemetry() itself is the thing you register. This is the cheapest integration path this platform has built for any framework so far, because the AI SDK already exposes a native, typed Telemetry lifecycle-callback interface — this is why this framework (over LangChain.js/Mastra) was chosen first.

Customizing what gets captured

import { adgTelemetry } from "@adg/sdk-node/ai-sdk";
import { loadArtifactTypeMapping } from "@adg/sdk-node";

const artifactTypeMapper = loadArtifactTypeMapping("./artifact_types.json");

registerTelemetry(adgTelemetry({ artifactTypeMapper }));

See the Artifact Type Mapping guide for the mapping file format (JSON only in this Node SDK today — Python also accepts TOML/YAML) — this classifies your own outcome Artifacts (e.g. "this tool's return value is a DECISION") without ADG ever guessing at your business semantics itself.

No true zero-dependency mode (yet) outside Next.js's instrumentation.ts

@adg/sdk-node/zero-code exists (mirroring Python's ADG_ZERO_CODE=1/ADG_ZERO_CODE_FRAMEWORKS env-var contract, see §7 below) for processes where you cannot add even one line to an instrumentation.ts-equivalent entry point — e.g. an unmodified third-party CLI tool. For any application you do control the entry point of, the one-liner above is simpler and is the documented, intended path.


2. How the AI SDK's telemetry events map onto the ontology

AI SDK event Ontology entity Notes
onStart Trace One per generateText/streamText call. The call's own callId becomes the traceId; runtimeContext (the AI SDK's own native, generic "arbitrary caller-attached data" option) is forwarded verbatim, after redaction, as TraceObservation.customerContext — exactly like LangGraph's config.configurable passthrough in the Python SDK.
onStepStart / onStepEnd Activity One per multi-step tool-calling round (stopWhen: isStepCount(n) et al.).
onLanguageModelCallEnd Resource ("llm"-typed) + Lineage (Activity -USED-> Resource) Emitted at call-end (not call-start), once usage/finishReason is known.
onToolExecutionStart / onToolExecutionEnd Activity (the tool call) + Resource ("tool"-typed) + Artifact (the tool's own return value) + Lineage (USED, PRODUCED) A tool's return value is "produced information" per the ontology's own Artifact definition — the direct analogue of a LangGraph node's new state key, adapted to this framework's call-based (not graph-state-based) shape.
onEnd Artifact (opaque final result payload) + Trace (complete) + Lineage (PRODUCED) artifactType classification (§1's "Customizing what gets captured") is applied only to the call's own functionId (or, as a structural fallback, the most recently completed tool's name) — never the payload itself.
onAbort / onError Trace (failed)

Scope (v1): generateText/streamText (and their ToolLoopAgent equivalent) only. generateObject/embed/rerank/speech/ transcription operations are intentionally out of scope for this first pass — their lifecycle events are structurally different and are simply ignored, never guessed at. A documented, honest gap, not a silent one.

As with every ADG adapter, no framework-provided field's payload is ever guessed at or reclassified as a business concept. The one narrow exception is Artifact Type classification, applied only to a structural name (a tool's own name, or the call's own functionId) via the same generic, overridable keyword heuristic as every other adapter (artifactTypes.ts, ported 1:1 from the Python SDK's artifact_types.py) — classifying by name is ontology-level English vocabulary, not a guess about any one customer's semantics.


3. Lineage emission

Lineage wiring (Activity -USED-> Resource, Activity -PRODUCED-> Artifact) is emitted directly by this adapter, ported 1:1 from the Python SDK's DefaultLineageBuilder rationale — pure structural causation, no business/domain semantics. The platform also derives this edge server-side at read time; emitting it client-side here is a parity/real-time-consumer convenience, not a domain-coverage requirement.


4. Guardrails

The AI SDK has no dedicated guardrail span type of its own (unlike the OpenAI Agents SDK's input_guardrail/output_guardrail). If your application performs its own policy/PII/compliance check, do it as a plain tool (captured automatically as its own Activity/Artifact per §2 above), or — if it sits outside any tool-calling loop entirely (e.g. a direct-LLM-client PII check before/after a chat completion, not a Vercel AI SDK call at all) — use the direct-LLM adapter's recordStep(...) escape hatch (§6 below). See our own internal test applications for a worked, real example: a regex-based SSN check emitting a POLICY_EVALUATION Artifact via recordStep(...), inside the same observe(...) block as the LLM call it guards.


5. Real-world validation: what this adapter was actually proven against

Beyond this project's own hand-built internal test applications, the adapter was validated against a real, independently-maintained open-source application:

vercel/ai-chatbot (Vercel's own official open-source Next.js + AI SDK reference template) — not a live end-to-end deployment (that needs Postgres, Redis, Blob storage, Auth.js, and a live AI Gateway key to boot), but a faithful reproduction of its two load-bearing integration points, confirmed by directly cloning the repo and reading its source:

  1. Its instrumentation.ts already calls registerTelemetry(new OpenTelemetry()) globally with no per-route wiring — direct, real-world confirmation that the zero-code pattern in §1 is not a theoretical API; it is the pattern the ecosystem's own official reference app already uses.
  2. Its app/(chat)/api/chat/route.ts streamText() call shape (a getWeather tool, stopWhen: isStepCount(5) multi-step tool-calling, onAbort/onChunk/onEnd/onError callbacks, no experimental_telemetry passed at all — confirming the real app relies entirely on the global registration from (1)) was reproduced exactly, pinned to [email protected] (the chatbot's own pinned version at validation time), using ai's own MockLanguageModelV3 test utility for a deterministic two-step tool-calling run — no live model or API key required.

This validation deliberately did not vendor the full repository, since unlike the rest of our own test applications (plain importable packages exercisable standalone/offline), ai-chatbot cannot run deterministically with no external dependencies if vendored wholesale.

Result: zero changes to the adapter were needed.


6. No framework: the direct-LLM adapter

If your application makes plain, direct calls to an OpenAI-shaped client (chat.completions.create, embeddings.create) with no orchestration framework at all, use @adg/sdk-node/direct-llm instead — the Node counterpart to Python's adg.adapters.direct_llm:

import { instrumentClient } from "@adg/sdk-node/direct-llm";

const observed = instrumentClient(openaiLikeClient);

const response = await observed.observe(async (o) => {
  return await o.chat.completions.create({
    model: "gpt-4o",
    messages: [{ role: "user", content: userInput }],
  });
});

instrumentClient(...) wraps your existing client instance (itself never modified) so every .chat.completions.create(...)/ .embeddings.create(...) call made inside one observe(...) block is captured as Activities/Resources/Artifacts within a single Trace — auto-opening a Trace for a single bare call made outside observe(...) too. recordStep(...) is the escape hatch for anything the adapter doesn't auto-capture (e.g. a guardrail check — §4 above); it must be called from inside an observe(...) callback (throws otherwise, by design — mirrors Python's own contract).

Streaming responses are reassembled and observed once fully consumed, not per-chunk — matching the Vercel AI SDK adapter's own streaming behavior in spirit.

See our own internal test applications for a complete, 8-scenario worked example (including a real MCP tool-call round trip via @modelcontextprotocol/sdk, and a second, independently-constructed client instance standing in for a second LLM provider).

No zero-code mode exists for the direct-LLM adapter today (unlike the Vercel AI SDK adapter's registerTelemetry() hook) — there is no Node equivalent of Python's sitecustomize_shim monkeypatching openai.OpenAI.__init__. instrumentClient(...) (explicit, one call at your own client construction site) is the only supported integration path today — a documented, honest gap, not a silent one.


7. Zero-code instrumentation (@adg/sdk-node/zero-code)

For the Vercel AI SDK specifically, @adg/sdk-node/zero-code offers a true "zero @adg/sdk-node imports anywhere in the customer's own application code" mode, mirroring Python's ADG_ZERO_CODE=1/ADG_ZERO_CODE_FRAMEWORKS env-var contract exactly:

ADG_ZERO_CODE=1 NODE_OPTIONS="--import=@adg/sdk-node/zero-code" \
    node your-unmodified-app.js

Unlike Python (which must monkeypatch each of its six frameworks' own compile/invoke entry points, since none of them expose a native process-global instrumentation hook), this module needs no monkeypatching at all — it simply calls the same registerTelemetry(adgTelemetry()) from §1 on your behalf, once, triggered by the environment variable instead of code you write. This is why §1's one-liner and this section converge on the exact same underlying mechanism; §7 exists only for processes where you cannot add even one line to your own entry point.

Importing @adg/sdk-node/zero-code never registers anything by itself — only ADG_ZERO_CODE=1 (or an explicit call to enable()) activates it, an explicit opt-in either way, identical to Python's contract.

Currently supports the Vercel AI SDK only (ADG_ZERO_CODE_FRAMEWORKS=vercel_ai, the default and only entry in _PATCHERS today) — the direct-LLM adapter has no zero-code mechanism yet (§6 above).


8. Where to go next

  • The Ontology Mapping Decision Guide — how to decide ontology boundaries for anything the AI SDK's own event stream doesn't already structure for you.
  • The Artifact Type Mapping guide — classifying your agent's own outcome Artifacts.
  • The Field Mapping guide — vocabulary normalization (mapping your own field names onto canonical projection fields).
  • Your Facet platform contact — production transport, monitoring, and scaling guidance.