Real-Time Event Streaming
Runner.stream() provides real-time event streaming for interactive web applications, chat interfaces, and CLI tools using native JavaScript AsyncGenerator.
Why Stream Events?
In modern AI applications, users expect real-time feedback token-by-token rather than waiting 5+ seconds for a complete response.
Runner.stream() yields structured events for:
- Token Text Deltas: Streamed partial text chunks as they arrive from the model.
- Tool Call Lifecycle: Notifications when a tool execution starts, completes, or fails.
- Agent Handoffs: Live alerts when control shifts from a triage agent to a specialist agent.
- Run Completion: Final metrics, total tokens, and full message history.
Stream Event Types
| Event Type | Properties | Description |
|---|---|---|
'text_delta' | delta: string | Next chunk of text generated by the model. |
'tool_call_started' | toolCall: { name, args } | Tool execution initiated by the model. |
'tool_call_finished' | toolCall: { name }, result | Tool execution completed with output data. |
'handoff' | fromAgent: string, toAgent: string | Active agent transferred via handoff. |
'run_complete' | result: RunResult | Entire execution loop completed cleanly. |
Complete Streaming Code Example
typescript
Next.js App Router Server-Sent Events (SSE)
Integrate Runner.stream() with Next.js App Router API Route handlers:
typescript
Best Practices
- Handle High Delta Volume: Ensure client-side UI handlers batch or throttle DOM updates if receiving rapid token deltas.
- Always Handle
run_complete: Userun_completeto mark the stream as finished and store conversation state.