Lifecycle Callbacks
Event 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, and experimental_decide 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
runtimeContextandtoolsContext.
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:
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.
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.
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.
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.
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.
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:
onStartonStepStartonLanguageModelCallStartonLanguageModelCallEndonStepEndonEnd
A multi-step generation with local tool execution usually runs like this:
onStartonStepStartonLanguageModelCallStartonLanguageModelCallEndonToolExecutionStartonToolExecutionEndonStepEnd- 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.
Telemetry integrations can filter runtimeContext and toolsContext before
exporting them. Generation and step callbacks receive the full context
objects; tool-execution callbacks receive scoped tool context. Be careful not
to log secrets or sensitive user data from callbacks.
Available Callbacks
generateText and streamText
execute function runs.execute function completes or errors.onStepStart event of the failed step plus error. In generateText, also called on abort or timeout. In streamText, aborts and timeouts call onAbort instead.onStepFinish is deprecated. Use onStepEnd for new code.embed and embedMany
rerank
experimental_decide
Event Data Reference
The exact event data depends on the callback. The tables below summarize the fields you will most commonly use.
Text Generation Events
onStart
Called once before any model calls are made.
toolsContext.onStepStart
Called before each step begins.
prepareStep between steps.prepareStep between steps.onLanguageModelCallStart
Called immediately before the provider model call begins.
onLanguageModelCallEnd
Called after the provider response has been normalized and parsed, before local tool execution begins.
onToolExecutionStart
Called before a local tool's execute function runs.
toolCallId, toolName, and input.onToolExecutionEnd
Called after a local tool's execute function completes or errors.
onStepEnd
Called after each step completes. The event is the full StepResult for that step.
onEnd
Called once when the full generation completes.
steps.at(-1).Embedding Events
embed and embedMany share the same event interfaces.
Use operationId to distinguish 'ai.embed' from 'ai.embedMany'.
For embed, value is a single string. For embedMany, value is an array of strings.
onStart
onEnd
embedMany, this can be one response per chunk.Rerank Events
onStart
onEnd
Decision Events
Decision callbacks are experimental. Their exported types are
Experimental_DecideStartEvent and Experimental_DecideEndEvent.
onStart
onEnd
Includes every onStart field plus: