potato-type 0.26.0

Toppings for your potatoes
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
pub mod error;

pub use crate::error::TypeError;
use pyo3::prelude::*;
use schemars::JsonSchema;
use serde::de::Error;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::any::type_name;
use std::fmt;
use std::fmt::Display;
use std::path::{Path, PathBuf};
use tracing::error;
pub mod anthropic;
pub mod common;
pub mod google;
pub mod openai;
pub mod prompt;
pub mod spec;
pub mod tools;
pub mod traits;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[pyclass(from_py_object)]
pub enum Model {
    Undefined,
}

impl Model {
    pub fn as_str(&self) -> &str {
        match self {
            Model::Undefined => "undefined",
        }
    }

    pub fn from_string(s: &str) -> Result<Self, TypeError> {
        match s.to_lowercase().as_str() {
            "undefined" => Ok(Model::Undefined),
            _ => Err(TypeError::UnknownModelError(s.to_string())),
        }
    }
}

pub enum Common {
    Undefined,
}

impl Common {
    pub fn as_str(&self) -> &str {
        match self {
            Common::Undefined => "undefined",
        }
    }
}

impl Display for Common {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[pyclass(from_py_object, eq, eq_int)]
pub enum Provider {
    OpenAI,
    Gemini,
    Google,
    Vertex,
    Anthropic,
    GoogleAdk,
    Undefined, // Added Undefined for better error handling
}

impl Provider {
    pub fn from_string(s: &str) -> Result<Self, TypeError> {
        match s.to_lowercase().as_str() {
            "openai" => Ok(Provider::OpenAI),
            "gemini" => Ok(Provider::Gemini),
            "google" => Ok(Provider::Google),
            "vertex" => Ok(Provider::Vertex),
            "anthropic" => Ok(Provider::Anthropic),
            "google_adk" => Ok(Provider::GoogleAdk),
            "undefined" => Ok(Provider::Undefined), // Handle undefined case
            _ => Err(TypeError::UnknownProviderError(s.to_string())),
        }
    }

    pub const DEFAULT_ENV_VAR: &'static str = "POTATO_HEAD_DEFAULT_PROVIDER";

    /// Reads `POTATO_HEAD_DEFAULT_PROVIDER` from the environment.
    ///
    /// - Unset, empty, or whitespace-only -> `Ok(None)`
    /// - Set and parseable -> `Ok(Some(provider))`
    /// - Set but unparseable -> `Err(TypeError::UnknownProviderError(...))`
    pub fn from_env_default() -> Result<Option<Provider>, TypeError> {
        match std::env::var(Self::DEFAULT_ENV_VAR) {
            Ok(s) => {
                let trimmed = s.trim();
                if trimmed.is_empty() {
                    Ok(None)
                } else {
                    Provider::from_string(trimmed).map(Some)
                }
            }
            Err(_) => Ok(None),
        }
    }

    /// Resolve a provider from an optional explicit string, falling back to the env var,
    /// then erroring with `MissingProviderError` if neither is available.
    pub fn resolve(provided: Option<&str>) -> Result<Provider, TypeError> {
        if let Some(s) = provided.map(str::trim).filter(|s| !s.is_empty()) {
            return Provider::from_string(s);
        }

        Self::from_env_default()?.ok_or(TypeError::MissingProviderError(Self::DEFAULT_ENV_VAR))
    }

    /// PyO3-friendly resolution: accepts an optional `Bound<'_, PyAny>` (Provider enum or string).
    /// `None` or `py.None()` triggers env-var fallback.
    pub fn resolve_from_py(provider: Option<&Bound<'_, PyAny>>) -> Result<Provider, TypeError> {
        match provider {
            Some(p) if !p.is_none() => Self::extract_provider(p),
            _ => Self::from_env_default()?
                .ok_or(TypeError::MissingProviderError(Self::DEFAULT_ENV_VAR)),
        }
    }

