adk-gemini 0.7.0

Rust client for Google Gemini API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use crate::{
    BlockReason, FinishReason, FunctionCall, GenerationResponse, HarmCategory, HarmProbability,
    Modality, Model, Part,
};
use serde::{Deserialize, Serialize};
use serde_json::json;

#[test]
fn test_model_deserialization() {
    #[derive(Serialize, Deserialize)]
    struct Response {
        model: Model,
    }

    let response = Response { model: Model::Custom("models/custom_gemini_model".to_string()) };
    let serialized = serde_json::to_string(&response).unwrap();
    let deserialized: Response = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized.model, response.model);

    let response = Response { model: Model::Gemini25Flash };
    let serialized = serde_json::to_string(&response).unwrap();
    let deserialized: Response = serde_json::from_str(&serialized).unwrap();
    assert_eq!(deserialized.model, response.model);
}

#[test]
fn test_thought_signature_deserialization() {
    // Test JSON that includes thoughtSignature like in the provided API response
    let json_response = json!({
        "candidates": [
            {
                "content": {
                    "parts": [
                        {
                            "functionCall": {
                                "name": "get_current_weather",
                                "args": {
                                    "location": "Kaohsiung Zuoying District"
                                }
                            },
                            "thoughtSignature": "CtwFAVSoXO4WSz0Ri3HddDzPQzsB8EaYsiQobiBKOzGOaAPM0d4DewrzUmhCnZbdboz+n+6v503fcy4epZC2bomn247laY6RHtKTc0UA8scj1DW/Y8w9AsfvjDX1adpIi043qjivTtowjxKAIesKoO69mFj6HTmGRI6sE1hamsIblZGZypowxnBQmxqJftl1aebB7kQN+MoYSeX+OU1z/8G+RXE+cb9cvwdAGIZjHXoGgEaIigYlrjTkZjRGBiI+gC2AcLNe32MHVla2/dmV8O7k8Cl45ksH+4srYABtmXLxjxwQK6s2bjVngvaRcBTCK4AUHiDb1j54n3Fls5J1i9k2sd6OcJYJuRlfwuxv2RMZ+V8zLdNthfSWtZwuJslkOD3uZCkEhO/hI6nAKcyuSokdAKtOw9g6LWORnEQoUJ+BaTVymN1tuJzbzrS9kPP5d3QJfFdQaILkk8CUdnGOEcngvlINN4MGNTQYN+0Au/JFWDWj33T5LZWkbDMp+yIpqFkZuRYwjW/9KOR6qFbxzvJyQcAKTxf0Sq7UfHTYBXTVp0/N4cDWRv+5DF0UOp+6emnPslCmaRK8JEGkmKkYXCzR6PpopfdzHHSDQHbNjjwr0h9ADZKehiB/cB1Jjy0oyBOM3HSHyuzcP8CO4NoAXOUM/VP5P41ys9TdeaPZAZ1E3cGQI4pifFVPdy3o33QSYqS1ce5Wxbeud06+d+sz2O7jJrfHMdgYpcO/2RcXQyK/GVIlDkWyxpYtBZhlkh3vLxPVmV/JJv5DQSS3YNTFSbfbwC8DtrI6YNFK5Vo07cl6mAY+U8b4ziFJk2HGuO27jq5EnhJE6v39HCfXTa8cKaLzpIURJSOs12S1rc3pqXdv4VBL6dp+Yjr8eQPxYRP93QzZMFXcYZ+Vc2H5mbnXbvTxVdYT7Qpu7aK1o6csSOMOx47NzZnOnlTWNJUxtU5UIZJ2JelOt/NsWnVJZY8D"
                        }
                    ],
                    "role": "model"
                },
                "finishReason": "STOP",
                "index": 0
            }
        ],
        "usageMetadata": {
            "promptTokenCount": 70,
            "candidatesTokenCount": 21,
            "totalTokenCount": 255,
            "thoughtsTokenCount": 164
        },
        "modelVersion": "gemini-2.5-pro",
        "responseId": "CCm8aJjzBaWh1MkP_cLEgQo"
    });

    // Test deserialization
    let response: GenerationResponse = serde_json::from_value(json_response).unwrap();

    // Verify basic structure
    assert_eq!(response.candidates.len(), 1);
    let candidate = &response.candidates[0];
    assert_eq!(candidate.finish_reason, Some(FinishReason::Stop));

    // Check content parts
    let parts = candidate.content.parts.as_ref().unwrap();
    assert_eq!(parts.len(), 1);

    // Verify the part is a function call with thought signature
    match &parts[0] {
        Part::FunctionCall { function_call, thought_signature } => {
            assert_eq!(function_call.name, "get_current_weather");
            assert_eq!(function_call.args["location"], "Kaohsiung Zuoying District");

            // Verify thought signature is present and not empty
            assert!(thought_signature.is_some());
            let signature = thought_signature.as_ref().unwrap();
            assert!(!signature.is_empty());
            assert!(signature.starts_with("CtwFAVSoXO4WSz0Ri3HddDzPQzsB8EaYsiQobiBKOzGOaAPM"));
        }
        _ => panic!("Expected FunctionCall part"),
    }

    // Test the function_calls_with_thoughts method
    let function_calls_with_thoughts = response.function_calls_with_thoughts();
    assert_eq!(function_calls_with_thoughts.len(), 1);

    let (function_call, thought_signature) = &function_calls_with_thoughts[0];
    assert_eq!(function_call.name, "get_current_weather");
    assert!(thought_signature.is_some());

    // Test usage metadata with thinking tokens
    assert!(response.usage_metadata.is_some());
    let usage = response.usage_metadata.as_ref().unwrap();
    assert_eq!(usage.thoughts_token_count, Some(164));
}

