potato-provider 0.24.0

Potato brands
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use crate::error::ProviderError;
use potato_type::anthropic::v1::response::AnthropicMessageResponse;
use potato_type::google::v1::generate::adk_response::AdkLlmResponse;
use potato_type::google::v1::generate::GenerateContentResponse;
use potato_type::google::PredictResponse;
use potato_type::openai::v1::OpenAIChatResponse;
use potato_type::prompt::MessageNum;
use potato_type::tools::ToolCallInfo;
use potato_type::traits::ResponseAdapter;
use potato_type::Provider;
use potato_util::utils::TokenLogProbs;
use potatohead_macro::dispatch_response_trait_method;
use pyo3::prelude::*;
use reqwest::header::HeaderMap;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;

pub const GENERATE_CONTENT: &str = "generateContent";
pub const EMBED_CONTENT: &str = "embedContent";
pub const CHAT_COMPLETIONS: &str = "chat/completions";
pub const PREDICT: &str = "predict";
pub const EMBEDDINGS: &str = "embeddings";
pub const MESSAGES: &str = "messages";

#[derive(Debug, PartialEq)]
pub enum ServiceType {
    Generate,
    Embed,
}

impl ServiceType {
    /// Get the service type string
    pub fn gemini_endpoint(&self) -> &'static str {
        match self {
            Self::Generate => GENERATE_CONTENT,
            Self::Embed => EMBED_CONTENT,
        }
    }
    pub fn vertex_endpoint(&self) -> &'static str {
        match self {
            Self::Generate => GENERATE_CONTENT,
            Self::Embed => PREDICT, // vertex uses "predict" for embeddings since it calls models directly
        }
    }

    pub fn openai_endpoint(&self) -> &'static str {
        match self {
            Self::Generate => CHAT_COMPLETIONS,
            Self::Embed => EMBEDDINGS,
        }
    }

    pub fn anthropic_endpoint(&self) -> &'static str {
        match self {
            Self::Generate => MESSAGES,
            Self::Embed => EMBEDDINGS,
        }
    }
}

/// Merges extra_body fields into the serialized prompt JSON object.
///
/// # Arguments
/// * `serialized_prompt` - Mutable reference to the JSON value to modify
/// * `extra_body` - Reference to the extra body JSON object to merge
///
/// # Example
/// ```rust
/// let mut prompt = serde_json::json!({"model": "gpt-4"});
/// let extra = serde_json::json!({"temperature": 0.7});
/// add_extra_body_to_prompt(&mut prompt, &extra);
/// ```
pub fn add_extra_body_to_prompt(serialized_prompt: &mut Value, extra_body: &Value) {
    if let (Some(prompt_obj), Some(extra_obj)) =
        (serialized_prompt.as_object_mut(), extra_body.as_object())
    {
        // Merge the extra_body fields into prompt
        for (key, value) in extra_obj {
            prompt_obj.insert(key.clone(), value.clone());
        }
    }
}

pub fn build_http_client(default_headers: Option<HeaderMap>) -> Result<Client, ProviderError> {
    let headers = default_headers.unwrap_or_default();

    Client::builder()
        .default_headers(headers)
        .timeout(std::time::Duration::from_secs(30))
        .build()
        .map_err(ProviderError::from)
}

/// Unified ChatResponse enum to encapsulate different provider responses
/// Follows  our strategy pattern for dispatching methods to the appropriate inner type
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ChatResponse {
    OpenAIV1(OpenAIChatResponse),
    GeminiV1(GenerateContentResponse),
    VertexGenerateV1(GenerateContentResponse),
    VertexPredictV1(PredictResponse),
    AnthropicMessageV1(AnthropicMessageResponse),
    AdkLlmV1(Box<AdkLlmResponse>),
}

