Skip to main content

Install

Instrument

instrumentVercelAI takes the ai module’s functions and returns instrumented replacements. Import it once at the top of any module that uses the Vercel AI SDK.

Minimal example — streamText in a Next.js Route Handler

app/api/chat/route.ts

generateObject with a Zod schema

The span captures the structured object as output and any validation error as span.status = error.

What gets captured

  • llm spans around every wrapped call with:
    • input — the last message (or prompt string)
    • output — completed text, or the structured object for generateObject
    • model — the model id (for example gpt-4o-mini)
    • prompt_tokens / completion_tokens
    • latency_ms
  • Stream results hold the span open until the final token arrives; usage is recorded from the resolved result.usage promise.

Known gotchas

  • Next.js Edge runtime is unsupported. Add export const runtime = "nodejs" to any Route Handler or Server Action that calls an instrumented function. The SDK relies on node:async_hooks for trace context propagation, which is not available on Edge.
  • Only wrapped functions are traced. If you import generateText directly from ai elsewhere in your code, those calls bypass TruLayer. Pick one convention per module.
  • Tool calls are recorded on the parent llm span. For a dedicated tool span per tool execution, wrap the tool body with tl.span("tool:name", { spanType: "tool" }).