Struct ThinkingConfig

Source
pub struct ThinkingConfig {
    pub thinking_budget: Option<i32>,
    pub include_thoughts: Option<bool>,
}
Expand description

Configuration for thinking (Gemini 2.5 series only)

Fields§

§thinking_budget: Option<i32>

The thinking budget (number of thinking tokens)

  • Set to 0 to disable thinking
  • Set to -1 for dynamic thinking (model decides)
  • Set to a positive number for a specific token budget

Model-specific ranges:

  • 2.5 Pro: 128 to 32768 (cannot disable thinking)
  • 2.5 Flash: 0 to 24576
  • 2.5 Flash Lite: 512 to 24576
§include_thoughts: Option<bool>

Whether to include thought summaries in the response

When enabled, the response will include synthesized versions of the model’s raw thoughts, providing insights into the reasoning process.

Implementations§

Source§

impl ThinkingConfig

Source

pub fn new() -> Self

Create a new thinking config with default settings

Examples found in repository?
examples/thinking_basic.rs (line 89)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    // Get API key from environment variable
7    let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
8
9    // Create client
10    let client = Gemini::with_model(api_key, "models/gemini-2.5-pro".to_string());
11
12    println!("=== Gemini 2.5 Thinking Basic Example ===\n");
13
14    // Example 1: Using default dynamic thinking
15    println!(
16        "--- Example 1: Dynamic thinking (model automatically determines thinking budget) ---"
17    );
18    let response1 = client
19        .generate_content()
20        .with_system_prompt("You are a helpful mathematics assistant.")
21        .with_user_message(
22            "Explain Occam's razor principle and provide a simple example from daily life.",
23        )
24        .with_dynamic_thinking()
25        .with_thoughts_included(true)
26        .execute()
27        .await?;
28
29    // Display thinking process
30    let thoughts = response1.thoughts();
31    if !thoughts.is_empty() {
32        println!("Thinking summary:");
33        for (i, thought) in thoughts.iter().enumerate() {
34            println!("Thought {}: {}\n", i + 1, thought);
35        }
36    }
37
38    println!("Answer: {}\n", response1.text());
39
40    // Display token usage
41    if let Some(usage) = &response1.usage_metadata {
42        println!("Token usage:");
43        println!("  Prompt tokens: {}", usage.prompt_token_count);
44        println!(
45            "  Response tokens: {}",
46            usage.candidates_token_count.unwrap_or(0)
47        );
48        if let Some(thinking_tokens) = usage.thoughts_token_count {
49            println!("  Thinking tokens: {}", thinking_tokens);
50        }
51        println!("  Total tokens: {}\n", usage.total_token_count);
52    }
53
54    // Example 2: Set specific thinking budget
55    println!("--- Example 2: Set thinking budget (1024 tokens) ---");
56    let response2 = client
57        .generate_content()
58        .with_system_prompt("You are a helpful programming assistant.")
59        .with_user_message("List 3 main advantages of using the Rust programming language")
60        .with_thinking_budget(1024)
61        .with_thoughts_included(true)
62        .execute()
63        .await?;
64
65    // Display thinking process
66    let thoughts2 = response2.thoughts();
67    if !thoughts2.is_empty() {
68        println!("Thinking summary:");
69        for (i, thought) in thoughts2.iter().enumerate() {
70            println!("Thought {}: {}\n", i + 1, thought);
71        }
72    }
73
74    println!("Answer: {}\n", response2.text());
75
76    // Example 3: Disable thinking feature
77    println!("--- Example 3: Disable thinking feature ---");
78    let response3 = client
79        .generate_content()
80        .with_system_prompt("You are a helpful assistant.")
81        .with_user_message("What is artificial intelligence?")
82        .execute()
83        .await?;
84
85    println!("Answer: {}\n", response3.text());
86
87    // Example 4: Use GenerationConfig to set thinking
88    println!("--- Example 4: Use GenerationConfig to set thinking ---");
89    let thinking_config = ThinkingConfig::new()
90        .with_thinking_budget(2048)
91        .with_thoughts_included(true);
92
93    let generation_config = GenerationConfig {
94        temperature: Some(0.7),
95        max_output_tokens: Some(500),
96        thinking_config: Some(thinking_config),
97        ..Default::default()
98    };
99
100    let response4 = client
101        .generate_content()
102        .with_system_prompt("You are a creative writing assistant.")
103        .with_user_message(
104            "Write the opening of a short story about a robot learning to feel emotions.",
105        )
106        .with_generation_config(generation_config)
107        .execute()
108        .await?;
109
110    // Display thinking process
111    let thoughts4 = response4.thoughts();
112    if !thoughts4.is_empty() {
113        println!("Thinking summary:");
114        for (i, thought) in thoughts4.iter().enumerate() {
115            println!("Thought {}: {}\n", i + 1, thought);
116        }
117    }
118
119    println!("Answer: {}\n", response4.text());
120
121    Ok(())
122}
More examples
Hide additional examples
examples/thinking_advanced.rs (line 122)
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::with_model(api_key, "models/gemini-2.5-pro".to_string());
14
15    println!("=== Gemini 2.5 Thinking Advanced Example ===\n");
16
17    // Example 1: Streaming with thinking
18    println!("--- Example 1: Streaming with thinking ---");
19    let mut stream = client
20        .generate_content()
21        .with_system_prompt("You are a mathematics expert skilled at solving complex mathematical problems.")
22        .with_user_message("Solve this math problem: Find the sum of the first 50 prime numbers. Please explain your solution process in detail.")
23        .with_thinking_budget(2048)
24        .with_thoughts_included(true)
25        .execute_stream()
26        .await?;
27
28    println!("Streaming response:");
29    let mut thoughts_shown = false;
30    while let Some(chunk_result) = stream.next().await {
31        match chunk_result {
32            Ok(chunk) => {
33                // Check if there's thinking content
34                let thoughts = chunk.thoughts();
35                if !thoughts.is_empty() && !thoughts_shown {
36                    println!("\nThinking process:");
37                    for (i, thought) in thoughts.iter().enumerate() {
38                        println!("Thought {}: {}", i + 1, thought);
39                    }
40                    println!("\nAnswer:");
41                    thoughts_shown = true;
42                }
43
44                // Display general text content
45                print!("{}", chunk.text());
46                std::io::Write::flush(&mut std::io::stdout())?;
47            }
48            Err(e) => eprintln!("Streaming error: {}", e),
49        }
50    }
51    println!("\n");
52
53    // Example 2: Thinking combined with function calls
54    println!("--- Example 2: Thinking combined with function calls ---");
55
56    // Define a calculator function
57    let calculator = FunctionDeclaration::new(
58        "calculate",
59        "Perform basic mathematical calculations",
60        FunctionParameters::object()
61            .with_property(
62                "expression",
63                PropertyDetails::string(
64                    "The mathematical expression to calculate, e.g., '2 + 3 * 4'",
65                ),
66                true,
67            )
68            .with_property(
69                "operation_type",
70                PropertyDetails::enum_type("Type of calculation", ["arithmetic", "advanced"]),
71                false,
72            ),
73    );
74
75    let response = client
76        .generate_content()
77        .with_system_prompt("You are a mathematics assistant. When calculations are needed, use the provided calculator function.")
78        .with_user_message("Calculate the result of (15 + 25) * 3 - 8 and explain the calculation steps.")
79        .with_function(calculator)
80        .with_thinking_budget(1024)
81        .with_thoughts_included(true)
82        .execute()
83        .await?;
84
85    // Display thinking process
86    let thoughts = response.thoughts();
87    if !thoughts.is_empty() {
88        println!("Thinking process:");
89        for (i, thought) in thoughts.iter().enumerate() {
90            println!("Thought {}: {}\n", i + 1, thought);
91        }
92    }
93
94    // Check for function calls
95    let function_calls = response.function_calls();
96    if !function_calls.is_empty() {
97        println!("Function calls:");
98        for (i, call) in function_calls.iter().enumerate() {
99            println!("Call {}: {} Args: {}", i + 1, call.name, call.args);
100        }
101        println!();
102    }
103
104    println!("Answer: {}\n", response.text());
105
106    // Example 3: Complex reasoning task
107    println!("--- Example 3: Complex reasoning task ---");
108    let complex_response = client
109        .generate_content()
110        .with_system_prompt("You are a logical reasoning expert.")
111        .with_user_message(
112            "There are three people: Alice, Bob, and Carol, who live in red, green, and blue houses respectively.\
113            Given:\
114            1. The person in the red house owns a cat\
115            2. Bob does not live in the green house\
116            3. Carol owns a dog\
117            4. The green house is to the left of the red house\
118            5. Alice does not own a cat\
119            Please reason out which color house each person lives in and what pets they own.",
120        )
121        .with_thinking_config(
122            ThinkingConfig::new()
123                .with_thinking_budget(3072)
124                .with_thoughts_included(true),
125        )
126        .execute()
127        .await?;
128
129    // Display thinking process
130    let complex_thoughts = complex_response.thoughts();
131    if !complex_thoughts.is_empty() {
132        println!("Reasoning process:");
133        for (i, thought) in complex_thoughts.iter().enumerate() {
134            println!("Reasoning step {}: {}\n", i + 1, thought);
135        }
136    }
137
138    println!("Conclusion: {}\n", complex_response.text());
139
140    // Display token usage statistics
141    if let Some(usage) = &complex_response.usage_metadata {
142        println!("Token usage statistics:");
143        println!("  Prompt tokens: {}", usage.prompt_token_count);
144        println!(
145            "  Response tokens: {}",
146            usage.candidates_token_count.unwrap_or(0)
147        );
148        if let Some(thinking_tokens) = usage.thoughts_token_count {
149            println!("  Thinking tokens: {}", thinking_tokens);
150        }
151        println!("  Total tokens: {}", usage.total_token_count);
152    }
153
154    Ok(())
155}
Source

