structured_response/
structured_response.rs

1use gemini_rust::Gemini;
2use serde_json::json;
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    // Using response_schema for structured output
14    println!("--- Structured Response Example ---");
15
16    // Define a JSON schema for the response
17    let schema = json!({
18        "type": "object",
19        "properties": {
20            "name": {
21                "type": "string",
22                "description": "Name of the programming language"
23            },
24            "year_created": {
25                "type": "integer",
26                "description": "Year the programming language was created"
27            },
28            "creator": {
29                "type": "string",
30                "description": "Person or organization who created the language"
31            },
32            "key_features": {
33                "type": "array",
34                "items": {
35                    "type": "string"
36                },
37                "description": "Key features of the programming language"
38            },
39            "popularity_score": {
40                "type": "integer",
41                "description": "Subjective popularity score from 1-10"
42            }
43        },
44        "required": ["name", "year_created", "creator", "key_features", "popularity_score"]
45    });
46
47    let response = client
48        .generate_content()
49        .with_system_prompt("You provide information about programming languages in JSON format.")
50        .with_user_message("Tell me about the Rust programming language.")
51        .with_response_mime_type("application/json")
52        .with_response_schema(schema)
53        .execute()
54        .await?;
55
56    println!("Structured JSON Response:");
57    println!("{}", response.text());
58
59    // Parse the JSON response
60    let json_response: serde_json::Value = serde_json::from_str(&response.text())?;
61
62    println!("\nAccessing specific fields:");
63    println!("Language: {}", json_response["name"]);
64    println!("Created in: {}", json_response["year_created"]);
65    println!("Created by: {}", json_response["creator"]);
66    println!("Popularity: {}/10", json_response["popularity_score"]);
67
68    println!("\nKey Features:");
69    if let Some(features) = json_response["key_features"].as_array() {
70        for (i, feature) in features.iter().enumerate() {
71            println!("{}. {}", i + 1, feature);
72        }
73    }
74
75    Ok(())
76}