#[test]
fn test_function_call_with_thought_signature() {
    // Test creating a FunctionCall with thought signature
    let function_call = FunctionCall::with_thought_signature(
        "test_function",
        json!({"param": "value"}),
        "test_thought_signature",
    );

    assert_eq!(function_call.name, "test_function");
    assert_eq!(function_call.args["param"], "value");
    assert_eq!(function_call.thought_signature, Some("test_thought_signature".to_string()));

    // thoughtSignature is now serialized to support Gemini 3.x multi-turn tool calling.
    let serialized = serde_json::to_value(&function_call).unwrap();
    assert_eq!(
        serialized,
        json!({
            "name": "test_function",
            "args": {"param": "value"},
            "thoughtSignature": "test_thought_signature"
        })
    );

    // Accept both camelCase and legacy snake_case on input.
    let deserialized: FunctionCall = serde_json::from_value(json!({
        "name": "test_function",
        "args": {"param": "value"},
        "thoughtSignature": "test_thought_signature"
    }))
    .unwrap();
    assert_eq!(deserialized, function_call);
}

#[test]
fn test_function_call_without_thought_signature() {
    // Test creating a FunctionCall without thought signature (backward compatibility)
    let function_call = FunctionCall::new("test_function", json!({"param": "value"}));

    assert_eq!(function_call.name, "test_function");
    assert_eq!(function_call.args["param"], "value");
    assert_eq!(function_call.thought_signature, None);

    // Test serialization should not include thought_signature field when None
    let serialized = serde_json::to_string(&function_call).unwrap();
    assert!(!serialized.contains("thought_signature"));
    assert!(!serialized.contains("thoughtSignature"));
}

#[test]
fn test_multi_turn_content_structure() {
    // Test that we can create proper multi-turn content structure for maintaining thought context
    use crate::{Content, Part, Role};

    // Simulate a function call with thought signature from first turn
    let function_call = FunctionCall::with_thought_signature(
        "get_weather",
        json!({"location": "Tokyo"}),
        "sample_thought_signature",
    );

    // Create model content with function call and thought signature
    let model_content = Content {
        parts: Some(vec![Part::FunctionCall {
            function_call: function_call.clone(),
            thought_signature: Some("sample_thought_signature".to_string()),
        }]),
        role: Some(Role::Model),
    };

    // Verify structure
    assert!(model_content.parts.is_some());
    assert_eq!(model_content.role, Some(Role::Model));

    // thoughtSignature is now serialized to support Gemini 3.x multi-turn tool calling.
    let serialized = serde_json::to_value(&model_content).unwrap();
    assert_eq!(
        serialized,
        json!({
            "parts": [
                {
                    "functionCall": {
                        "name": "get_weather",
                        "args": {"location": "Tokyo"},
                        "thoughtSignature": "sample_thought_signature"
                    },
                    "thoughtSignature": "sample_thought_signature"
                }
            ],
            "role": "model"
        })
    );

    let parts = model_content.parts.unwrap();
    assert_eq!(parts.len(), 1);

    match &parts[0] {
        Part::FunctionCall { function_call, thought_signature } => {
            assert_eq!(function_call.name, "get_weather");
            assert_eq!(thought_signature.as_ref().unwrap(), "sample_thought_signature");
        }
        _ => panic!("Expected FunctionCall part"),
    }
}

