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
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
use crate::anthropic::v1::request::MessageParam as AnthropicMessage;
use crate::anthropic::v1::request::TextBlockParam;
use crate::anthropic::v1::response::ResponseContentBlock;
use crate::google::v1::generate::Candidate;
use crate::google::v1::generate::GeminiContent;
use crate::google::PredictResponse;
use crate::openai::v1::chat::request::ChatMessage as OpenAIChatMessage;
use crate::openai::v1::Choice;
use crate::traits::MessageConversion;
use crate::traits::PromptMessageExt;
use crate::Provider;
use crate::{StructuredOutput, TypeError};
use potato_util::PyHelperFuncs;
use pyo3::types::PyAnyMethods;
use pyo3::{prelude::*, IntoPyObjectExt};
use pythonize::{depythonize, pythonize};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt::Display;
use tracing::error;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[pyclass(from_py_object)]
pub enum Role {
    User,
    Assistant,
    Developer,
    Tool,
    Model,
    System,
}

#[pymethods]
impl Role {
    #[pyo3(name = "as_str")]
    pub fn as_str_py(&self) -> &'static str {
        self.as_str()
    }
}

impl Role {
    /// Returns the string representation of the role
    pub const fn as_str(&self) -> &'static str {
        match self {
            Role::User => "user",
            Role::Assistant => "assistant",
            Role::Developer => "developer",
            Role::Tool => "tool",
            Role::Model => "model",
            Role::System => "system",
        }
    }
}

impl Display for Role {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Role::User => write!(f, "user"),
            Role::Assistant => write!(f, "assistant"),
            Role::Developer => write!(f, "developer"),
            Role::Tool => write!(f, "tool"),
            Role::Model => write!(f, "model"),
            Role::System => write!(f, "system"),
        }
    }
}

impl From<Role> for &str {
    fn from(role: Role) -> Self {
        match role {
            Role::User => "user",
            Role::Assistant => "assistant",
            Role::Developer => "developer",
            Role::Tool => "tool",
            Role::Model => "model",
            Role::System => "system",
        }
    }
}

pub trait DeserializePromptValExt: for<'de> serde::Deserialize<'de> {
    /// 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) -> Result<Self, serde_json::Error> {
        serde_json::from_value(value.clone())
    }
}

pub fn get_pydantic_module<'py>(py: Python<'py>, module_name: &str) -> PyResult<Bound<'py, PyAny>> {
    py.import("pydantic_ai")?.getattr(module_name)
}

/// Checks if an object is a subclass of a pydantic BaseModel. This is used when validating structured outputs
/// # Arguments
/// * `py` - The Python interpreter instance
/// * `object` - The object to check
/// # Returns
/// A boolean indicating whether the object is a subclass of pydantic.BaseModel
pub fn check_pydantic_model<'py>(
    py: Python<'py>,
    object: &Bound<'_, PyAny>,
) -> Result<bool, TypeError> {
    // check pydantic import. Return false if it fails
    let pydantic = match py.import("pydantic").map_err(|e| {
        error!("Failed to import pydantic: {}", e);
        false
    }) {
        Ok(pydantic) => pydantic,
        Err(_) => return Ok(false),
    };

    // get builtin subclass
    let is_subclass = py.import("builtins")?.getattr("issubclass")?;

    // Need to check if provided object is a basemodel
    let basemodel = pydantic.getattr("BaseModel")?;
    let matched = is_subclass.call1((object, basemodel))?.extract::<bool>()?;

    Ok(matched)
}

