Skip to main content

structured_output/
structured_output.rs

1use gemini_client_api::gemini::ask::Gemini;
2use gemini_client_api::gemini::types::sessions::Session;
3use gemini_client_api::gemini::utils::{gemini_schema, GeminiSchema};
4use serde::Deserialize;
5use std::env;
6
7/// Define your desired response structure.
8/// Use the `#[gemini_schema]` macro to automatically generate the JSON schema.
9#[derive(Debug, Deserialize)]
10#[gemini_schema]
11struct MovieReview {
12    /// The title of the movie.
13    title: String,
14    /// A score from 1 to 10.
15    rating: u8,
16    /// A list of main actors.
17    cast: Vec<String>,
18    /// A short summary of the plot.
19    summary: String,
20}
21
22#[tokio::main]
23async fn main() {
24    let mut session = Session::new(2).set_remember_reply(false);
25    let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY must be set");
26    let ai = Gemini::new(api_key, "gemini-2.5-flash", None);
27
28    println!("--- Structured Output (JSON Mode) Example ---");
29
30    // Enable JSON mode by passing the generated schema
31    let ai = ai.set_json_mode(MovieReview::gemini_schema());
32
33    let prompt = "Give me a review for the movie Interstellar.";
34    println!("User: {}", prompt);
35
36    let response = ai.ask(session.ask_string(prompt)).await.unwrap();
37
38    // Extract and deserialize the JSON response
39    if let Ok(review) = response.get_json::<MovieReview>() {
40        println!("\nGemini (Structured):");
41        println!("{:#?}", review);
42    } else {
43        println!("\nFailed to parse JSON response: {}", response.get_chat().get_text_no_think(""));
44    }
45}