streaming/
streaming.rs

1//! # Streaming Example
2//!
3//! This example demonstrates how to use the streaming API with Claude.
4//! It creates a conversation loop where the user can chat with the AI assistant,
5//! and the assistant's responses are streamed in real-time.
6//!
7//! ## Features
8//!
9//! - Initializes with a system-like message to set the assistant's behavior
10//! - Maintains conversation history for context
11//! - Streams responses in real-time for a more interactive experience
12//! - Simple command-line interface for user input
13//!
14//! ## Usage
15//!
16//! Run this example with:
17//!
18//! ```bash
19//! cargo run --example streaming
20//! ```
21//!
22//! Make sure you have set the `ANTHROPIC_API_KEY` environment variable.
23
24use anthropic_api::{messages::*, Credentials};
25use std::io::{stdin, stdout, Write};
26
27#[tokio::main]
28async fn main() {
29    let credentials = Credentials::from_env();
30
31    let mut messages = vec![Message {
32        role: MessageRole::User,
33        content: MessageContent::Text(
34            "You are a helpful AI assistant. Please introduce yourself briefly.".to_string(),
35        ),
36    }];
37
38    // Create initial message request with streaming
39    let mut stream =
40        MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
41            .credentials(credentials.clone())
42            .create_stream()
43            .await
44            .unwrap();
45
46    // Print assistant's streaming response
47    print!("Assistant: ");
48    stdout().flush().unwrap();
49    while let Some(event) = stream.recv().await {
50        match event {
51            StreamEvent::ContentBlockDelta { delta, .. } => {
52                if let ContentBlockDelta::Text { text } = delta {
53                    print!("{}", text);
54                    stdout().flush().unwrap();
55                }
56            }
57            StreamEvent::MessageStop => {
58                println!();
59            }
60            _ => {}
61        }
62    }
63
64    // Start conversation loop
65    loop {
66        print!("\nUser: ");
67        stdout().flush().unwrap();
68
69        let mut user_input = String::new();
70        stdin().read_line(&mut user_input).unwrap();
71
72        // Add user message
73        messages.push(Message {
74            role: MessageRole::User,
75            content: MessageContent::Text(user_input),
76        });
77
78        // Send message request with streaming
79        let mut stream =
80            MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
81                .credentials(credentials.clone())
82                .create_stream()
83                .await
84                .unwrap();
85
86        // Print assistant's streaming response and store the text
87        print!("\nAssistant: ");
88        stdout().flush().unwrap();
89        let mut full_response = String::new();
90        while let Some(event) = stream.recv().await {
91            match event {
92                StreamEvent::ContentBlockDelta { delta, .. } => {
93                    if let ContentBlockDelta::Text { text } = delta {
94                        print!("{}", text);
95                        stdout().flush().unwrap();
96                        full_response.push_str(&text);
97                    }
98                }
99                StreamEvent::MessageStop => {
100                    println!();
101                }
102                _ => {}
103            }
104        }
105
106        // Add assistant's complete response to messages
107        messages.push(Message {
108            role: MessageRole::Assistant,
109            content: MessageContent::Text(full_response),
110        });
111    }
112}