/// Generate a JSON schema from a pydantic BaseModel object.
/// # Arguments
/// * `object` - The pydantic BaseModel object to generate the schema from.
/// # Returns
/// A JSON schema as a serde_json::Value.
fn get_json_schema_from_basemodel(object: &Bound<'_, PyAny>) -> Result<Value, TypeError> {
    // call staticmethod .model_json_schema()
    let schema = object.getattr("model_json_schema")?.call1(())?;

    let mut schema: Value = depythonize(&schema)?;

    // ensure schema as additionalProperties set to false
    if let Some(additional_properties) = schema.get_mut("additionalProperties") {
        *additional_properties = serde_json::json!(false);
    } else {
        schema
            .as_object_mut()
            .unwrap()
            .insert("additionalProperties".to_string(), serde_json::json!(false));
    }

    Ok(schema)
}

fn parse_pydantic_model<'py>(
    py: Python<'py>,
    object: &Bound<'_, PyAny>,
) -> Result<Option<Value>, TypeError> {
    let is_subclass = check_pydantic_model(py, object)?;
    if is_subclass {
        Ok(Some(get_json_schema_from_basemodel(object)?))
    } else {
        Ok(None)
    }
}

pub fn check_response_type(object: &Bound<'_, PyAny>) -> Result<Option<ResponseType>, TypeError> {
    // try calling staticmethod response_type()
    let response_type = match object.getattr("response_type") {
        Ok(method) => {
            if method.is_callable() {
                let response_type: ResponseType = method.call0()?.extract()?;
                Some(response_type)
            } else {
                None
            }
        }
        Err(_) => None,
    };

    Ok(response_type)
}

fn get_json_schema_from_response_type(response_type: &ResponseType) -> Result<Value, TypeError> {
    match response_type {
        ResponseType::Score => Ok(Score::get_structured_output_schema()),
        _ => {
            // If the response type is not recognized, return None
            Err(TypeError::Error(format!(
                "Unsupported response type: {response_type}"
            )))
        }
    }
}

pub fn parse_response_to_json<'py>(
    py: Python<'py>,
    object: &Bound<'_, PyAny>,
) -> Result<(ResponseType, Option<Value>), TypeError> {
    // check if object is a pydantic model
    let is_pydantic_model = check_pydantic_model(py, object)?;
    if is_pydantic_model {
        return Ok((ResponseType::Pydantic, parse_pydantic_model(py, object)?));
    }

    // check if object has response_type method
    let response_type = check_response_type(object)?;
    if let Some(response_type) = response_type {
        return Ok((
            response_type.clone(),
            Some(get_json_schema_from_response_type(&response_type)?),
        ));
    }

    Ok((ResponseType::Null, None))
}

#[pyclass(from_py_object)]
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)] // ensure strict validation
pub struct Score {
    #[pyo3(get)]
    #[schemars(range(min = 1, max = 5))]
    pub score: i64,

    #[pyo3(get)]
    pub reason: String,
}
#[pymethods]
impl Score {
    #[staticmethod]
    pub fn response_type() -> ResponseType {
        ResponseType::Score
    }

    #[staticmethod]
    pub fn model_validate_json(json_string: String) -> Result<Score, TypeError> {
        Ok(serde_json::from_str(&json_string)?)
    }

    #[staticmethod]
    pub fn model_json_schema<'py>(py: Python<'py>) -> Result<Bound<'py, PyAny>, TypeError> {
        let schema = Score::get_structured_output_schema();
        Ok(pythonize(py, &schema)?)
    }

    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(self)
    }
}

impl StructuredOutput for Score {}

#[pyclass(from_py_object)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub enum ResponseType {
    Score,
    Pydantic,
    #[default]
    Null, // This is used when no response type is specified
}

impl Display for ResponseType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResponseType::Score => write!(f, "Score"),
            ResponseType::Pydantic => write!(f, "Pydantic"),
            ResponseType::Null => write!(f, "Null"),
        }
    }
}

// add conversion logic based on message conversion trait

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum MessageNum {
    OpenAIMessageV1(OpenAIChatMessage),
    AnthropicMessageV1(AnthropicMessage),
    GeminiContentV1(GeminiContent),

    // this is a special case for Anthropic system messages
    AnthropicSystemMessageV1(TextBlockParam),

    // Raw JSON message - used internally in the agentic loop for provider-specific
    // messages that don't fit the typed variants (e.g., OpenAI tool-call assistant messages).
    // Must be LAST so serde tries typed variants first when deserializing.
    RawV1(serde_json::Value),
}