pub fn with_thinking_budget(self, budget: i32) -> Self

Set the thinking budget

Examples found in repository?
examples/thinking_basic.rs (line 90)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    // Get API key from environment variable
7    let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
8
9    // Create client
10    let client = Gemini::with_model(api_key, "models/gemini-2.5-pro".to_string());
11
12    println!("=== Gemini 2.5 Thinking Basic Example ===\n");
13
14    // Example 1: Using default dynamic thinking
15    println!(
16        "--- Example 1: Dynamic thinking (model automatically determines thinking budget) ---"
17    );
18    let response1 = client
19        .generate_content()
20        .with_system_prompt("You are a helpful mathematics assistant.")
21        .with_user_message(
22            "Explain Occam's razor principle and provide a simple example from daily life.",
23        )
24        .with_dynamic_thinking()
25        .with_thoughts_included(true)
26        .execute()
27        .await?;
28
29    // Display thinking process
30    let thoughts = response1.thoughts();
31    if !thoughts.is_empty() {
32        println!("Thinking summary:");
33        for (i, thought) in thoughts.iter().enumerate() {
34            println!("Thought {}: {}\n", i + 1, thought);
35        }
36    }
37
38    println!("Answer: {}\n", response1.text());
39
40    // Display token usage
41    if let Some(usage) = &response1.usage_metadata {
42        println!("Token usage:");
43        println!("  Prompt tokens: {}", usage.prompt_token_count);
44        println!(
45            "  Response tokens: {}",
46            usage.candidates_token_count.unwrap_or(0)
47        );
48        if let Some(thinking_tokens) = usage.thoughts_token_count {
49            println!("  Thinking tokens: {}", thinking_tokens);
50        }
51        println!("  Total tokens: {}\n", usage.total_token_count);
52    }
53
54    // Example 2: Set specific thinking budget
55    println!("--- Example 2: Set thinking budget (1024 tokens) ---");
56    let response2 = client
57        .generate_content()
58        .with_system_prompt("You are a helpful programming assistant.")
59        .with_user_message("List 3 main advantages of using the Rust programming language")
60        .with_thinking_budget(1024)
61        .with_thoughts_included(true)
62        .execute()
63        .await?;
64
65    // Display thinking process
66    let thoughts2 = response2.thoughts();
67    if !thoughts2.is_empty() {
68        println!("Thinking summary:");
69        for (i, thought) in thoughts2.iter().enumerate() {
70            println!("Thought {}: {}\n", i + 1, thought);
71        }
72    }
73
74    println!("Answer: {}\n", response2.text());
75
76    // Example 3: Disable thinking feature
77    println!("--- Example 3: Disable thinking feature ---");
78    let response3 = client
79        .generate_content()
80        .with_system_prompt("You are a helpful assistant.")
81        .with_user_message("What is artificial intelligence?")
82        .execute()
83        .await?;
84
85    println!("Answer: {}\n", response3.text());
86
87    // Example 4: Use GenerationConfig to set thinking
88    println!("--- Example 4: Use GenerationConfig to set thinking ---");
89    let thinking_config = ThinkingConfig::new()
90        .with_thinking_budget(2048)
91        .with_thoughts_included(true);
92
93    let generation_config = GenerationConfig {
94        temperature: Some(0.7),
95        max_output_tokens: Some(500),
96        thinking_config: Some(thinking_config),
97        ..Default::default()
98    };
99
100    let response4 = client
101        .generate_content()
102        .with_system_prompt("You are a creative writing assistant.")
103        .with_user_message(
104            "Write the opening of a short story about a robot learning to feel emotions.",
105        )
106        .with_generation_config(generation_config)
107        .execute()
108        .await?;
109
110    // Display thinking process
111    let thoughts4 = response4.thoughts();
112    if !thoughts4.is_empty() {
113        println!("Thinking summary:");
114        for (i, thought) in thoughts4.iter().enumerate() {
115            println!("Thought {}: {}\n", i + 1, thought);
116        }
117    }
118
119    println!("Answer: {}\n", response4.text());
120
121    Ok(())
122}
More examples
Hide additional examples
examples/thinking_advanced.rs (line 123)
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::with_model(api_key, "models/gemini-2.5-pro".to_string());
14
15    println!("=== Gemini 2.5 Thinking Advanced Example ===\n");
16
17    // Example 1: Streaming with thinking
18    println!("--- Example 1: Streaming with thinking ---");
19    let mut stream = client
20        .generate_content()
21        .with_system_prompt("You are a mathematics expert skilled at solving complex mathematical problems.")
22        .with_user_message("Solve this math problem: Find the sum of the first 50 prime numbers. Please explain your solution process in detail.")
23        .with_thinking_budget(2048)
24        .with_thoughts_included(true)
25        .execute_stream()
26        .await?;
27
28    println!("Streaming response:");
29    let mut thoughts_shown = false;
30    while let Some(chunk_result) = stream.next().await {
31        match chunk_result {
32            Ok(chunk) => {
33                // Check if there's thinking content
34                let thoughts = chunk.thoughts();
35                if !thoughts.is_empty() && !thoughts_shown {
36                    println!("\nThinking process:");
37                    for (i, thought) in thoughts.iter().enumerate() {
38                        println!("Thought {}: {}", i + 1, thought);
39                    }
40                    println!("\nAnswer:");
41                    thoughts_shown = true;
42                }
43
44                // Display general text content
45                print!("{}", chunk.text());
46                std::io::Write::flush(&mut std::io::stdout())?;
47            }
48            Err(e) => eprintln!("Streaming error: {}", e),
49        }
50    }
51    println!("\n");
52
53    // Example 2: Thinking combined with function calls
54    println!("--- Example 2: Thinking combined with function calls ---");
55
56    // Define a calculator function
57    let calculator = FunctionDeclaration::new(
58        "calculate",
59        "Perform basic mathematical calculations",
60        FunctionParameters::object()
61            .with_property(
62                "expression",
63                PropertyDetails::string(
64                    "The mathematical expression to calculate, e.g., '2 + 3 * 4'",
65                ),
66                true,
67            )
68            .with_property(
69                "operation_type",
70                PropertyDetails::enum_type("Type of calculation", ["arithmetic", "advanced"]),
71                false,
72            ),
73    );
74
75    let response = client
76        .generate_content()
77        .with_system_prompt("You are a mathematics assistant. When calculations are needed, use the provided calculator function.")
78        .with_user_message("Calculate the result of (15 + 25) * 3 - 8 and explain the calculation steps.")
79        .with_function(calculator)
80        .with_thinking_budget(1024)
81        .with_thoughts_included(true)
82        .execute()
83        .await?;
84
85    // Display thinking process
86    let thoughts = response.thoughts();
87    if !thoughts.is_empty() {
88        println!("Thinking process:");
89        for (i, thought) in thoughts.iter().enumerate() {
90            println!("Thought {}: {}\n", i + 1, thought);
91        }
92    }
93
94    // Check for function calls
95    let function_calls = response.function_calls();
96    if !function_calls.is_empty() {
97        println!("Function calls:");
98        for (i, call) in function_calls.iter().enumerate() {
99            println!("Call {}: {} Args: {}", i + 1, call.name, call.args);
100        }
101        println!();
102    }
103
104    println!("Answer: {}\n", response.text());
105
106    // Example 3: Complex reasoning task
107    println!("--- Example 3: Complex reasoning task ---");
108    let complex_response = client
109        .generate_content()
110        .with_system_prompt("You are a logical reasoning expert.")
111        .with_user_message(
112            "There are three people: Alice, Bob, and Carol, who live in red, green, and blue houses respectively.\
113            Given:\
114            1. The person in the red house owns a cat\
115            2. Bob does not live in the green house\
116            3. Carol owns a dog\
117            4. The green house is to the left of the red house\
118            5. Alice does not own a cat\
119            Please reason out which color house each person lives in and what pets they own.",
120        )
121        .with_thinking_config(
122            ThinkingConfig::new()
123                .with_thinking_budget(3072)
124                .with_thoughts_included(true),
125        )
126        .execute()
127        .await?;
128
129    // Display thinking process
130    let complex_thoughts = complex_response.thoughts();
131    if !complex_thoughts.is_empty() {
132        println!("Reasoning process:");
133        for (i, thought) in complex_thoughts.iter().enumerate() {
134            println!("Reasoning step {}: {}\n", i + 1, thought);
135        }
136    }
137
138    println!("Conclusion: {}\n", complex_response.text());
139
140    // Display token usage statistics
141    if let Some(usage) = &complex_response.usage_metadata {
142        println!("Token usage statistics:");
143        println!("  Prompt tokens: {}", usage.prompt_token_count);
144        println!(
145            "  Response tokens: {}",
146            usage.candidates_token_count.unwrap_or(0)
147        );
148        if let Some(thinking_tokens) = usage.thoughts_token_count {
149            println!("  Thinking tokens: {}", thinking_tokens);
150        }
151        println!("  Total tokens: {}", usage.total_token_count);
152    }
153
154    Ok(())
155}
Source