    /// Extract provider from a PyAny object
    ///
    /// # Arguments
    /// * `provider` - PyAny object
    ///
    /// # Returns
    /// * `Result<Provider, AgentError>` - Result
    ///
    /// # Errors
    /// * `AgentError` - Error
    pub fn extract_provider(provider: &Bound<'_, PyAny>) -> Result<Provider, TypeError> {
        match provider.is_instance_of::<Provider>() {
            true => Ok(provider.extract::<Provider>().inspect_err(|e| {
                error!("Failed to extract provider: {}", e);
            })?),
            false => {
                let provider = provider.extract::<String>().unwrap();
                Ok(Provider::from_string(&provider).inspect_err(|e| {
                    error!("Failed to convert string to provider: {}", e);
                })?)
            }
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            Provider::OpenAI => "openai",
            Provider::Gemini => "gemini",
            Provider::Vertex => "vertex",
            Provider::Google => "google",
            Provider::Anthropic => "anthropic",
            Provider::GoogleAdk => "google_adk",
            Provider::Undefined => "undefined", // Added Undefined case
        }
    }
}

impl Display for Provider {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[pyclass(from_py_object, eq, eq_int)]
#[derive(Debug, PartialEq, Clone)]
pub enum SaveName {
    Prompt,
}

#[pymethods]
impl SaveName {
    #[staticmethod]
    pub fn from_string(s: &str) -> Option<Self> {
        match s {
            "prompt" => Some(SaveName::Prompt),

            _ => None,
        }
    }

    pub fn as_string(&self) -> &str {
        match self {
            SaveName::Prompt => "prompt",
        }
    }

    pub fn __str__(&self) -> String {
        self.to_string()
    }
}

impl Display for SaveName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_string())
    }
}

impl AsRef<Path> for SaveName {
    fn as_ref(&self) -> &Path {
        match self {
            SaveName::Prompt => Path::new("prompt"),
        }
    }
}

// impl PathBuf: From<SaveName>
impl From<SaveName> for PathBuf {
    fn from(save_name: SaveName) -> Self {
        PathBuf::from(save_name.as_ref())
    }
}

