stream()
Similar to text() but returns a stream of responses instead of waiting for completion
const agent = new Agent({...});
// Stream responses
const stream = await agent.stream({
messages: ["Write a long story about..."]
});
for await (const chunk of stream) {
console.log(chunk.text); // Process each chunk as it arrives
}
// With step tracking
const stream = await agent.stream({
messages: ["Complex task requiring multiple tools..."],
onStepFinish: (step) => {
console.log(`Step completed: ${step}`)
},
maxSteps: 3
});
Key differences between text() and stream():
1. Response Format
- text(): Returns complete response when finished
- stream(): Returns chunks of response as they’re generated
2. Use Cases
- text(): Better for short responses or when you need the complete result
- stream(): Better for long responses or when you want to show progress
3. Memory Usage
- text(): Holds complete response in memory
- stream(): Processes response in chunks, more memory efficient
4. Both methods share:
- Same input parameters
- Tool execution capabilities
- Rate limit handling
- Logging
- Error handling
API Signature
Parameters
messages:
Array<string>
An array of messages to generate process
onStepFinish?:
(step: string) => void;
Callback function called after each step. Receives step details as a JSON string
maxSteps?:
number
Maximum number of tool execution steps allowed. (Defaults to 5)
Returns an array
text?:
string
The generated text response
toolCalls?:
Array<ToolCall>
The tool calls made during the text generation process
ToolCall
toolName:
string
The name of the tool
args:
any
The arguments passed to the tool
error?:
string
Error message if the tool execution fails