pub async fn query_stream(
prompt: impl Into<String>,
options: Option<ClaudeAgentOptions>,
) -> Result<Pin<Box<dyn Stream<Item = Result<Message>> + Send>>>Expand description
Query Claude Code with streaming responses for memory-efficient processing.
Unlike query() which collects all messages in memory before returning,
this function returns a stream that yields messages as they arrive from Claude.
This is more memory-efficient for large conversations and provides real-time
message processing capabilities.
Note: This function does not support can_use_tool callbacks or hooks.
For permission handling or hook support, use [ClaudeClient] instead.
§Performance Comparison
query(): O(n) memory usage, waits for all messages before returningquery_stream(): O(1) memory per message, processes messages in real-time
§Errors
Returns an error if:
options.can_use_toolis set (use ClaudeClient instead)options.hooksis set (use ClaudeClient instead)- Claude CLI cannot be found or started
§Examples
use claude_agent_sdk_rs::{query_stream, Message, ContentBlock};
use futures::stream::StreamExt;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let mut stream = query_stream("What is 2 + 2?", None).await?;
while let Some(result) = stream.next().await {
match result? {
Message::Assistant(msg) => {
for block in &msg.message.content {
if let ContentBlock::Text(text) = block {
println!("Claude: {}", text.text);
}
}
}
_ => {}
}
}
Ok(())
}