/// A trait for structured output types that can be used with potatohead prompts agents and workflows.
///
/// # Example
/// ```rust
/// use potatohead_macro::StructureOutput;
/// use serde::{Serialize, Deserialize};
/// use schemars::JsonSchema;
///
/// #[derive(Serialize, Deserialize, JsonSchema)]
/// struct MyOutput {
///     message: String,
///     value: i32,
/// }
///
/// impl StructuredOutput for MyOutput {}
///
/// let schema = MyOutput::get_structured_output_schema();
/// ```
pub trait StructuredOutput: for<'de> serde::Deserialize<'de> + JsonSchema {
    fn type_name() -> &'static str {
        type_name::<Self>().rsplit("::").next().unwrap_or("Unknown")
    }

    /// Validates and deserializes a JSON value into its struct type.
    ///
    /// # Arguments
    /// * `value` - The JSON value to deserialize
    ///
    /// # Returns
    /// * `Result<Self, serde_json::Error>` - The deserialized value or error
    fn model_validate_json_value(value: &Value) -> Result<Self, serde_json::Error> {
        match &value {
            Value::String(json_str) => Self::model_validate_json_str(json_str),
            Value::Object(_) => {
                // Content is already a JSON object
                serde_json::from_value(value.clone())
            }
            _ => {
                // If the value is not a string or object, we cannot deserialize it
                Err(Error::custom("Expected a JSON string or object"))
            }
        }
    }

    fn model_validate_json_str(value: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(value)
    }

    /// Generates an OpenAI-compatible JSON schema.
    ///
    /// # Returns
    /// * `Value` - The JSON schema wrapped in OpenAI's format
    fn get_structured_output_schema() -> Value {
        let schema = ::schemars::schema_for!(Self);
        schema.into()
    }
    // add fallback parsing logic
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[pyclass(from_py_object)]
pub enum SettingsType {
    GoogleChat,
    OpenAIChat,
    ModelSettings,
    Anthropic,
}

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

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    fn with_env_var<F: FnOnce()>(value: Option<&str>, f: F) {
        let _guard = ENV_LOCK.lock().unwrap();
        let prev = std::env::var(Provider::DEFAULT_ENV_VAR).ok();
        match value {
            Some(v) => std::env::set_var(Provider::DEFAULT_ENV_VAR, v),
            None => std::env::remove_var(Provider::DEFAULT_ENV_VAR),
        }
        f();
        match prev {
            Some(v) => std::env::set_var(Provider::DEFAULT_ENV_VAR, v),
            None => std::env::remove_var(Provider::DEFAULT_ENV_VAR),
        }
    }

    #[test]
    fn test_provider_google_adk_round_trip() {
        let p = Provider::from_string("google_adk").unwrap();
        assert_eq!(p, Provider::GoogleAdk);
        assert_eq!(p.as_str(), "google_adk");
    }

    #[test]
    fn test_provider_all_variants_round_trip() {
        for (s, variant) in [
            ("openai", Provider::OpenAI),
            ("gemini", Provider::Gemini),
            ("google", Provider::Google),
            ("vertex", Provider::Vertex),
            ("anthropic", Provider::Anthropic),
            ("google_adk", Provider::GoogleAdk),
            ("undefined", Provider::Undefined),
        ] {
            let parsed = Provider::from_string(s).unwrap();
            assert_eq!(parsed, variant);
            assert_eq!(parsed.as_str(), s);
        }
    }

    #[test]
    fn test_provider_unknown_string_errors() {
        assert!(Provider::from_string("not_a_provider").is_err());
    }

    #[test]
    fn resolve_explicit_wins_over_env() {
        with_env_var(Some("anthropic"), || {
            let p = Provider::resolve(Some("openai")).unwrap();
            assert_eq!(p, Provider::OpenAI);
        });
    }

    #[test]
    fn resolve_uses_env_when_explicit_missing() {
        with_env_var(Some("openai"), || {
            let p = Provider::resolve(None).unwrap();
            assert_eq!(p, Provider::OpenAI);
        });
    }

    #[test]
    fn resolve_uses_env_when_explicit_empty_string() {
        with_env_var(Some("openai"), || {
            let p = Provider::resolve(Some("   ")).unwrap();
            assert_eq!(p, Provider::OpenAI);
        });
    }

    #[test]
    fn resolve_empty_env_treated_as_unset() {
        with_env_var(Some("   "), || {
            let err = Provider::resolve(None).unwrap_err();
            assert!(matches!(err, TypeError::MissingProviderError(_)));
        });
    }

    #[test]
    fn resolve_invalid_env_is_hard_error() {
        with_env_var(Some("not_a_provider"), || {
            let err = Provider::resolve(None).unwrap_err();
            assert!(matches!(err, TypeError::UnknownProviderError(_)));
        });
    }

    #[test]
    fn resolve_no_explicit_no_env_returns_missing() {
        with_env_var(None, || {
            let err = Provider::resolve(None).unwrap_err();
            match err {
                TypeError::MissingProviderError(name) => {
                    assert_eq!(name, "POTATO_HEAD_DEFAULT_PROVIDER");
                }
                other => panic!("expected MissingProviderError, got {:?}", other),
            }
        });
    }

    #[test]
    fn from_env_default_unset_returns_none() {
        with_env_var(None, || {
            assert!(Provider::from_env_default().unwrap().is_none());
        });
    }

    #[test]
    fn from_env_default_set_and_parseable() {
        with_env_var(Some("gemini"), || {
            assert_eq!(
                Provider::from_env_default().unwrap(),
                Some(Provider::Gemini)
            );
        });
    }

    #[test]
    fn from_env_default_set_but_invalid_errors() {
        with_env_var(Some("garbage"), || {
            assert!(Provider::from_env_default().is_err());
        });
    }
}