Skip to main content

streaming/
streaming.rs

1use futures::StreamExt;
2use gemini_client_api::gemini::ask::Gemini;
3use gemini_client_api::gemini::types::sessions::Session;
4use std::env;
5use std::io::{stdout, Write};
6
7#[tokio::main]
8async fn main() {
9    let mut session = Session::new(10);
10    let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY must be set");
11    let ai = Gemini::new(api_key, "gemini-2.5-flash", None);
12
13    println!("--- Streaming Example ---");
14    let prompt = "Write a short poem about crab-like robots on Mars.";
15    println!("User: {}\n", prompt);
16    print!("Gemini: ");
17    stdout().flush().unwrap();
18
19    // Start a streaming request
20    let mut response_stream = ai.ask_as_stream(session.ask_string(prompt).clone()).await.unwrap();
21
22    while let Some(chunk_result) = response_stream.next().await {
23        match chunk_result {
24            Ok(response) => {
25                // Get the text from the current chunk
26                let text = response.get_chat().get_text_no_think("");
27                print!("{}", text);
28                stdout().flush().unwrap();
29            }
30            Err(e) => {
31                eprintln!("\nError receiving chunk: {:?}", e);
32                break;
33            }
34        }
35    }
36
37    println!("\n\n--- Stream Complete ---");
38    // Note: The session passed to ask_as_stream is updated as you exhaust the stream.
39}