impl MessageNum {
    /// Checks if the message type matches the given provider
    fn matches_provider(&self, provider: &Provider) -> bool {
        matches!(
            (self, provider),
            (MessageNum::OpenAIMessageV1(_), Provider::OpenAI)
                | (MessageNum::AnthropicMessageV1(_), Provider::Anthropic)
                | (MessageNum::AnthropicSystemMessageV1(_), Provider::Anthropic)
                | (MessageNum::GeminiContentV1(_), Provider::Google)
                | (MessageNum::GeminiContentV1(_), Provider::Vertex)
                | (MessageNum::GeminiContentV1(_), Provider::Gemini)
        )
    }

    /// Converts the message to an openai message
    /// This is only done for anthropic and gemini messages
    /// openai message will return a failure if called on an openai message
    /// Control flow should ensure this is only called on non-openai messages
    fn to_openai_message(&self) -> Result<MessageNum, TypeError> {
        match self {
            MessageNum::AnthropicMessageV1(msg) => {
                Ok(MessageNum::OpenAIMessageV1(msg.to_openai_message()?))
            }
            MessageNum::GeminiContentV1(msg) => {
                Ok(MessageNum::OpenAIMessageV1(msg.to_openai_message()?))
            }
            _ => Err(TypeError::CantConvertSelf),
        }
    }