#[test]
fn test_function_response_wraps_array_payloads() {
    use crate::Content;

    let content = Content::function_response_json("rag_search", json!([{ "id": "pricing" }]));
    let serialized = serde_json::to_value(&content).unwrap();

    assert_eq!(
        serialized,
        json!({
            "parts": [
                {
                    "functionResponse": {
                        "name": "rag_search",
                        "response": {
                            "result": [
                                { "id": "pricing" }
                            ]
                        }
                    }
                }
            ]
        })
    );
}

#[test]
fn test_text_with_thought_signature() {
    use crate::GenerationResponse;

    // Test JSON similar to the provided API response
    let json_response = json!({
        "candidates": [
            {
                "content": {
                    "parts": [
                        {
                            "text": "**Okay, here's what I'm thinking:**\n\nThe user wants me to show them...",
                            "thought": true
                        },
                        {
                            "text": "The following functions are available in the environment: `chat.get_message_count()`",
                            "thoughtSignature": "Cs4BA.../Yw="
                        }
                    ],
                    "role": "model"
                },
                "finishReason": "STOP",
                "index": 0
            }
        ],
        "usageMetadata": {
            "promptTokenCount": 36,
            "candidatesTokenCount": 18,
            "totalTokenCount": 96,
            "thoughtsTokenCount": 42
        },
        "modelVersion": "gemini-2.5-flash",
        "responseId": "gIC..."
    });

    // Test deserialization
    let response: GenerationResponse = serde_json::from_value(json_response).unwrap();

    // Verify basic structure
    assert_eq!(response.candidates.len(), 1);
    let candidate = &response.candidates[0];

    // Check content parts
    let parts = candidate.content.parts.as_ref().unwrap();
    assert_eq!(parts.len(), 2);

    // Check first part (thought without signature)
    match &parts[0] {
        Part::Text { text, thought, thought_signature } => {
            assert_eq!(*thought, Some(true));
            assert_eq!(*thought_signature, None);
            assert!(text.contains("here's what I'm thinking"));
        }
        _ => panic!("Expected Text part for first element"),
    }

    // Check second part (text with thought signature)
    match &parts[1] {
        Part::Text { text, thought, thought_signature } => {
            assert_eq!(*thought, None);
            assert!(thought_signature.is_some());
            assert_eq!(thought_signature.as_ref().unwrap(), "Cs4BA.../Yw=");
            assert!(text.contains("chat.get_message_count"));
        }
        _ => panic!("Expected Text part for second element"),
    }

    // Test the new text_with_thoughts method
    let text_with_thoughts = response.text_with_thoughts();
    assert_eq!(text_with_thoughts.len(), 2);

    let (first_text, is_thought, thought_sig) = &text_with_thoughts[0];
    assert!(*is_thought);
    assert!(thought_sig.is_none());
    assert!(first_text.contains("here's what I'm thinking"));

    let (second_text, is_thought, thought_sig) = &text_with_thoughts[1];
    assert!(!(*is_thought));
    assert!(thought_sig.is_some());
    assert_eq!(thought_sig.unwrap(), "Cs4BA.../Yw=");
    assert!(second_text.contains("chat.get_message_count"));
}

