streaming/
streaming.rs

1use futures_util::StreamExt;
2use gemini_rust::Gemini;
3use std::env;
4
5#[tokio::main]
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // Get API key from environment variable
8    let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
9
10    // Create client
11    let client = Gemini::new(api_key);
12
13    // Simple streaming generation
14    println!("--- Streaming generation ---");
15
16    let mut stream = client
17        .generate_content()
18        .with_system_prompt("You are a helpful, creative assistant.")
19        .with_user_message("Write a short story about a robot who learns to feel emotions.")
20        .execute_stream()
21        .await?;
22
23    print!("Streaming response: ");
24    while let Some(chunk_result) = stream.next().await {
25        match chunk_result {
26            Ok(chunk) => {
27                print!("{}", chunk.text());
28                std::io::Write::flush(&mut std::io::stdout())?;
29            }
30            Err(e) => eprintln!("Error in stream: {}", e),
31        }
32    }
33    println!("\n");
34
35    // Multi-turn conversation
36    println!("--- Multi-turn conversation ---");
37
38    // First turn
39    let response1 = client
40        .generate_content()
41        .with_system_prompt("You are a helpful travel assistant.")
42        .with_user_message("I'm planning a trip to Japan. What are the best times to visit?")
43        .execute()
44        .await?;
45
46    println!("User: I'm planning a trip to Japan. What are the best times to visit?");
47    println!("Assistant: {}\n", response1.text());
48
49    // Second turn (continuing the conversation)
50    let response2 = client
51        .generate_content()
52        .with_system_prompt("You are a helpful travel assistant.")
53        .with_user_message("I'm planning a trip to Japan. What are the best times to visit?")
54        .with_model_message(response1.text())
55        .with_user_message("What about cherry blossom season? When exactly does that happen?")
56        .execute()
57        .await?;
58
59    println!("User: What about cherry blossom season? When exactly does that happen?");
60    println!("Assistant: {}\n", response2.text());
61
62    // Third turn (continuing the conversation)
63    let response3 = client
64        .generate_content()
65        .with_system_prompt("You are a helpful travel assistant.")
66        .with_user_message("I'm planning a trip to Japan. What are the best times to visit?")
67        .with_model_message(response1.text())
68        .with_user_message("What about cherry blossom season? When exactly does that happen?")
69        .with_model_message(response2.text())
70        .with_user_message("What are some must-visit places in Tokyo?")
71        .execute()
72        .await?;
73
74    println!("User: What are some must-visit places in Tokyo?");
75    println!("Assistant: {}", response3.text());
76
77    Ok(())
78}