    /// Converts to Anthropic message format
    fn to_anthropic_message(&self) -> Result<MessageNum, TypeError> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => {
                Ok(MessageNum::AnthropicMessageV1(msg.to_anthropic_message()?))
            }
            MessageNum::GeminiContentV1(msg) => {
                Ok(MessageNum::AnthropicMessageV1(msg.to_anthropic_message()?))
            }
            _ => Err(TypeError::CantConvertSelf),
        }
    }

    /// Converts to Google Gemini message format
    fn to_google_message(&self) -> Result<MessageNum, TypeError> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => {
                Ok(MessageNum::GeminiContentV1(msg.to_google_message()?))
            }
            MessageNum::AnthropicMessageV1(msg) => {
                Ok(MessageNum::GeminiContentV1(msg.to_google_message()?))
            }
            _ => Err(TypeError::CantConvertSelf),
        }
    }

    fn convert_message_to_provider_type(
        &self,
        provider: &Provider,
    ) -> Result<MessageNum, TypeError> {
        match provider {
            Provider::OpenAI => self.to_openai_message(),
            Provider::Anthropic => self.to_anthropic_message(),
            Provider::Google => self.to_google_message(),
            Provider::Vertex => self.to_google_message(),
            Provider::Gemini => self.to_google_message(),
            _ => Err(TypeError::UnsupportedProviderError),
        }
    }

    pub fn convert_message(&mut self, provider: &Provider) -> Result<(), TypeError> {
        // RawV1 is provider-specific raw JSON — skip conversion
        if matches!(self, MessageNum::RawV1(_)) {
            return Ok(());
        }
        // if message already matches provider, return Ok
        if self.matches_provider(provider) {
            return Ok(());
        }
        let converted = self.convert_message_to_provider_type(provider)?;
        *self = converted;
        Ok(())
    }

    pub fn anthropic_message_to_system_message(&mut self) -> Result<(), TypeError> {
        match self {
            MessageNum::AnthropicMessageV1(msg) => {
                let text_param = msg.to_text_block_param()?;
                *self = MessageNum::AnthropicSystemMessageV1(text_param);
                Ok(())
            }
            _ => Err(TypeError::Error(
                "Cannot convert non-AnthropicMessageV1 to system message".to_string(),
            )),
        }
    }
    pub fn role(&self) -> &str {
        match self {
            MessageNum::OpenAIMessageV1(msg) => &msg.role,
            MessageNum::AnthropicMessageV1(msg) => &msg.role,
            MessageNum::GeminiContentV1(msg) => &msg.role,
            _ => "system",
        }
    }
    pub fn bind(&self, name: &str, value: &str) -> Result<Self, TypeError> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => {
                let bound_msg = msg.bind(name, value)?;
                Ok(MessageNum::OpenAIMessageV1(bound_msg))
            }
            MessageNum::AnthropicMessageV1(msg) => {
                let bound_msg = msg.bind(name, value)?;
                Ok(MessageNum::AnthropicMessageV1(bound_msg))
            }
            MessageNum::GeminiContentV1(msg) => {
                let bound_msg = msg.bind(name, value)?;
                Ok(MessageNum::GeminiContentV1(bound_msg))
            }
            _ => Ok(self.clone()),
        }
    }
    pub fn bind_mut(&mut self, name: &str, value: &str) -> Result<(), TypeError> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => msg.bind_mut(name, value),
            MessageNum::AnthropicMessageV1(msg) => msg.bind_mut(name, value),
            MessageNum::GeminiContentV1(msg) => msg.bind_mut(name, value),
            _ => Ok(()),
        }
    }

    pub(crate) fn extract_variables(&self) -> Vec<String> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => msg.extract_variables(),
            MessageNum::AnthropicMessageV1(msg) => msg.extract_variables(),
            MessageNum::GeminiContentV1(msg) => msg.extract_variables(),
            _ => vec![],
        }
    }

    pub(crate) fn extract_media_variables(&self) -> Vec<String> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => msg.extract_media_variables(),
            MessageNum::AnthropicMessageV1(msg) => msg.extract_media_variables(),
            MessageNum::GeminiContentV1(msg) => msg.extract_media_variables(),
            MessageNum::AnthropicSystemMessageV1(t) => {
                let mut out = Vec::new();
                let regex = crate::traits::get_media_regex();
                for cap in regex.captures_iter(&t.text) {
                    if let Some(name) = cap.get(1) {
                        out.push(name.as_str().to_string());
                    }
                }
                out
            }
            _ => vec![],
        }
    }

    pub fn split_media_placeholders(&mut self) -> Result<(), TypeError> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => msg.split_media_placeholders(),
            MessageNum::AnthropicMessageV1(msg) => msg.split_media_placeholders(),
            MessageNum::GeminiContentV1(msg) => msg.split_media_placeholders(),
            MessageNum::AnthropicSystemMessageV1(t) => {
                let regex = crate::traits::get_media_regex();
                if regex.is_match(&t.text) {
                    Err(TypeError::MediaInSystemMessage)
                } else {
                    Ok(())
                }
            }
            MessageNum::RawV1(_) => Ok(()),
        }
    }

    pub fn bind_media_mut(
        &mut self,
        token: &str,
        media: &crate::prompt::media::MediaRef,
        provider: &crate::Provider,
    ) -> Result<bool, TypeError> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => msg.bind_media_mut(token, media, provider),
            MessageNum::AnthropicMessageV1(msg) => msg.bind_media_mut(token, media, provider),
            MessageNum::GeminiContentV1(msg) => msg.bind_media_mut(token, media, provider),
            MessageNum::AnthropicSystemMessageV1(t) => {
                if t.text.contains(token) {
                    Err(TypeError::MediaInSystemMessage)
                } else {
                    Ok(false)
                }
            }
            MessageNum::RawV1(_) => Ok(false),
        }
    }

    pub fn to_bound_py_object<'py>(&self, py: Python<'py>) -> Result<Bound<'py, PyAny>, TypeError> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => {
                let bound_msg = msg.clone().into_bound_py_any(py)?;
                Ok(bound_msg)
            }
            MessageNum::AnthropicMessageV1(msg) => {
                let bound_msg = msg.clone().into_bound_py_any(py)?;
                Ok(bound_msg)
            }
            MessageNum::GeminiContentV1(msg) => {
                let bound_msg = msg.clone().into_bound_py_any(py)?;
                Ok(bound_msg)
            }
            MessageNum::AnthropicSystemMessageV1(msg) => {
                // Convert to AnthropicMessage first
                let anthropic_msg = AnthropicMessage::from_text(msg.text.clone(), self.role())?;
                let bound_msg = anthropic_msg.into_bound_py_any(py)?;
                Ok(bound_msg)
            }
            MessageNum::RawV1(v) => Ok(pythonize(py, v)?),
        }
    }

    pub fn to_bound_openai_message<'py>(
        &self,
        py: Python<'py>,
    ) -> Result<Bound<'py, OpenAIChatMessage>, TypeError> {
        match self {
            MessageNum::OpenAIMessageV1(msg) => {
                let py_obj = Py::new(py, msg.clone())?;
                let bound = py_obj.bind(py);
                Ok(bound.clone())
            }
            _ => Err(TypeError::CantConvertSelf),
        }
    }

    pub fn to_bound_gemini_message<'py>(
        &self,
        py: Python<'py>,
    ) -> Result<Bound<'py, GeminiContent>, TypeError> {
        match self {
            MessageNum::GeminiContentV1(msg) => {
                let py_obj = Py::new(py, msg.clone())?;
                let bound = py_obj.bind(py);
                Ok(bound.clone())
            }
            _ => Err(TypeError::CantConvertSelf),
        }
    }

    pub fn to_bound_anthropic_message<'py>(
        &self,
        py: Python<'py>,
    ) -> Result<Bound<'py, AnthropicMessage>, TypeError> {
        match self {
            MessageNum::AnthropicMessageV1(msg) => {
                let py_obj = Py::new(py, msg.clone())?;
                let bound = py_obj.bind(py);
                Ok(bound.clone())
            }
            _ => Err(TypeError::CantConvertSelf),
        }
    }

    pub fn is_system_message(&self) -> bool {
        match self {
            MessageNum::OpenAIMessageV1(msg) => {
                msg.role == Role::Developer.to_string() || msg.role == Role::System.to_string()
            }
            MessageNum::AnthropicMessageV1(msg) => msg.role == Role::System.to_string(),
            MessageNum::GeminiContentV1(msg) => msg.role == Role::Model.to_string(),
            MessageNum::AnthropicSystemMessageV1(_) => true,
            MessageNum::RawV1(v) => v
                .get("role")
                .and_then(|r| r.as_str())
                .map(|r| r == "system" || r == "developer")
                .unwrap_or(false),
        }
    }

    pub fn is_user_message(&self) -> bool {
        match self {
            MessageNum::OpenAIMessageV1(msg) => msg.role == Role::User.to_string(),
            MessageNum::AnthropicMessageV1(msg) => msg.role == Role::User.to_string(),
            MessageNum::GeminiContentV1(msg) => msg.role == Role::User.to_string(),
            MessageNum::AnthropicSystemMessageV1(_) => false,
            MessageNum::RawV1(v) => v
                .get("role")
                .and_then(|r| r.as_str())
                .map(|r| r == "user")
                .unwrap_or(false),
        }
    }
}

