Vercel AI SDK
Use Confident AI for LLM observability and evals for Vercel AI SDK on typescript
The AI SDK by Vercel is a powerful TypeScript framework that allows you to use various LLM providers and models for AI-based applications. Confident AI allows you to trace and evaluate AI SDK based LLM applications in just a few lines of code.
Choose Your Integration Mode
DeepEval supports two ways to integrate tracing with the Vercel AI SDK.
If you are not already using OpenTelemetry, simply use configureAiSdkTracing and pass the tracer to the AI SDK telemetry:
import { generateText } from "ai";
import { configureAiSdkTracing } from "deepeval";
const tracer = configureAiSdkTracing();
await generateText({
model: "openai/gpt-4o",
prompt: "Explain how neural networks work",
experimental_telemetry: {
isEnabled: true,
tracer: tracer,
},
});This is the easiest way to enable tracing.
If your application already uses OpenTelemetry (for example in Next.js or a custom observability stack), you should attach DeepEval processors to your existing tracer provider instead of creating a new one.
Add the deepeval span processor in your instrumentation.ts file as shown below:
import { registerOTel } from "@vercel/otel";
import { createDeepEvalProcessors } from "deepeval/integrations/ai-sdk";
const deepevalProcessors = createDeepEvalProcessors();
export function register() {
registerOTel({
serviceName: "deepeval-next-sandbox",
spanProcessors: [
// Your existing processors
...deepevalProcessors,
],
});
}import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { createDeepEvalProcessors } from "deepeval/integrations/ai-sdk";
const deepevalProcessors = createDeepEvalProcessors();
const tracerProvider = new NodeTracerProvider({
spanProcessors: [
// Existing processors
...deepevalProcessors
],
});
tracerProvider.register();Tracing Quickstart
Install Dependencies
Run the following command to install the required packages:
npm install ai deepevalConfigure AI SDK
Use DeepEval's
configureAiSdkTracingto trace LLM operations.import { generateText } from "ai"; import { configureAiSdkTracing } from "deepeval"; const tracer = configureAiSdkTracing(); const { text } = await generateText({ model: "openai/gpt-4o", prompt: "How to make the best coffee?", experimental_telemetry: { isEnabled: true, tracer: tracer, }, }); console.log(text);import { streamText } from "ai"; import { configureAiSdkTracing } from "deepeval"; const tracer = configureAiSdkTracing(); const result = streamText({ model: "openai/gpt-4o", prompt: 'Invent a new holiday and describe its traditions.', experimental_telemetry: { isEnabled: true, tracer: tracer, }, }); for await (const textPart of result.textStream) { console.log(textPart); }import { generateText, tool } from "ai"; import { configureAiSdkTracing } from "deepeval"; import { z } from "zod"; const tracer = configureAiSdkTracing(); const result = await generateText({ model: "openai/gpt-4o", tools: { weather: tool({ description: 'Get the weather in a location', parameters: z.object({ location: z.string().describe('The location to get the weather for'), }), execute: async ({ location }) => ({ location, temperature: 72 + Math.floor(Math.random() * 21) - 10, }), }), }, prompt: 'What is the weather in San Francisco?', experimental_telemetry: { isEnabled: true, tracer: tracer, }, }); console.log(result);import { generateObject } from "ai"; import { configureAiSdkTracing } from "deepeval"; import { z } from "zod"; const tracer = configureAiSdkTracing(); const { object } = await generateObject({ model: "openai/gpt-4o", schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array( z.object({ name: z.string(), amount: z.string() }), ), steps: z.array(z.string()), }), }), prompt: 'Generate a lasagna recipe.', experimental_telemetry: { isEnabled: true, tracer: tracer, }, }); console.log(object);import { embed } from "ai"; import { configureAiSdkTracing } from "deepeval"; const tracer = configureAiSdkTracing(); const { embedding } = await embed({ model: 'openai/text-embedding-3-small', value: 'sunny day at the beach', experimental_telemetry: { isEnabled: true, tracer: tracer, }, }); console.log(embedding);import { generateText } from "ai"; const { text } = await generateText({ model: "openai/gpt-4o", prompt: "How to make the best coffee?", experimental_telemetry: { isEnabled: true, }, }); console.log(text);import { streamText } from "ai"; const result = streamText({ model: "openai/gpt-4o", prompt: 'Invent a new holiday and describe its traditions.', experimental_telemetry: { isEnabled: true, }, }); for await (const textPart of result.textStream) { console.log(textPart); }import { generateText, tool } from "ai"; import { z } from "zod"; const result = await generateText({ model: "openai/gpt-4o", tools: { weather: tool({ description: 'Get the weather in a location', parameters: z.object({ location: z.string().describe('The location to get the weather for'), }), execute: async ({ location }) => ({ location, temperature: 72 + Math.floor(Math.random() * 21) - 10, }), }), }, prompt: 'What is the weather in San Francisco?', experimental_telemetry: { isEnabled: true, }, }); console.log(result);import { generateObject } from "ai"; import { z } from "zod"; const { object } = await generateObject({ model: "openai/gpt-4o", schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array( z.object({ name: z.string(), amount: z.string() }), ), steps: z.array(z.string()), }), }), prompt: 'Generate a lasagna recipe.', experimental_telemetry: { isEnabled: true, }, }); console.log(object);import { embed } from "ai"; const { embedding } = await embed({ model: 'openai/text-embedding-3-small', value: 'sunny day at the beach', experimental_telemetry: { isEnabled: true, }, }); console.log(embedding);Run AI SDK Generation
Run your LLM application. You can directly view the traces on Confident AI's traces page inside the observatory.
Advanced Usage
Configuration options
configureAiSdkTracing accepts an optional options object to control tracing behavior:
import { configureAiSdkTracing } from "deepeval";
const tracer = configureAiSdkTracing({
apiKey: "your-confident-api-key", // defaults to CONFIDENT_API_KEY env var
environment: "production", // defaults to "development"
name: "my-ai-app", // optional default trace name
traceMetricCollection: "my-metrics", // optional default metric collection for all traces
debug: false, // set true to enable verbose logging
});View configureAiSdkTracing Options
apiKeystring
Your Confident AI API key. Defaults to the CONFIDENT_API_KEY environment variable.
environmentstring
The deployment environment label attached to all traces (e.g. "production", "staging"). Defaults to "development". Can also be set via the CONFIDENT_TRACE_ENVIRONMENT environment variable.
namestring
A default name applied to every trace created by this tracer. Can be overridden per-trace using setTracingContext or via ai.telemetry.metadata.traceName.
traceMetricCollectionstring
A default metric collection applied to every trace for online evaluation. Can be overridden per-trace using setTracingContext or via ai.telemetry.metadata.traceMetricCollection.
otelEndpointstring
Custom OTLP endpoint URL. Defaults to https://otel.confident-ai.com. Use https://eu.otel.confident-ai.com for the EU region.
debugboolean
When true, logs tracing configuration details and flush events to the console. Defaults to false.
Logging prompts
If you are managing prompts on Confident AI and wish to log them, pass your Prompt object to the llmSpanContext using the setTracingContext function:
import { generateText } from "ai";
import { configureAiSdkTracing, Prompt } from "deepeval";
import { setTracingContext } from "deepeval/tracing";
const prompt = new Prompt({ alias: "PROMPT_ALIAS" });
prompt.pull();
const tracer = configureAiSdkTracing();
await setTracingContext(
{
llmSpanContext: {
prompt: prompt
}
},
async () => {
const { text } = await generateText({
model: "openai/gpt-4o",
prompt: "How to make the best coffee?",
experimental_telemetry: {
isEnabled: true,
tracer: tracer,
},
});
console.log(text);
}
);import { generateText } from "ai";
import { Prompt } from "deepeval";
const prompt = new Prompt({ alias: "PROMPT_ALIAS" });
prompt.pull();
const { text } = await generateText({
model: "openai/gpt-4o",
prompt: "How to make the best coffee?",
experimental_telemetry: {
isEnabled: true,
metadata: {
promptAlias: prompt.alias,
promptCommitHash: prompt.hash
}
},
});
console.log(text);Setting trace attributes
Confident AI's LLM tracing advanced features provide teams with the ability to set certain attributes for each trace when invoking your AI SDK applications.
For example, threadId and userId are used to group related traces together, and are useful for chat apps, agents, or any multi-turn interactions. You can learn more about threads here.
You can set these attributes using the setTracingContext function from deepeval/tracing:
import { generateText } from "ai";
import { configureAiSdkTracing } from "deepeval";
import { setTracingContext } from "deepeval/tracing";
const tracer = configureAiSdkTracing();
await setTracingContext(
{
threadId: "thread-123",
userId: "user-456",
testCaseId: "tc-789", // optional: link trace to a test case
turnId: "turn-1", // optional: identify a specific turn in a conversation
},
async () => {
const { text } = await generateText({
model: "openai/gpt-4o",
prompt: "How to make the best coffee?",
experimental_telemetry: {
isEnabled: true,
tracer: tracer,
},
});
console.log(text);
}
);import { generateText } from "ai";
const { text } = await generateText({
model: "openai/gpt-4o",
prompt: "How to make the best coffee?",
experimental_telemetry: {
isEnabled: true,
metadata: {
threadId: "thread-123",
userId: "user-456",
traceName: "Trace name here",
testCaseId: "tc-789", // optional: link trace to a test case
turnId: "turn-1", // optional: identify a specific turn in a conversation
}
},
});
console.log(text);View Trace Attributes
namestring
The name of the trace. Learn more.
tagsstring[]
Tags are string labels that help you group related traces. Learn more.
metadataRecord<string, any>
Attach any metadata to the trace. Learn more.
threadIdstring
Supply the thread or conversation ID to view and evaluate conversations. Learn more.
userIdstring
Supply the user ID to enable user analytics. Learn more.
testCaseIdstring
Link this trace to an existing test case on Confident AI for offline evaluation workflows.
turnIdstring
Identifies a specific turn within a multi-turn conversation thread. Used together with threadId to track individual turns.
Evals Usage
Online evals
You can run online evals on your AI SDK application by setting a metricCollection which will run evaluations on all incoming traces on Confident AI's servers. This approach is recommended if your agent is in production.
Create metric collection
Create a metric collection on Confident AI with the metrics you wish to use to evaluate your AI SDK based application.
Create metric collection Run evals
You can run evals at both the trace and span level. We recommend creating separate metric collections for each component, since each requires its own evaluation criteria and metrics.
Pass different metric collections as trace attributes:
metricCollectionapplies to the entire trace, whilellmSpanContext.metricCollectionapplies to individual LLM spans, andllmSpanContext.toolsMetricCollectionapplies to tool call spans.import { generateText } from "ai"; import { configureAiSdkTracing } from "deepeval"; import { setTracingContext } from "deepeval/tracing"; const tracer = configureAiSdkTracing(); await setTracingContext( { metricCollection: "trace-metric-collection-name", llmSpanContext: { metricCollection: "llm-metric-collection-name", toolsMetricCollection: "tool-metric-collection-name" } }, async () => { const { text } = await generateText({ model: "openai/gpt-4o", prompt: "How to make the best coffee?", experimental_telemetry: { isEnabled: true, tracer: tracer, }, }); console.log(text); } );import { generateText } from "ai"; const { text } = await generateText({ model: "openai/gpt-4o", prompt: "How to make the best coffee?", experimental_telemetry: { isEnabled: true, metadata: { traceMetricCollection: "trace-metric-collection", metricCollection: "span-metric-collection" } }, }); console.log(text);
You can view evals on Confident AI by visiting the traces pages inside the observatory on Confident AI platform.
Last updated on