potato-provider 0.17.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
use crate::error::ProviderError;
use potato_type::anthropic::v1::response::AnthropicMessageResponse;
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),
}

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())
    }

    /// Helper for deserializing a JSON value into the appropriate ChatResponse variant based on its structure.
    /// We won't always know which provider response type we're getting back, so we need to inspect the JSON to determine how to deserialize it.
    pub fn from_response_value(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(|_| ProviderError::DeserializationError)
        } else if obj.contains_key("predictions") {
            serde_json::from_value::<PredictResponse>(value)
                .map(ChatResponse::VertexPredictV1)
                .map_err(|_| ProviderError::DeserializationError)
        } else if obj.contains_key("candidates") {
            // Can't distinguish Gemini vs VertexGenerate from JSON alone
            serde_json::from_value::<GenerateContentResponse>(value)
                .map(ChatResponse::GeminiV1)
                .map_err(|_| ProviderError::DeserializationError)
        } else if obj.contains_key("stop_reason") && obj.contains_key("content") {
            serde_json::from_value::<AnthropicMessageResponse>(value)
                .map(ChatResponse::AnthropicMessageV1)
                .map_err(|_| 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()).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()).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()).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));
    }

    #[test]
    fn test_from_response_value_predict() {
        let resp = ChatResponse::from_response_value(predict_json()).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).is_err());
    }

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

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

    #[test]
    fn test_id_dispatch() {
        let resp = ChatResponse::from_response_value(openai_json()).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).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).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).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()).unwrap();
        assert!(resp.get_log_probs().is_empty());
    }
}