#[derive(Debug, Clone)]
pub enum ResponseContent {
    OpenAI(Choice),
    Google(Candidate),
    Anthropic(ResponseContentBlock),
    PredictResponse(PredictResponse),
}

#[pyclass(skip_from_py_object)]
pub struct OpenAIMessageList {
    pub messages: Vec<OpenAIChatMessage>,
}

#[pymethods]
impl OpenAIMessageList {
    fn __iter__(slf: PyRef<'_, Self>) -> PyResult<Py<OpenAIMessageIterator>> {
        let iter = OpenAIMessageIterator {
            inner: slf.messages.clone().into_iter(),
        };
        Py::new(slf.py(), iter)
    }

    pub fn __len__(&self) -> usize {
        self.messages.len()
    }

    pub fn __getitem__(&self, index: isize) -> Result<OpenAIChatMessage, TypeError> {
        let len = self.messages.len() as isize;
        let normalized_index = if index < 0 { len + index } else { index };

        if normalized_index < 0 || normalized_index >= len {
            return Err(TypeError::Error(format!(
                "Index {} out of range for list of length {}",
                index, len
            )));
        }

        Ok(self.messages[normalized_index as usize].clone())
    }

    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(&self.messages)
    }

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

#[pyclass(skip_from_py_object)]
pub struct OpenAIMessageIterator {
    inner: std::vec::IntoIter<OpenAIChatMessage>,
}