impl ChatResponse {
    /// Returns the token usage as a Python object
    pub fn token_usage<'py>(&self, py: Python<'py>) -> Result<Bound<'py, PyAny>, ProviderError> {
        Ok(dispatch_response_trait_method!(
            self,
            ResponseAdapter,
            usage(py)
        )?)
    }

    /// Converts the response to a Python object
    pub fn to_bound_py_object<'py>(
        &self,
        py: Python<'py>,
    ) -> Result<Bound<'py, PyAny>, ProviderError> {
        Ok(dispatch_response_trait_method!(
            self,
            ResponseAdapter,
            to_bound_py_object(py)
        )?)
    }

    /// Returns the string representation of the response
    pub fn __str__(&self) -> String {
        dispatch_response_trait_method!(self, ResponseAdapter, __str__())
    }

    /// Checks if the response is empty
    pub fn is_empty(&self) -> bool {
        dispatch_response_trait_method!(self, ResponseAdapter, is_empty())
    }

    /// Converts the response to a vector of MessageNum
    pub fn id(&self) -> String {
        dispatch_response_trait_method!(self, ResponseAdapter, id()).to_string()
    }

    /// Converts the response to a vector of MessageNum
    pub fn structured_output<'py>(
        &self,
        py: Python<'py>,
        output_type: Option<&Bound<'py, PyAny>>,
    ) -> Result<Bound<'py, PyAny>, ProviderError> {
        Ok(dispatch_response_trait_method!(
            self,
            ResponseAdapter,
            structured_output(py, output_type)
        )?)
    }

    pub fn get_log_probs(&self) -> Vec<TokenLogProbs> {
        dispatch_response_trait_method!(self, ResponseAdapter, get_log_probs())
    }

    /// Converts the response messages to a vector of MessageNum for requests
    /// If necessary, will convert each message to the appropriate provider format
    pub fn to_message_num(&self, provider: &Provider) -> Result<Vec<MessageNum>, ProviderError> {
        // convert response to MessageNum of existing provider type
        let mut messages =
            dispatch_response_trait_method!(self, ResponseAdapter, to_message_num())?;

        // convert each message to the target provider type if needed
        // if the current message provider type matches the target provider, no conversion done
        for msg in messages.iter_mut() {
            msg.convert_message(provider)?;
        }
        Ok(messages)
    }

    /// Retrieves the structured output value as a serde_json::Value
    /// output is either a structure response or tool call data
    pub fn extract_structured_data(&self) -> Option<Value> {
        if let Some(output) =
            dispatch_response_trait_method!(self, ResponseAdapter, structured_output_value())
        {
            Some(output)
        } else {
            dispatch_response_trait_method!(self, ResponseAdapter, tool_call_output())
        }
    }

    pub fn response_text(&self) -> String {
        dispatch_response_trait_method!(self, ResponseAdapter, response_text())
    }

    /// Extracts tool calls from the response, if any.
    pub fn extract_tool_calls(&self) -> Option<Vec<potato_type::tools::ToolCall>> {
        dispatch_response_trait_method!(self, ResponseAdapter, extract_tool_calls())
    }
    /// Helper for deserializing a JSON value into the appropriate ChatResponse variant.
    ///
    /// When a `provider` hint is given, deserialization is attempted directly for that provider's
    /// type — this avoids heuristic misrouting (e.g. ADK responses without `"partial"`).
    /// When `provider` is `None` or `Undefined`, the JSON keys are inspected heuristically.
    pub fn from_response_value(
        value: Value,
        provider: Option<&Provider>,
    ) -> Result<Self, ProviderError> {
        match provider {
            Some(p) if *p != Provider::Undefined => {
                Self::from_response_value_with_provider(value, p)
            }
            _ => Self::from_response_value_heuristic(value),
        }
    }

    /// Provider-hinted path: direct deserialization based on known provider.
    fn from_response_value_with_provider(
        value: Value,
        provider: &Provider,
    ) -> Result<Self, ProviderError> {
        match provider {
            Provider::OpenAI => serde_json::from_value::<OpenAIChatResponse>(value)
                .map(ChatResponse::OpenAIV1)
                .map_err(|e| {
                    tracing::warn!("Failed to deserialize OpenAIChatResponse: {e}");
                    ProviderError::DeserializationError
                }),
            Provider::Gemini => serde_json::from_value::<GenerateContentResponse>(value)
                .map(ChatResponse::GeminiV1)
                .map_err(|e| {
                    tracing::warn!("Failed to deserialize GenerateContentResponse: {e}");
                    ProviderError::DeserializationError
                }),
            Provider::Google | Provider::Vertex => {
                let obj = value
                    .as_object()
                    .ok_or(ProviderError::DeserializationError)?;
                if obj.contains_key("predictions") {
                    serde_json::from_value::<PredictResponse>(value)
                        .map(ChatResponse::VertexPredictV1)
                        .map_err(|e| {
                            tracing::warn!("Failed to deserialize PredictResponse: {e}");
                            ProviderError::DeserializationError
                        })
                } else {
                    serde_json::from_value::<GenerateContentResponse>(value)
                        .map(ChatResponse::VertexGenerateV1)
                        .map_err(|e| {
                            tracing::warn!("Failed to deserialize GenerateContentResponse: {e}");
                            ProviderError::DeserializationError
                        })
                }
            }
            Provider::Anthropic => serde_json::from_value::<AnthropicMessageResponse>(value)
                .map(ChatResponse::AnthropicMessageV1)
                .map_err(|e| {
                    tracing::warn!("Failed to deserialize AnthropicMessageResponse: {e}");
                    ProviderError::DeserializationError
                }),
            Provider::GoogleAdk => serde_json::from_value::<AdkLlmResponse>(value)
                .map(|r| ChatResponse::AdkLlmV1(Box::new(r)))
                .map_err(|e| {
                    tracing::warn!("Failed to deserialize AdkLlmResponse: {e}");
                    ProviderError::DeserializationError
                }),
            // Undefined is guarded at the entry point; reaching here is unreachable in
            // practice, but the pattern must be exhaustive — delegate to heuristic.
            Provider::Undefined => Self::from_response_value_heuristic(value),
        }
    }

    /// ADK-specific keys that distinguish an ADK LlmResponse from other Google responses.
    ///
    /// Includes the unambiguously ADK-exclusive event fields plus the snake_case metadata keys
    /// (`usage_metadata`, `model_version`) that ADK uses instead of Gemini's camelCase
    /// equivalents (`usageMetadata`, `modelVersion`).
    const ADK_SPECIFIC_KEYS: &'static [&'static str] = &[
        "partial",
        "turn_complete",
        "interrupted",
        "error_code",
        "error_message",
        "interaction_id",
        "live_session_resumption_update",
        "input_transcription",
        "output_transcription",
        "custom_metadata",
        "usage_metadata",
        "model_version",
    ];

    /// Heuristic path: inspect JSON keys when provider is unknown.
    fn from_response_value_heuristic(value: Value) -> Result<Self, ProviderError> {
        let obj = value
            .as_object()
            .ok_or(ProviderError::DeserializationError)?;

        if obj.contains_key("choices") {
            serde_json::from_value::<OpenAIChatResponse>(value)
                .map(ChatResponse::OpenAIV1)
                .map_err(|e| {
                    tracing::warn!("Failed to deserialize OpenAIChatResponse: {e}");
                    ProviderError::DeserializationError
                })
        } else if obj.contains_key("predictions") {
            serde_json::from_value::<PredictResponse>(value)
                .map(ChatResponse::VertexPredictV1)
                .map_err(|e| {
                    tracing::warn!("Failed to deserialize PredictResponse: {e}");
                    ProviderError::DeserializationError
                })
        } else if obj.contains_key("stop_reason") && obj.contains_key("content") {
            serde_json::from_value::<AnthropicMessageResponse>(value)
                .map(ChatResponse::AnthropicMessageV1)
                .map_err(|e| {
                    tracing::warn!("Failed to deserialize AnthropicMessageResponse: {e}");
                    ProviderError::DeserializationError
                })
        } else if Self::ADK_SPECIFIC_KEYS.iter().any(|k| obj.contains_key(*k)) {
            // Any ADK-specific key (including snake_case variants like usage_metadata /
            // model_version that differ from Gemini's camelCase equivalents) routes here.
            // This check comes before the Gemini "candidates" check so that ADK responses
            // that also contain "candidates" are not misrouted to GeminiV1.
            serde_json::from_value::<AdkLlmResponse>(value)
                .map(|r| ChatResponse::AdkLlmV1(Box::new(r)))
                .map_err(|e| {
                    tracing::warn!("Failed to deserialize AdkLlmResponse: {e}");
                    ProviderError::DeserializationError
                })
        } else if obj.contains_key("candidates") {
            // Gemini / Vertex generate — can't distinguish from JSON alone
            serde_json::from_value::<GenerateContentResponse>(value)
                .map(ChatResponse::GeminiV1)
                .map_err(|e| {
                    tracing::warn!("Failed to deserialize GenerateContentResponse: {e}");
                    ProviderError::DeserializationError
                })
        } else {
            Err(ProviderError::DeserializationError)
        }
    }

    pub fn model_name(&self) -> Option<String> {
        dispatch_response_trait_method!(self, ResponseAdapter, model_name()).map(|s| s.to_string())
    }
    pub fn finish_reason_str(&self) -> Option<String> {
        dispatch_response_trait_method!(self, ResponseAdapter, finish_reason())
            .map(|s| s.to_string())
    }
    pub fn input_tokens(&self) -> Option<i64> {
        dispatch_response_trait_method!(self, ResponseAdapter, input_tokens())
    }
    pub fn output_tokens(&self) -> Option<i64> {
        dispatch_response_trait_method!(self, ResponseAdapter, output_tokens())
    }
    pub fn total_tokens(&self) -> Option<i64> {
        dispatch_response_trait_method!(self, ResponseAdapter, total_tokens())
    }

    pub fn get_tool_calls(&self) -> Vec<ToolCallInfo> {
        dispatch_response_trait_method!(self, ResponseAdapter, get_tool_calls())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn openai_json() -> Value {
        serde_json::json!({
            "id": "chatcmpl-test",
            "object": "chat.completion",
            "created": 1700000000,
            "model": "gpt-4o",
            "choices": [{
                "message": {"content": "Hello!", "role": "assistant"},
                "finish_reason": "stop"
            }],
            "usage": {
                "completion_tokens": 5,
                "prompt_tokens": 10,
                "total_tokens": 15
            }
        })
    }

    fn anthropic_json() -> Value {
        serde_json::json!({
            "id": "msg_test",
            "model": "claude-sonnet-4-20250514",
            "role": "assistant",
            "stop_reason": "end_turn",
            "stop_sequence": null,
            "type": "message",
            "usage": {"input_tokens": 25, "output_tokens": 10},
            "content": [{"type": "text", "text": "Hello from Claude!"}]
        })
    }

    fn gemini_json() -> Value {
        serde_json::json!({
            "candidates": [{
                "content": {
                    "role": "model",
                    "parts": [{"text": "Hello from Gemini!"}]
                },
                "finishReason": "STOP"
            }],
            "modelVersion": "gemini-2.0-flash",
            "usageMetadata": {
                "promptTokenCount": 12,
                "candidatesTokenCount": 8,
                "totalTokenCount": 20
            }
        })
    }

    fn predict_json() -> Value {
        serde_json::json!({
            "predictions": [{"embeddings": {"values": [0.1, 0.2]}}],
            "metadata": {},
            "deployedModelId": "dm-1",
            "model": "gecko@003",
            "modelVersionId": "1",
            "modelDisplayName": "Gecko"
        })
    }

    #[test]
    fn test_from_response_value_openai() {
        let resp = ChatResponse::from_response_value(openai_json(), None).unwrap();
        assert!(matches!(resp, ChatResponse::OpenAIV1(_)));
        assert_eq!(resp.response_text(), "Hello!");
        assert_eq!(resp.model_name(), Some("gpt-4o".to_string()));
        assert_eq!(resp.finish_reason_str(), Some("stop".to_string()));
        assert_eq!(resp.input_tokens(), Some(10));
        assert_eq!(resp.output_tokens(), Some(5));
        assert_eq!(resp.total_tokens(), Some(15));
    }

    #[test]
    fn test_from_response_value_anthropic() {
        let resp = ChatResponse::from_response_value(anthropic_json(), None).unwrap();
        assert!(matches!(resp, ChatResponse::AnthropicMessageV1(_)));
        assert_eq!(resp.response_text(), "Hello from Claude!");
        assert_eq!(
            resp.model_name(),
            Some("claude-sonnet-4-20250514".to_string())
        );
        assert_eq!(resp.finish_reason_str(), Some("end_turn".to_string()));
        assert_eq!(resp.input_tokens(), Some(25));
        assert_eq!(resp.output_tokens(), Some(10));
        assert_eq!(resp.total_tokens(), Some(35));
    }

    #[test]
    fn test_from_response_value_gemini() {
        let resp = ChatResponse::from_response_value(gemini_json(), None).unwrap();
        assert!(matches!(resp, ChatResponse::GeminiV1(_)));
        assert_eq!(resp.response_text(), "Hello from Gemini!");
        assert_eq!(resp.model_name(), Some("gemini-2.0-flash".to_string()));
        assert_eq!(resp.finish_reason_str(), Some("STOP".to_string()));
        assert_eq!(resp.input_tokens(), Some(12));
        assert_eq!(resp.output_tokens(), Some(8));
        assert_eq!(resp.total_tokens(), Some(20));
    }

    fn adk_json() -> Value {
        serde_json::json!({
            "model_version": "google/gemini-3-flash-preview",
            "content": {
                "role": "model",
                "parts": [{"text": "Hello from ADK!"}]
            },
            "partial": false,
            "turn_complete": true,
            "finish_reason": "STOP",
            "usage_metadata": {
                "prompt_token_count": 20,
                "candidates_token_count": 10,
                "total_token_count": 30
            }
        })
    }

    #[test]
    fn test_from_response_value_adk() {
        let resp = ChatResponse::from_response_value(adk_json(), None).unwrap();
        assert!(matches!(resp, ChatResponse::AdkLlmV1(_)));
        assert_eq!(resp.response_text(), "Hello from ADK!");
        assert_eq!(
            resp.model_name(),
            Some("google/gemini-3-flash-preview".to_string())
        );
        assert_eq!(resp.finish_reason_str(), Some("STOP".to_string()));
        assert_eq!(resp.input_tokens(), Some(20));
        assert_eq!(resp.output_tokens(), Some(10));
        assert_eq!(resp.total_tokens(), Some(30));
    }

    #[test]
    fn test_from_response_value_adk_partial_null() {
        // Pydantic wire format: "partial" key present but null value
        let json = serde_json::json!({
            "model_version": "google/gemini-3-flash-preview",
            "content": {
                "role": "model",
                "parts": [{"text": "Hello from ADK!"}]
            },
            "partial": null,
            "turn_complete": true,
            "finish_reason": "STOP",
            "usage_metadata": {
                "prompt_token_count": 20,
                "candidates_token_count": 10,
                "total_token_count": 30
            }
        });
        let resp = ChatResponse::from_response_value(json, None).unwrap();
        assert!(matches!(resp, ChatResponse::AdkLlmV1(_)));
        assert_eq!(resp.response_text(), "Hello from ADK!");
    }

    #[test]
    fn test_gemini_provider_hint_overrides_adk_heuristic() {
        // A response with "candidates" + "partial" would route to ADK heuristically (since
        // "partial" is in ADK_SPECIFIC_KEYS), but a Gemini provider hint bypasses the heuristic.
        let json = serde_json::json!({
            "candidates": [{"content": {"role": "model", "parts": [{"text": "hi"}]}}],
            "partial": false
        });
        let resp = ChatResponse::from_response_value(json, Some(&Provider::Gemini)).unwrap();
        assert!(matches!(resp, ChatResponse::GeminiV1(_)));
    }

    #[test]
    fn test_from_response_value_predict() {
        let resp = ChatResponse::from_response_value(predict_json(), None).unwrap();
        assert!(matches!(resp, ChatResponse::VertexPredictV1(_)));
        assert_eq!(resp.model_name(), Some("gecko@003".to_string()));
        assert!(!resp.is_empty());
    }

    #[test]
    fn test_from_response_value_unknown() {
        let unknown = serde_json::json!({"unknown_field": true});
        assert!(ChatResponse::from_response_value(unknown, None).is_err());
    }

    #[test]
    fn test_from_response_value_not_object() {
        assert!(ChatResponse::from_response_value(serde_json::json!("string"), None).is_err());
        assert!(ChatResponse::from_response_value(serde_json::json!(42), None).is_err());
    }

    #[test]
    fn test_is_empty_dispatch() {
        let resp = ChatResponse::from_response_value(openai_json(), None).unwrap();
        assert!(!resp.is_empty());
    }

    #[test]
    fn test_id_dispatch() {
        let resp = ChatResponse::from_response_value(openai_json(), None).unwrap();
        assert_eq!(resp.id(), "chatcmpl-test");
    }

    #[test]
    fn test_extract_structured_data_json() {
        let json = serde_json::json!({
            "id": "chatcmpl-json",
            "object": "chat.completion",
            "created": 1700000000,
            "model": "gpt-4o",
            "choices": [{
                "message": {"content": "{\"name\":\"Alice\"}", "role": "assistant"},
                "finish_reason": "stop"
            }],
            "usage": {"completion_tokens": 5, "prompt_tokens": 10, "total_tokens": 15}
        });
        let resp = ChatResponse::from_response_value(json, None).unwrap();
        let data = resp.extract_structured_data();
        assert!(data.is_some());
        assert_eq!(data.unwrap()["name"], "Alice");
    }

    #[test]
    fn test_extract_structured_data_tool_call() {
        let json = serde_json::json!({
            "id": "chatcmpl-tc",
            "object": "chat.completion",
            "created": 1700000000,
            "model": "gpt-4o",
            "choices": [{
                "message": {
                    "content": null,
                    "role": "assistant",
                    "tool_calls": [{
                        "id": "call_1",
                        "type": "function",
                        "function": {"name": "search", "arguments": "{\"q\":\"rust\"}"}
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "usage": {"completion_tokens": 5, "prompt_tokens": 10, "total_tokens": 15}
        });
        let resp = ChatResponse::from_response_value(json, None).unwrap();
        let data = resp.extract_structured_data();
        assert!(data.is_some());
    }

    #[test]
    fn test_get_tool_calls_dispatch() {
        let json = serde_json::json!({
            "id": "msg_tools",
            "model": "claude-sonnet-4-20250514",
            "role": "assistant",
            "stop_reason": "tool_use",
            "type": "message",
            "usage": {"input_tokens": 10, "output_tokens": 5},
            "content": [
                {"type": "tool_use", "id": "toolu_01", "name": "search", "input": {"q": "test"}}
            ]
        });
        let resp = ChatResponse::from_response_value(json, None).unwrap();
        let calls = resp.get_tool_calls();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "search");
    }

    #[test]
    fn test_get_log_probs_dispatch() {
        let resp = ChatResponse::from_response_value(openai_json(), None).unwrap();
        assert!(resp.get_log_probs().is_empty());
    }

    // --- Provider-hinted tests ---

    #[test]
    fn test_adk_with_provider_hint_no_partial() {
        // The core broken case: valid ADK response without "partial" key
        let json = serde_json::json!({
            "model_version": "google/gemini-3-flash-preview",
            "content": {
                "role": "model",
                "parts": [{"text": "Hello from ADK!"}]
            },
            "turn_complete": true,
            "finish_reason": "STOP",
            "usage_metadata": {
                "prompt_token_count": 20,
                "candidates_token_count": 10,
                "total_token_count": 30
            }
        });
        let resp = ChatResponse::from_response_value(json, Some(&Provider::GoogleAdk)).unwrap();
        assert!(matches!(resp, ChatResponse::AdkLlmV1(_)));
        assert_eq!(resp.response_text(), "Hello from ADK!");
    }

    #[test]
    fn test_adk_heuristic_snake_case_signals_only() {
        // ADK response with only snake_case signals (no ADK-unique keys like partial/turn_complete)
        let json = serde_json::json!({
            "model_version": "google/gemini-3-flash-preview",
            "content": {
                "role": "model",
                "parts": [{"text": "Hello!"}]
            },
            "usage_metadata": {
                "prompt_token_count": 5,
                "candidates_token_count": 3,
                "total_token_count": 8
            }
        });
        let resp = ChatResponse::from_response_value(json, None).unwrap();
        assert!(matches!(resp, ChatResponse::AdkLlmV1(_)));
    }

    #[test]
    fn test_vertex_with_provider_hint_generates_vertex_variant() {
        // With Vertex hint, a generateContent response should yield VertexGenerateV1 (not GeminiV1)
        let json = gemini_json();
        let resp = ChatResponse::from_response_value(json, Some(&Provider::Vertex)).unwrap();
        assert!(matches!(resp, ChatResponse::VertexGenerateV1(_)));
    }

    #[test]
    fn test_undefined_provider_falls_through_to_heuristic() {
        let resp =
            ChatResponse::from_response_value(openai_json(), Some(&Provider::Undefined)).unwrap();
        assert!(matches!(resp, ChatResponse::OpenAIV1(_)));
    }

    #[test]
    fn test_openai_with_provider_hint() {
        let resp =
            ChatResponse::from_response_value(openai_json(), Some(&Provider::OpenAI)).unwrap();
        assert!(matches!(resp, ChatResponse::OpenAIV1(_)));
    }

    #[test]
    fn test_anthropic_with_provider_hint() {
        let resp = ChatResponse::from_response_value(anthropic_json(), Some(&Provider::Anthropic))
            .unwrap();
        assert!(matches!(resp, ChatResponse::AnthropicMessageV1(_)));
    }

    #[test]
    fn test_gemini_with_provider_hint() {
        let resp =
            ChatResponse::from_response_value(gemini_json(), Some(&Provider::Gemini)).unwrap();
        assert!(matches!(resp, ChatResponse::GeminiV1(_)));
    }

    #[test]
    fn test_predict_with_provider_hint() {
        let resp =
            ChatResponse::from_response_value(predict_json(), Some(&Provider::Vertex)).unwrap();
        assert!(matches!(resp, ChatResponse::VertexPredictV1(_)));
    }

    #[test]
    fn test_google_provider_hint_generate() {
        // Provider::Google with a generateContent response → VertexGenerateV1
        let resp =
            ChatResponse::from_response_value(gemini_json(), Some(&Provider::Google)).unwrap();
        assert!(matches!(resp, ChatResponse::VertexGenerateV1(_)));
    }

    #[test]
    fn test_google_provider_hint_predict() {
        // Provider::Google with a predictions response → VertexPredictV1
        let resp =
            ChatResponse::from_response_value(predict_json(), Some(&Provider::Google)).unwrap();
        assert!(matches!(resp, ChatResponse::VertexPredictV1(_)));
    }

    #[test]
    fn test_adk_heuristic_candidates_plus_usage_metadata_routes_adk() {
        // Regression guard: ADK responses can contain "candidates" alongside snake_case keys.
        // The ADK check (usage_metadata ∈ ADK_SPECIFIC_KEYS) must come before the Gemini
        // "candidates" check, or these responses would be silently misrouted to GeminiV1.
        let json = serde_json::json!({
            "candidates": [{"content": {"role": "model", "parts": [{"text": "hi"}]}}],
            "usage_metadata": {
                "prompt_token_count": 5,
                "candidates_token_count": 3,
                "total_token_count": 8
            }
        });
        let resp = ChatResponse::from_response_value(json, None).unwrap();
        assert!(matches!(resp, ChatResponse::AdkLlmV1(_)));
    }

    #[test]
    fn test_provider_hint_error_on_non_object_openai() {
        // A non-object value cannot deserialize into any struct — error path is exercised.
        assert!(ChatResponse::from_response_value(
            serde_json::json!("string"),
            Some(&Provider::OpenAI)
        )
        .is_err());
    }

    #[test]
    fn test_provider_hint_error_on_non_object_anthropic() {
        assert!(ChatResponse::from_response_value(
            serde_json::json!(42),
            Some(&Provider::Anthropic)
        )
        .is_err());
    }

    #[test]
    fn test_provider_hint_error_on_non_object_adk() {
        // AdkLlmResponse has all-optional fields so a bare `{}` deserializes successfully;
        // a non-object input must still return Err.
        assert!(ChatResponse::from_response_value(
            serde_json::json!("not an object"),
            Some(&Provider::GoogleAdk)
        )
        .is_err());
    }
}