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 = MessagesAPI::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
40        .credentials(credentials.clone())
41        .create_stream()
42        .await
43        .unwrap();
44
45    // Print assistant's streaming response
46    print!("Assistant: ");
47    stdout().flush().unwrap();
48    while let Some(event) = stream.recv().await {
49        match event {
50            StreamEvent::ContentBlockDelta { delta, .. } => {
51                if let ContentBlockDelta::Text { text } = delta {
52                    print!("{}", text);
53                    stdout().flush().unwrap();
54                }
55            }
56            StreamEvent::MessageStop => {
57                println!();
58            }
59            _ => {}
60        }
61    }
62
63    // Start conversation loop
64    loop {
65        print!("\nUser: ");
66        stdout().flush().unwrap();
67
68        let mut user_input = String::new();
69        stdin().read_line(&mut user_input).unwrap();
70
71        // Add user message
72        messages.push(Message {
73            role: MessageRole::User,
74            content: MessageContent::Text(user_input),
75        });
76
77        // Send message request with streaming
78        let mut stream = MessagesAPI::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
79            .credentials(credentials.clone())
80            .create_stream()
81            .await
82            .unwrap();
83
84        // Print assistant's streaming response and store the text
85        print!("\nAssistant: ");
86        stdout().flush().unwrap();
87        let mut full_response = String::new();
88        while let Some(event) = stream.recv().await {
89            match event {
90                StreamEvent::ContentBlockDelta { delta, .. } => {
91                    if let ContentBlockDelta::Text { text } = delta {
92                        print!("{}", text);
93                        stdout().flush().unwrap();
94                        full_response.push_str(&text);
95                    }
96                }
97                StreamEvent::MessageStop => {
98                    println!();
99                }
100                _ => {}
101            }
102        }
103
104        // Add assistant's complete response to messages
105        messages.push(Message {
106            role: MessageRole::Assistant,
107            content: MessageContent::Text(full_response),
108        });
109    }
110}