#[pymethods]
impl OpenAIMessageIterator {
    fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
        slf
    }

    fn __next__(mut slf: PyRefMut<'_, Self>) -> Option<OpenAIChatMessage> {
        slf.inner.next()
    }
}

#[pyclass(skip_from_py_object)]
pub struct AnthropicMessageList {
    pub messages: Vec<AnthropicMessage>,
}

#[pymethods]
impl AnthropicMessageList {
    fn __iter__(slf: PyRef<'_, Self>) -> PyResult<Py<AnthropicMessageIterator>> {
        let iter = AnthropicMessageIterator {
            inner: slf.messages.clone().into_iter(),
        };
        Py::new(slf.py(), iter)
    }

    pub fn __len__(&self) -> usize {
        self.messages.len()
    }

    pub fn __getitem__(&self, index: isize) -> Result<AnthropicMessage, TypeError> {
        let len = self.messages.len() as isize;
        let normalized_index = if index < 0 { len + index } else { index };

        if normalized_index < 0 || normalized_index >= len {
            return Err(TypeError::Error(format!(
                "Index {} out of range for list of length {}",
                index, len
            )));
        }

        Ok(self.messages[normalized_index as usize].clone())
    }

    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(&self.messages)
    }

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

#[pyclass(skip_from_py_object)]
pub struct AnthropicMessageIterator {
    inner: std::vec::IntoIter<AnthropicMessage>,
}

#[pymethods]
impl AnthropicMessageIterator {
    fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
        slf
    }

    fn __next__(mut slf: PyRefMut<'_, Self>) -> Option<AnthropicMessage> {
        slf.inner.next()
    }
}

#[pyclass(skip_from_py_object)]
pub struct GeminiContentList {
    pub messages: Vec<GeminiContent>,
}

#[pymethods]
impl GeminiContentList {
    fn __iter__(slf: PyRef<'_, Self>) -> PyResult<Py<GeminiContentIterator>> {
        let iter = GeminiContentIterator {
            inner: slf.messages.clone().into_iter(),
        };
        Py::new(slf.py(), iter)
    }

    pub fn __len__(&self) -> usize {
        self.messages.len()
    }

    pub fn __getitem__(&self, index: isize) -> Result<GeminiContent, TypeError> {
        let len = self.messages.len() as isize;
        let normalized_index = if index < 0 { len + index } else { index };

        if normalized_index < 0 || normalized_index >= len {
            return Err(TypeError::Error(format!(
                "Index {} out of range for list of length {}",
                index, len
            )));
        }

        Ok(self.messages[normalized_index as usize].clone())
    }

    pub fn __str__(&self) -> String {
        PyHelperFuncs::__str__(&self.messages)
    }

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

#[pyclass(skip_from_py_object)]
pub struct GeminiContentIterator {
    inner: std::vec::IntoIter<GeminiContent>,
}

#[pymethods]
impl GeminiContentIterator {
    fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
        slf
    }

    fn __next__(mut slf: PyRefMut<'_, Self>) -> Option<GeminiContent> {
        slf.inner.next()
    }
}