pub fn with_dynamic_thinking(self) -> Self

Enable dynamic thinking (model decides the budget)

Source

pub fn with_thoughts_included(self, include: bool) -> Self

Include thought summaries in the response

Examples found in repository?
examples/thinking_basic.rs (line 91)
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6    // Get API key from environment variable
7    let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
8
9    // Create client
10    let client = Gemini::with_model(api_key, "models/gemini-2.5-pro".to_string());
11
12    println!("=== Gemini 2.5 Thinking Basic Example ===\n");
13
14    // Example 1: Using default dynamic thinking
15    println!(
16        "--- Example 1: Dynamic thinking (model automatically determines thinking budget) ---"
17    );
18    let response1 = client
19        .generate_content()
20        .with_system_prompt("You are a helpful mathematics assistant.")
21        .with_user_message(
22            "Explain Occam's razor principle and provide a simple example from daily life.",
23        )
24        .with_dynamic_thinking()
25        .with_thoughts_included(true)
26        .execute()
27        .await?;
28
29    // Display thinking process
30    let thoughts = response1.thoughts();
31    if !thoughts.is_empty() {
32        println!("Thinking summary:");
33        for (i, thought) in thoughts.iter().enumerate() {
34            println!("Thought {}: {}\n", i + 1, thought);
35        }
36    }
37
38    println!("Answer: {}\n", response1.text());
39
40    // Display token usage
41    if let Some(usage) = &response1.usage_metadata {
42        println!("Token usage:");
43        println!("  Prompt tokens: {}", usage.prompt_token_count);
44        println!(
45            "  Response tokens: {}",
46            usage.candidates_token_count.unwrap_or(0)
47        );
48        if let Some(thinking_tokens) = usage.thoughts_token_count {
49            println!("  Thinking tokens: {}", thinking_tokens);
50        }
51        println!("  Total tokens: {}\n", usage.total_token_count);
52    }
53
54    // Example 2: Set specific thinking budget
55    println!("--- Example 2: Set thinking budget (1024 tokens) ---");
56    let response2 = client
57        .generate_content()
58        .with_system_prompt("You are a helpful programming assistant.")
59        .with_user_message("List 3 main advantages of using the Rust programming language")
60        .with_thinking_budget(1024)
61        .with_thoughts_included(true)
62        .execute()
63        .await?;
64
65    // Display thinking process
66    let thoughts2 = response2.thoughts();
67    if !thoughts2.is_empty() {
68        println!("Thinking summary:");
69        for (i, thought) in thoughts2.iter().enumerate() {
70            println!("Thought {}: {}\n", i + 1, thought);
71        }
72    }
73
74    println!("Answer: {}\n", response2.text());
75
76    // Example 3: Disable thinking feature
77    println!("--- Example 3: Disable thinking feature ---");
78    let response3 = client
79        .generate_content()
80        .with_system_prompt("You are a helpful assistant.")
81        .with_user_message("What is artificial intelligence?")
82        .execute()
83        .await?;
84
85    println!("Answer: {}\n", response3.text());
86
87    // Example 4: Use GenerationConfig to set thinking
88    println!("--- Example 4: Use GenerationConfig to set thinking ---");
89    let thinking_config = ThinkingConfig::new()
90        .with_thinking_budget(2048)
91        .with_thoughts_included(true);
92
93    let generation_config = GenerationConfig {
94        temperature: Some(0.7),
95        max_output_tokens: Some(500),
96        thinking_config: Some(thinking_config),
97        ..Default::default()
98    };
99
100    let response4 = client
101        .generate_content()
102        .with_system_prompt("You are a creative writing assistant.")
103        .with_user_message(
104            "Write the opening of a short story about a robot learning to feel emotions.",
105        )
106        .with_generation_config(generation_config)
107        .execute()
108        .await?;
109
110    // Display thinking process
111    let thoughts4 = response4.thoughts();
112    if !thoughts4.is_empty() {
113        println!("Thinking summary:");
114        for (i, thought) in thoughts4.iter().enumerate() {
115            println!("Thought {}: {}\n", i + 1, thought);
116        }
117    }
118
119    println!("Answer: {}\n", response4.text());
120
121    Ok(())
122}
More examples
Hide additional examples
examples/thinking_advanced.rs (line 124)
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::with_model(api_key, "models/gemini-2.5-pro".to_string());
14
15    println!("=== Gemini 2.5 Thinking Advanced Example ===\n");
16
17    // Example 1: Streaming with thinking
18    println!("--- Example 1: Streaming with thinking ---");
19    let mut stream = client
20        .generate_content()
21        .with_system_prompt("You are a mathematics expert skilled at solving complex mathematical problems.")
22        .with_user_message("Solve this math problem: Find the sum of the first 50 prime numbers. Please explain your solution process in detail.")
23        .with_thinking_budget(2048)
24        .with_thoughts_included(true)
25        .execute_stream()
26        .await?;
27
28    println!("Streaming response:");
29    let mut thoughts_shown = false;
30    while let Some(chunk_result) = stream.next().await {
31        match chunk_result {
32            Ok(chunk) => {
33                // Check if there's thinking content
34                let thoughts = chunk.thoughts();
35                if !thoughts.is_empty() && !thoughts_shown {
36                    println!("\nThinking process:");
37                    for (i, thought) in thoughts.iter().enumerate() {
38                        println!("Thought {}: {}", i + 1, thought);
39                    }
40                    println!("\nAnswer:");
41                    thoughts_shown = true;
42                }
43
44                // Display general text content
45                print!("{}", chunk.text());
46                std::io::Write::flush(&mut std::io::stdout())?;
47            }
48            Err(e) => eprintln!("Streaming error: {}", e),
49        }
50    }
51    println!("\n");
52
53    // Example 2: Thinking combined with function calls
54    println!("--- Example 2: Thinking combined with function calls ---");
55
56    // Define a calculator function
57    let calculator = FunctionDeclaration::new(
58        "calculate",
59        "Perform basic mathematical calculations",
60        FunctionParameters::object()
61            .with_property(
62                "expression",
63                PropertyDetails::string(
64                    "The mathematical expression to calculate, e.g., '2 + 3 * 4'",
65                ),
66                true,
67            )
68            .with_property(
69                "operation_type",
70                PropertyDetails::enum_type("Type of calculation", ["arithmetic", "advanced"]),
71                false,
72            ),
73    );
74
75    let response = client
76        .generate_content()
77        .with_system_prompt("You are a mathematics assistant. When calculations are needed, use the provided calculator function.")
78        .with_user_message("Calculate the result of (15 + 25) * 3 - 8 and explain the calculation steps.")
79        .with_function(calculator)
80        .with_thinking_budget(1024)
81        .with_thoughts_included(true)
82        .execute()
83        .await?;
84
85    // Display thinking process
86    let thoughts = response.thoughts();
87    if !thoughts.is_empty() {
88        println!("Thinking process:");
89        for (i, thought) in thoughts.iter().enumerate() {
90            println!("Thought {}: {}\n", i + 1, thought);
91        }
92    }
93
94    // Check for function calls
95    let function_calls = response.function_calls();
96    if !function_calls.is_empty() {
97        println!("Function calls:");
98        for (i, call) in function_calls.iter().enumerate() {
99            println!("Call {}: {} Args: {}", i + 1, call.name, call.args);
100        }
101        println!();
102    }
103
104    println!("Answer: {}\n", response.text());
105
106    // Example 3: Complex reasoning task
107    println!("--- Example 3: Complex reasoning task ---");
108    let complex_response = client
109        .generate_content()
110        .with_system_prompt("You are a logical reasoning expert.")
111        .with_user_message(
112            "There are three people: Alice, Bob, and Carol, who live in red, green, and blue houses respectively.\
113            Given:\
114            1. The person in the red house owns a cat\
115            2. Bob does not live in the green house\
116            3. Carol owns a dog\
117            4. The green house is to the left of the red house\
118            5. Alice does not own a cat\
119            Please reason out which color house each person lives in and what pets they own.",
120        )
121        .with_thinking_config(
122            ThinkingConfig::new()
123                .with_thinking_budget(3072)
124                .with_thoughts_included(true),
125        )
126        .execute()
127        .await?;
128
129    // Display thinking process
130    let complex_thoughts = complex_response.thoughts();
131    if !complex_thoughts.is_empty() {
132        println!("Reasoning process:");
133        for (i, thought) in complex_thoughts.iter().enumerate() {
134            println!("Reasoning step {}: {}\n", i + 1, thought);
135        }
136    }
137
138    println!("Conclusion: {}\n", complex_response.text());
139
140    // Display token usage statistics
141    if let Some(usage) = &complex_response.usage_metadata {
142        println!("Token usage statistics:");
143        println!("  Prompt tokens: {}", usage.prompt_token_count);
144        println!(
145            "  Response tokens: {}",
146            usage.candidates_token_count.unwrap_or(0)
147        );
148        if let Some(thinking_tokens) = usage.thoughts_token_count {
149            println!("  Thinking tokens: {}", thinking_tokens);
150        }
151        println!("  Total tokens: {}", usage.total_token_count);
152    }
153
154    Ok(())
155}

Trait Implementations§

Source§

impl Clone for ThinkingConfig

Source§

fn clone(&self) -> ThinkingConfig

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ThinkingConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ThinkingConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ThinkingConfig

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for ThinkingConfig

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,