页面简介
Observe AI SDK lifecycle events in generateText, streamText, embed, embedMany, rerank, experimental_decide, and experimental_extract calls
正文摘录
AI SDK CoreMenuLifecycle CallbacksCopy for LLMView MarkdownAsk AI about this pageEvent callbacks let you run your own code at important points in an AI SDK call. You can attach them directly to generateText, streamText, embed, embedMany, rerank, experimental_decide, and experimental_extract calls to observe what happened, record usage, debug multi-step generations, and monitor tool execution. They are especially useful when you want application-specific logic close to the call site: Log which model, prompt shape, and settings were used for a request. Record token usage, latency, finish reasons, and warnings for analytics or billing. Understand how a multi-step tool call moved from model response to tool execution to final answer. Track tool inputs, tool outputs, execution time, and errors. Attach your own request, user, tenant, or workflow identifiers through runtimeContext and toolsContext. For automatic OpenTelemetry instrumentation across your application, use Telemetry. Use event callbacks when you want to run custom code for a specific AI SDK call. Basic Usage Pass callbacks as options to the AI SDK function you are calling: GatewayProviderCustomClaude Sonnet 5.5import { generateText } from 'ai'; const result = await generateText({ model: "anthropic/claude-sonnet-5.5", prompt: 'What is the weather in San Francisco?', onStart({ callId, modelId }) { console.log('Generation started', { callId, modelId }); }, onEnd({ callId, usage, finishReason }) { console.log('Generation finished', { callId, finishReason, totalTokens: usage.totalTokens, }); }, }); Callbacks can be synchronous or asynchronous. If a callback throws, the error is caught internally and the AI SDK call continues. Because callbacks run as part of the lifecycle, keep them fast or enqueue expensive work in a background system. Use Cases Request Logging Use onStart and onEnd to record one application log for the beginning and end of a call. The callId is available across lifecycle events, so you can correlate logs from the same request. GatewayProviderCustomClaude Sonnet 5.5import { generateText } from 'ai'; const result = await generateText({ model: "anthropic/claude-sonnet-5.5", prompt: 'Write a short product description for a camping mug.', onStart({ callId, provider, modelId }) { logger.info('ai.request.started', { callId, provider, modelId, }); }, onEnd({ callId, finishReason, usage, warnings }) { logger.info('ai.request.finished', { callId, finishReason, usage, warningCount: warnings?.length ?? 0, }); }, }); This pattern works well for audit logs, internal dashboards, and tracking usage for a particular feature. Measuring Model Performance onLanguageModelCallEnd runs after a provider response has been normalized and parsed. For streamText, the event also includes streaming-specific timing data such as time to first output and gaps between output chunks. GatewayProviderCustomClaude Sonnet 5.5import { streamText } from 'ai'; const result = streamText({ model: "anthropic/claude-sonnet-5.5", prompt: 'Explain partial prerendering in two paragraphs.', onLanguageModelCallEnd({ callId, modelId, usage, performance, providerMetadata, }) { metrics.histogram('ai.model.response_time_ms', performance.responseTimeMs, { callId, modelId, }); metrics.gauge('ai.model.tokens_per_second', { output: performance.outputTokensPerSecond, total: performance.effectiveTotalTokensPerSecond, tokens: usage.totalTokens, }); logger.info('ai.model.provider_metadata', { callId, providerMetadata, }); }, }); for await (const textPart of result.textStream) { process.stdout.write(textPart); } Use model-call events when you want to measure provider work specifically. Use step events when you want timing that includes SDK-managed work such as local tool execution. Debugging Multi-Step Tool Calls When you use tools with generateText or streamText, a single user request can involve multiple model calls. Each model call is a step. The model may call a tool in one step, receive the tool result, and then produce a final answer in the next step. GatewayProviderCustomClaude Sonnet 5.5import { generateText, isStepCount, tool } from 'ai'; import { z } from 'zod'; const result = await generateText({ model: "anthropic/claude-sonnet-5.5", stopWhen: isStepCount(5), prompt: 'What is the weather in San Francisco?', tools: { weather: tool({ description: 'Get the weather in a location', inputSchema: z.object({ location: z.string() }), execute: async ({ location }) => getWeather(location), }), }, onStepStart({ stepNumber, messages, steps }) { console.log(`Step ${stepNumber} started`, { messageCount: messages.length, previousSteps: steps.length, }); }, onStepEnd({ stepNumber, finishReason, toolCalls, usage, performance }) { console.log(`Step ${stepNumber} finished`, { finishReason, toolCalls: toolCalls.map(toolCall => toolCall.toolName), totalTokens: usage.totalTokens, stepTimeMs: performance.stepTimeMs, }); }, }); This helps answer questions such as: Did the model call a tool or answer directly? How many steps did the request take? Which step used the most tokens? Did time go to the model response or to local tool execution? Monitoring Tool Execution Tool execution callbacks run around the tool's execute function. Use them to record tool usage, latency, successful results, and tool errors. GatewayProviderCustomClaude Sonnet 5.5import { generateText, tool } from 'ai'; import { z } from 'zod'; const result = await generateText({ model: "anthropic/claude-sonnet-5.5", prompt: 'Find flights from SFO to JFK tomorrow morning.', tools: { searchFlights: tool({ description: 'Search available flights', inputSchema: z.object({ origin: z.string(), destination: z.string(), }), execute: async input => searchFlights(input), }), }, onToolExecutionStart({ callId, toolCall }) { logger.info('ai.tool.started', { callId, toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input: toolCall.input, }); }, onToolExecutionEnd({ callId, toolCall, toolExecutionMs, toolOutput }) { logger.info('ai.tool.finished', { callId, toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, durationMs: toolExecutionMs, success: toolOutput.type === 'tool-result', }); }, }); toolOutput is a discriminated union. When toolOutput.type is 'tool-result', the output is available on toolOutput.output. When it is 'tool-error', the error is available on toolOutput.error. Observing Embeddings and Reranking Embedding and reranking callbacks are simpler: they expose onStart and onEnd around the operation. This is useful for retrieval pipelines where you want to understand how often you are embedding, how many values you embed, and how reranking changes result sets. import { embedMany, rerank } from 'ai'; import { cohere } from '@ai-sdk/cohere'; const values = ['sunny day at the beach', 'rainy afternoon in the city']; const { embeddings } = await embedMany({ model: 'openai/text-embedding-3-small', values, onStart({ callId, operationId, modelId, value }) { logger.info('ai.embedding.started', { callId, operationId, modelId, valueCount: Array.isArray(value) ? value.length : 1, }); }, onEnd({ callId, usage }) { logger.info('ai.embedding.finished', { callId, tokens: usage.tokens, }); }, }); const { ranking } = await rerank({ model: cohere.reranking('rerank-v4.0-pro'), documents: values, query: 'talk about rain', onEnd({ callId, ranking }) { logger.info('ai.rerank.finished', { callId, topResult: ranking[0], }); }, }); Generation Lifecycle generateText and streamText expose the richest lifecycle because they can involve prompts, model calls, tool calls, and multiple steps. A typical single-step generation runs in this order: onStart onStepStart onLanguageModelCallStart onLanguageModelCallEnd onStepEnd onEnd A multi-step generation with local tool execution usually runs like this: onStart onStepStart onLanguageModelCallStart onLanguageModelCallEnd onToolExecutionStart onToolExecutionEnd onStepEnd Repeat step callbacks until the stop condition is met onEnd onStepStart and onStepEnd describe the full step. onLanguageModelCallStart and onLanguageModelCallEnd describe only the model call inside that step. This distinction matters when the step includes local tool execution: the step duration can be longer than the model response duration. When a step that started fails before it produces a step result, onStepError is called instead of onStepEnd. This happens when the provider call throws or rejects, or when the model stream ends without output. A provider error chunk does not fail the step: the step still ends with onStepEnd and finishReason: 'error'. Aborts and timeouts end the step differently in each function. In generateText and agent.generate(), they end the step with onStepError. Its error is the abort or timeout error, or a provider error that has it as its cause. In streamText and agent.stream(), they end the step with onAbort. Runtime and Tool Context Generation and step lifecycle callbacks receive the full runtimeContext and toolsContext values that flow through the call. Tool-execution callbacks receive the scoped toolContext for the tool being executed. This makes callbacks useful for attaching application context without changing prompts or tool inputs. GatewayProviderCustomClaude Sonnet 5.5import { generateText, tool } from 'ai'; import { z } from 'zod'; const result = await generateText({ model: "anthropic/claude-sonnet-5.5", prompt: 'Check the order status.', runtimeContext: { requestId: 'req_123', tenantId: 'tenant_abc', }, tools: { getOrderStatus: tool({ inputSchema: z.object({ orderId: z.string() }), contextSchema: z.object({ region: z.string() }), execute: async ({ orderId }, { context }) => getOrderStatus(orderId, context.region), }), }, toolsContext: { getOrderStatus: { region: 'us-east-1', }, }, onStart({ callId, runtimeContext }) { logger.info('ai.request.started', { callId, requestId: runtimeContext.requestId, tenantId: runtimeContext.tenantId, }); }, onToolExecutionStart({ toolCall, toolContext }) { logger.info('ai.tool.started',