simple/
simple.rs

1use gemini_rust::{
2    Content, FunctionCallingMode, FunctionDeclaration, FunctionParameters, Gemini,
3    GenerationConfig, Message, PropertyDetails, Role,
4};
5use std::env;
6
7#[tokio::main]
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    // Get API key from environment variable
10    let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
11
12    // Create client
13    let client = Gemini::new(api_key);
14
15    // Simple generation
16    println!("--- Simple generation ---");
17    let response = client
18        .generate_content()
19        .with_user_message("Hello, can you tell me a joke about programming?")
20        .with_generation_config(GenerationConfig {
21            temperature: Some(0.7),
22            max_output_tokens: Some(1000),
23            ..Default::default()
24        })
25        .execute()
26        .await?;
27
28    println!("Response: {}", response.text());
29
30    // Function calling example
31    println!("\n--- Function calling example ---");
32
33    // Define a weather function
34    let get_weather = FunctionDeclaration::new(
35        "get_weather",
36        "Get the current weather for a location",
37        FunctionParameters::object()
38            .with_property(
39                "location",
40                PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
41                true,
42            )
43            .with_property(
44                "unit",
45                PropertyDetails::enum_type("The unit of temperature", ["celsius", "fahrenheit"]),
46                false,
47            ),
48    );
49
50    // Create a request with function calling
51    let response = client
52        .generate_content()
53        .with_system_prompt("You are a helpful weather assistant.")
54        .with_user_message("What's the weather like in San Francisco right now?")
55        .with_function(get_weather)
56        .with_function_calling_mode(FunctionCallingMode::Any)
57        .execute()
58        .await?;
59
60    // Check if there are function calls
61    if let Some(function_call) = response.function_calls().first() {
62        println!(
63            "Function call: {} with args: {}",
64            function_call.name, function_call.args
65        );
66
67        // Get parameters from the function call
68        let location: String = function_call.get("location")?;
69        let unit = function_call
70            .get::<String>("unit")
71            .unwrap_or_else(|_| String::from("celsius"));
72
73        println!("Location: {}, Unit: {}", location, unit);
74
75        // Create model content with function call
76        let model_content = Content::function_call((*function_call).clone());
77
78        // Add as model message
79        let model_message = Message {
80            content: model_content,
81            role: Role::Model,
82        };
83
84        // Simulate function execution
85        let weather_response = format!(
86            "{{\"temperature\": 22, \"unit\": \"{}\", \"condition\": \"sunny\"}}",
87            unit
88        );
89
90        // Continue the conversation with the function result
91        let final_response = client
92            .generate_content()
93            .with_system_prompt("You are a helpful weather assistant.")
94            .with_user_message("What's the weather like in San Francisco right now?")
95            .with_message(model_message)
96            .with_function_response_str("get_weather", weather_response)?
97            .with_generation_config(GenerationConfig {
98                temperature: Some(0.7),
99                max_output_tokens: Some(100),
100                ..Default::default()
101            })
102            .execute()
103            .await?;
104
105        println!("Final response: {}", final_response.text());
106    } else {
107        println!("No function calls in the response.");
108    }
109
110    Ok(())
111}