Agent Streaming
🎯 Introduction
An agent with multiple tools may call the model and business APIs several times. With invoke(), users wait for the entire task to finish without knowing what is being queried. This article introduces streaming tool calls, results, model text, and business progress while a task runs, preparing us to build AI applications with real-time feedback.
🧱 Agent Streaming Compared with Model Streaming
Model streaming primarily displays generated text incrementally. An agent may also call several tools before answering, and tool execution does not necessarily produce model text.
A text-only interface may therefore remain blank for a long time. Update it according to event type: show a query status when a tool starts, display data when it returns, and reveal the answer as the model generates text.
LangChain’s stream() provides three commonly used modes:
| Mode | Output | Use |
|---|---|---|
updates | State updates after each agent execution step | Observe tool calls and results |
messages | Model message chunks and associated metadata | Display model text incrementally |
custom | Data explicitly emitted by the application or tools | Display business progress |
These are LangChain streaming modes, not the HTTP SSE transport protocol. We will first inspect events in a Node.js terminal, then forward them to the frontend when building an AI workbench later.
🧱 Receive Execution Updates
Reuse agent.mjs from “Your First LangChain Agent” and create 03.streaming.mjs:
import { agent } from './agent.mjs';
const input = {
messages: [{ role: 'user', content: 'Are there enough mechanical keyboards to buy 15 units?' }],
};
// Receive state updates for each agent execution step
const stream = await agent.stream(input, {
streamMode: 'updates',
recursionLimit: 20,
});
for await (const update of stream) {
console.log(JSON.stringify(update, null, 4));
}
stream() does not wait for the whole task before making results available. Async iteration lets you receive an update after each step completes.
Run:
node --env-file=.env 03.streaming.mjs
Below are two possible updates with only the key fields retained. Actual serialized message structures and node names depend on the SDK output.
{
"model": {
"messages": [
{
"tool_calls": [{ "name": "find_product", "args": { "name": "mechanical keyboard" } }]
}
]
}
}
This update follows a model decision and indicates a product search request. It does not establish that the tool has executed successfully.
{
"tools": {
"messages": [{ "content": "{\"id\":\"P100\",\"name\":\"mechanical keyboard\"}" }]
}
}
This update follows tool execution. Further model and stock tool updates may follow, ending with the model’s answer message.
Print Only the Details You Need
Full state objects can be lengthy. Replace the for await loop with the following code to inspect what happened from the messages:
for await (const update of stream) {
// Get the messages added by each execution node in this update
for (const state of Object.values(update)) {
const messages = state?.messages ?? [];
for (const message of messages) {
console.log('Message type:', message.type);
console.log('Message content:', message.content);
if (message.tool_calls?.length) {
console.log('Tool calls:', message.tool_calls);
}
}
}
}
updates returns state updates keyed by execution node name. Object.values() retrieves each node’s update without requiring its name in advance.
Run again. You may see the following (tool call IDs are examples):
Message type: ai
Message content:
Tool calls: [
{
name: 'find_product',
args: { name: 'mechanical keyboard' },
id: 'call_1',
type: 'tool_call'
}
]
Message type: tool
Message content: {"id":"P100","name":"mechanical keyboard"}
Message type: ai
Message content:
Tool calls: [
{
name: 'get_stock',
args: { id: 'P100' },
id: 'call_2',
type: 'tool_call'
}
]
Message type: tool
Message content: {"id":"P100","stock":12}
Message type: ai
Message content: There are 12 units in stock, so you need 3 more.
Unlike invoke(), this prints logs as each step completes, rather than all at once after the task ends.
🧱 Stream Model Text
In 03.streaming.mjs, keep the import and input, and replace stream creation and consumption with:
const stream = await agent.stream(input, {
streamMode: 'messages',
recursionLimit: 20,
});
// Receive model message chunks, taking only the first tuple element
for await (const [chunk] of stream) {
// Print text only, ignoring tool calls and other content blocks
for (const block of chunk.contentBlocks ?? []) {
if (block.type === 'text') {
process.stdout.write(block.text);
}
}
}
process.stdout.write('\n');
messages mode yields [chunk, metadata]: a message chunk and its metadata. Metadata can identify the execution node that produced the message; we do not use it here.
Run again. The following text may appear incrementally:
There are 12 units in stock, so you need 3 more.
Since an agent may call the model repeatedly, not all text necessarily belongs to the final answer. Real applications should distinguish individual model messages.
🧱 Emit Custom Progress Events
Suppose a stock lookup calls an external API. The application wants to show “Checking stock” when the request starts rather than waiting for the tool to finish. A tool can explicitly emit progress events through writer.
In agent.mjs, replace the original stockTool definition with:
export const stockTool = tool(
({ id }, config) => {
// Emit progress when the tool starts
const writer = config?.writer;
writer?.({ status: 'loading', id, message: 'Checking stock' });
const result = getStock(id);
// Emit an end status based on the result
if (result.error) {
writer?.({ status: 'error', id, message: result.error });
} else {
writer?.({ status: 'done', id, message: 'Stock lookup finished' });
}
return JSON.stringify(result);
},
{
name: 'get_stock',
description: 'Look up stock using a known product ID; product names are not accepted',
schema: z.object({
id: z.string().describe('Product ID, such as P100'),
}),
}
);
The runtime provides config.writer to send custom data into the stream. Optional calls avoid errors when no writer is provided. Progress events are for the application; the tool must still return its business result to the model.
Receive Custom Progress
In 03.streaming.mjs, keep the import and input, and replace stream creation and the code after it with:
const stream = await agent.stream(input, {
streamMode: 'custom',
recursionLimit: 20,
});
for await (const data of stream) {
console.log('Business progress:', data);
}
Run:
node --env-file=.env 03.streaming.mjs
If the model calls the stock tool, you may see:
Business progress: { status: 'loading', id: 'P100', message: 'Checking stock' }
Business progress: { status: 'done', id: 'P100', message: 'Stock lookup finished' }
Since this example uses in-memory data, these events may appear immediately one after another. Progress feedback is more useful during the wait for a database or API query. custom mode outputs only explicitly emitted data, not model text.
🧱 Receive Multiple Event Types
In 03.streaming.mjs, keep the import and input, and replace stream creation and the code after it with:
const stream = await agent.stream(input, {
streamMode: ['updates', 'messages', 'custom'],
recursionLimit: 20,
});
for await (const [mode, data] of stream) {
// Display business progress
if (mode === 'custom') {
console.log('\nBusiness progress:', data);
continue;
}
// Display execution steps
if (mode === 'updates') {
console.log('\nExecution step:', Object.keys(data));
continue;
}
// Print model text incrementally
if (mode === 'messages') {
const [chunk] = data;
for (const block of chunk.contentBlocks ?? []) {
if (block.type === 'text') {
process.stdout.write(block.text);
}
}
}
}
process.stdout.write('\n');
When multiple modes are enabled, each iteration yields [mode, data]. Dispatching on mode lets you receive all three data types together.
Run node --env-file=.env 03.streaming.mjs again. You may see the following (blank lines omitted and consecutive text chunks combined):
Execution step: ['model']
Execution step: ['tools']
Execution step: ['model']
Business progress: { status: 'loading', id: 'P100', message: 'Checking stock' }
Business progress: { status: 'done', id: 'P100', message: 'Stock lookup finished' }
Execution step: ['tools']
There are 12 units in stock, so you need 3 more.
Execution step: ['model']
done only means the stock lookup finished, not that the entire task is complete. Do not infer completion from a fixed node count or event order. Wait for the stream to end normally and evaluate the business result. If the stream throws, display a failure state.❓ Questions and Answers
Q1: Does stream() reduce the number of model calls?
Not necessarily. Streaming changes when and how the application receives data, not the agent’s decision logic. Tool and model call counts still depend on the task and execution controls.
🧪 Exercises
Add search-start and search-end progress events to the execution function of findProductTool. Query mechanical keyboard stock using multiple stream modes. Check for both search and stock progress, and verify that the final answer reports 12 units in stock and a shortfall of 3. Preserve the tool’s existing return value.
🎉 Congratulations! You can now observe an agent’s execution in real time.
