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