#[test]
fn test_content_creation_with_thought_signature() {
    // Test creating content with thought signature
    use crate::Content;
    let content = Content::text_with_thought_signature("Test response", "test_signature_123");

    let parts = content.parts.as_ref().unwrap();
    assert_eq!(parts.len(), 1);

    match &parts[0] {
        Part::Text { text, thought, thought_signature } => {
            assert_eq!(text, "Test response");
            assert_eq!(*thought, None);
            assert_eq!(thought_signature.as_ref().unwrap(), "test_signature_123");
        }
        _ => panic!("Expected Text part"),
    }

    // Test creating thought content with signature
    let thought_content =
        Content::thought_with_signature("This is my thinking process", "thought_signature_456");

    let parts = thought_content.parts.as_ref().unwrap();
    assert_eq!(parts.len(), 1);

    match &parts[0] {
        Part::Text { text, thought, thought_signature } => {
            assert_eq!(text, "This is my thinking process");
            assert_eq!(*thought, Some(true));
            assert_eq!(thought_signature.as_ref().unwrap(), "thought_signature_456");
        }
        _ => panic!("Expected Text part"),
    }
    // thoughtSignature is now serialized when present (Gemini 3.x support).
    let serialized = serde_json::to_string(&content).unwrap();
    assert!(serialized.contains("thoughtSignature"));

    // thought field IS serialized, and thoughtSignature IS serialized when present.
    let serialized_thought = serde_json::to_string(&thought_content).unwrap();
    assert!(serialized_thought.contains("thoughtSignature"));
    assert!(serialized_thought.contains("\"thought\":true"));
}

#[test]
fn test_vertex_numeric_enum_deserialization() {
    let finish_reason: FinishReason = serde_json::from_value(json!(1)).unwrap();
    assert_eq!(finish_reason, FinishReason::Stop);

    let block_reason: BlockReason = serde_json::from_value(json!(5)).unwrap();
    assert_eq!(block_reason, BlockReason::ModelArmor);

    let harm_category: HarmCategory = serde_json::from_value(json!(1)).unwrap();
    assert_eq!(harm_category, HarmCategory::HateSpeech);

    let harm_probability: HarmProbability = serde_json::from_value(json!(3)).unwrap();
    assert_eq!(harm_probability, HarmProbability::Medium);

    let modality: Modality = serde_json::from_value(json!(4)).unwrap();
    assert_eq!(modality, Modality::Audio);
}

#[test]
fn test_thinking_level_serialization() {
    use crate::ThinkingLevel;

    // ThinkingLevel serializes as lowercase
    let level = ThinkingLevel::Low;
    let json = serde_json::to_value(level).unwrap();
    assert_eq!(json, json!("low"));

    let level = ThinkingLevel::High;
    let json = serde_json::to_value(level).unwrap();
    assert_eq!(json, json!("high"));

    // Round-trip all variants
    for (variant, expected) in [
        (ThinkingLevel::Minimal, "minimal"),
        (ThinkingLevel::Low, "low"),
        (ThinkingLevel::Medium, "medium"),
        (ThinkingLevel::High, "high"),
    ] {
        let serialized = serde_json::to_string(&variant).unwrap();
        assert_eq!(serialized, format!("\"{expected}\""));
        let deserialized: ThinkingLevel = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, variant);
    }
}

#[test]
fn test_thinking_config_with_level() {
    use crate::{ThinkingConfig, ThinkingLevel};

    // Builder method sets thinking_level
    let config = ThinkingConfig::new()
        .with_thinking_level(ThinkingLevel::Medium)
        .with_thoughts_included(true);

    assert_eq!(config.thinking_level, Some(ThinkingLevel::Medium));
    assert_eq!(config.include_thoughts, Some(true));
    assert_eq!(config.thinking_budget, None);

    // Serializes correctly with camelCase
    let json = serde_json::to_value(&config).unwrap();
    assert_eq!(json["thinkingLevel"], json!("medium"));
    assert_eq!(json["includeThoughts"], json!(true));
    assert!(json.get("thinkingBudget").is_none());
}

#[test]
fn test_thinking_config_budget_and_level_independent() {
    use crate::{ThinkingConfig, ThinkingLevel};

    // Budget-only config (Gemini 2.5 style)
    let budget_config = ThinkingConfig::new().with_thinking_budget(2048);
    let json = serde_json::to_value(&budget_config).unwrap();
    assert_eq!(json["thinkingBudget"], json!(2048));
    assert!(json.get("thinkingLevel").is_none());

    // Level-only config (Gemini 3 style)
    let level_config = ThinkingConfig::new().with_thinking_level(ThinkingLevel::High);
    let json = serde_json::to_value(&level_config).unwrap();
    assert_eq!(json["thinkingLevel"], json!("high"));
    assert!(json.get("thinkingBudget").is_none());
}