litellm-rs 0.4.16

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
//! Converse API Implementation
//!
//! Modern unified API for chat completions in Bedrock

use crate::core::providers::unified_provider::ProviderError;
use crate::core::types::chat::ChatRequest;
use crate::core::types::{message::MessageContent, message::MessageRole};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Converse API request format
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConverseRequest {
    pub messages: Vec<ConverseMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<Vec<SystemMessage>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inference_config: Option<InferenceConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_config: Option<ToolConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub guardrail_config: Option<GuardrailConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_model_request_fields: Option<Value>,
}

/// Converse message format
#[derive(Debug, Serialize, Deserialize)]
pub struct ConverseMessage {
    pub role: String,
    pub content: Vec<ContentBlock>,
}

/// System message format
#[derive(Debug, Serialize, Deserialize)]
pub struct SystemMessage {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub guardrail_content: Option<GuardrailContent>,
}

/// Content block for messages
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ContentBlock {
    Text { text: String },
    Image { image: ImageBlock },
    Document { document: DocumentBlock },
    ToolUse { tool_use: ToolUseBlock },
    ToolResult { tool_result: ToolResultBlock },
    GuardrailContent { guardrail_content: GuardrailContent },
}

/// Image block for multimodal input
#[derive(Debug, Serialize, Deserialize)]
pub struct ImageBlock {
    pub format: String,
    pub source: ImageSource,
}

/// Image source
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ImageSource {
    Bytes { bytes: String },
}

/// Document block for document input
#[derive(Debug, Serialize, Deserialize)]
pub struct DocumentBlock {
    pub format: String,
    pub name: String,
    pub source: DocumentSource,
}

/// Document source
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DocumentSource {
    Bytes { bytes: String },
}

/// Tool use block
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolUseBlock {
    pub tool_use_id: String,
    pub name: String,
    pub input: Value,
}

/// Tool result block
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolResultBlock {
    pub tool_use_id: String,
    pub content: Vec<ToolResultContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
}

/// Tool result content
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ToolResultContent {
    Text { text: String },
    Image { image: ImageBlock },
    Document { document: DocumentBlock },
}

/// Guardrail content
#[derive(Debug, Serialize, Deserialize)]
pub struct GuardrailContent {
    pub text: String,
}

/// Inference configuration
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InferenceConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<String>>,
}

/// Tool configuration
#[derive(Debug, Serialize, Deserialize)]
pub struct ToolConfig {
    pub tools: Vec<ToolSpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ToolChoice>,
}

/// Tool specification
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolSpec {
    pub tool_spec: ToolSpecDefinition,
}

/// Tool specification definition
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolSpecDefinition {
    pub name: String,
    pub description: String,
    pub input_schema: InputSchema,
}

/// Input schema for tools
#[derive(Debug, Serialize, Deserialize)]
pub struct InputSchema {
    pub json: Value,
}

/// Tool choice
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ToolChoice {
    Auto,
    Any,
    Tool { name: String },
}

/// Guardrail configuration
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GuardrailConfig {
    pub guardrail_identifier: String,
    pub guardrail_version: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace: Option<bool>,
}

/// Execute a converse API request
pub async fn execute_converse(
    client: &crate::core::providers::bedrock::client::BedrockClient,
    request: &ChatRequest,
) -> Result<Value, ProviderError> {
    // Transform ChatRequest to ConverseRequest
    let converse_request = transform_to_converse(request)?;

    // Send request using the client
    let response = client
        .send_request(
            &request.model,
            "converse",
            &serde_json::to_value(converse_request)?,
        )
        .await?;

    // Parse response and return as Value
    response
        .json::<Value>()
        .await
        .map_err(|e| ProviderError::response_parsing("bedrock", e.to_string()))
}

/// Transform OpenAI-style ChatRequest to Converse API format
fn transform_to_converse(request: &ChatRequest) -> Result<ConverseRequest, ProviderError> {
    let mut messages = Vec::new();
    let mut system_messages = Vec::new();

    for msg in &request.messages {
        match msg.role {
            MessageRole::System => {
                // Extract system message
                if let Some(content) = &msg.content {
                    let text = match content {
                        MessageContent::Text(text) => text.clone(),
                        MessageContent::Parts(parts) => {
                            // Extract text from parts
                            parts
                                .iter()
                                .filter_map(|part| {
                                    if let crate::core::types::content::ContentPart::Text { text } =
                                        part
                                    {
                                        Some(text.clone())
                                    } else {
                                        None
                                    }
                                })
                                .collect::<Vec<_>>()
                                .join(" ")
                        }
                    };
                    system_messages.push(SystemMessage {
                        text: Some(text),
                        guardrail_content: None,
                    });
                }
            }
            MessageRole::User | MessageRole::Assistant => {
                // Transform to converse message
                let role = match msg.role {
                    MessageRole::User => "user",
                    MessageRole::Assistant => "assistant",
                    _ => continue,
                }
                .to_string();

                let content = if let Some(msg_content) = &msg.content {
                    match msg_content {
                        MessageContent::Text(text) => {
                            vec![ContentBlock::Text { text: text.clone() }]
                        }
                        MessageContent::Parts(parts) => {
                            parts
                                .iter()
                                .filter_map(|part| {
                                    match part {
                                        crate::core::types::content::ContentPart::Text { text } => {
                                            Some(ContentBlock::Text { text: text.clone() })
                                        }
                                        crate::core::types::content::ContentPart::Image {
                                            ..
                                        } => {
                                            // NOTE: image content not yet handled
                                            None
                                        }
                                        crate::core::types::content::ContentPart::ImageUrl {
                                            ..
                                        } => {
                                            // NOTE: image URL content not yet handled
                                            None
                                        }
                                        crate::core::types::content::ContentPart::Audio {
                                            ..
                                        } => {
                                            // NOTE: audio content not yet handled
                                            None
                                        }
                                        crate::core::types::content::ContentPart::Document {
                                            ..
                                        } => {
                                            // NOTE: document content not yet handled
                                            None
                                        }
                                        crate::core::types::content::ContentPart::ToolResult {
                                            ..
                                        } => {
                                            // NOTE: tool result content not yet handled
                                            None
                                        }
                                        crate::core::types::content::ContentPart::ToolUse {
                                            ..
                                        } => {
                                            // NOTE: tool use content not yet handled
                                            None
                                        }
                                    }
                                })
                                .collect()
                        }
                    }
                } else {
                    vec![]
                };

                messages.push(ConverseMessage { role, content });
            }
            _ => {
                // Skip function/tool messages for now
                // NOTE: tool message handling not yet implemented
            }
        }
    }

    // Build inference config
    let inference_config = Some(InferenceConfig {
        max_tokens: request.max_tokens,
        temperature: request.temperature.map(|t| t as f64),
        top_p: request.top_p.map(|t| t as f64),
        stop_sequences: request.stop.clone(),
    });

    // Build tool config if tools are present
    let tool_config = if let Some(tools) = &request.tools {
        let tool_specs: Vec<ToolSpec> = tools
            .iter()
            .map(|tool| ToolSpec {
                tool_spec: ToolSpecDefinition {
                    name: tool.function.name.clone(),
                    description: tool.function.description.clone().unwrap_or_default(),
                    input_schema: InputSchema {
                        json: tool
                            .function
                            .parameters
                            .clone()
                            .unwrap_or(Value::Object(Default::default())),
                    },
                },
            })
            .collect();

        Some(ToolConfig {
            tools: tool_specs,
            tool_choice: None, // NOTE: tool_choice mapping not yet implemented
        })
    } else {
        None
    };

    Ok(ConverseRequest {
        messages,
        system: if system_messages.is_empty() {
            None
        } else {
            Some(system_messages)
        },
        inference_config,
        tool_config,
        guardrail_config: None, // NOTE: guardrail support not yet implemented
        additional_model_request_fields: None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::types::{chat::ChatMessage, message::MessageContent, message::MessageRole};

    // ==================== Data Structure Tests ====================

    #[test]
    fn test_converse_message_serialization() {
        let message = ConverseMessage {
            role: "user".to_string(),
            content: vec![ContentBlock::Text {
                text: "Hello".to_string(),
            }],
        };

        let json = serde_json::to_value(&message).unwrap();
        assert_eq!(json["role"], "user");
        assert!(json["content"].is_array());
    }

    #[test]
    fn test_system_message_with_text() {
        let msg = SystemMessage {
            text: Some("You are a helpful assistant".to_string()),
            guardrail_content: None,
        };

        let json = serde_json::to_value(&msg).unwrap();
        assert_eq!(json["text"], "You are a helpful assistant");
        assert!(json.get("guardrail_content").is_none());
    }

    #[test]
    fn test_system_message_with_guardrail() {
        let msg = SystemMessage {
            text: None,
            guardrail_content: Some(GuardrailContent {
                text: "Safety content".to_string(),
            }),
        };

        let json = serde_json::to_value(&msg).unwrap();
        assert!(json.get("text").is_none());
        assert_eq!(json["guardrail_content"]["text"], "Safety content");
    }

    #[test]
    fn test_content_block_text() {
        let block = ContentBlock::Text {
            text: "Hello world".to_string(),
        };

        let json = serde_json::to_value(&block).unwrap();
        assert_eq!(json["text"]["text"], "Hello world");
    }

    #[test]
    fn test_content_block_image() {
        let block = ContentBlock::Image {
            image: ImageBlock {
                format: "png".to_string(),
                source: ImageSource::Bytes {
                    bytes: "base64data".to_string(),
                },
            },
        };

        let json = serde_json::to_value(&block).unwrap();
        assert_eq!(json["image"]["image"]["format"], "png");
    }

    #[test]
    fn test_content_block_document() {
        let block = ContentBlock::Document {
            document: DocumentBlock {
                format: "pdf".to_string(),
                name: "test.pdf".to_string(),
                source: DocumentSource::Bytes {
                    bytes: "pdfdata".to_string(),
                },
            },
        };

        let json = serde_json::to_value(&block).unwrap();
        assert_eq!(json["document"]["document"]["format"], "pdf");
        assert_eq!(json["document"]["document"]["name"], "test.pdf");
    }

    #[test]
    fn test_tool_use_block() {
        let block = ContentBlock::ToolUse {
            tool_use: ToolUseBlock {
                tool_use_id: "tool-123".to_string(),
                name: "get_weather".to_string(),
                input: serde_json::json!({"location": "NYC"}),
            },
        };

        let json = serde_json::to_value(&block).unwrap();
        // ContentBlock::ToolUse serializes as:
        // { "toolUse": { "tool_use": { "toolUseId": "...", "name": "...", ... } } }
        // - outer key "toolUse" comes from enum variant with rename_all = "camelCase"
        // - inner key "tool_use" is the field name in the enum variant
        // - field names inside ToolUseBlock use camelCase (toolUseId)
        assert!(json.get("toolUse").is_some());
        let inner = &json["toolUse"]["tool_use"];
        assert_eq!(inner["toolUseId"], "tool-123");
        assert_eq!(inner["name"], "get_weather");
    }

    #[test]
    fn test_tool_result_block() {
        let block = ContentBlock::ToolResult {
            tool_result: ToolResultBlock {
                tool_use_id: "tool-123".to_string(),
                content: vec![ToolResultContent::Text {
                    text: "Weather is sunny".to_string(),
                }],
                status: Some("success".to_string()),
            },
        };

        let json = serde_json::to_value(&block).unwrap();
        // Similar to ToolUse, serializes as:
        // { "toolResult": { "tool_result": { ... } } }
        let inner = &json["toolResult"]["tool_result"];
        assert_eq!(inner["toolUseId"], "tool-123");
    }

    #[test]
    fn test_inference_config_full() {
        let config = InferenceConfig {
            max_tokens: Some(1000),
            temperature: Some(0.7),
            top_p: Some(0.9),
            stop_sequences: Some(vec!["STOP".to_string()]),
        };

        let json = serde_json::to_value(&config).unwrap();
        assert_eq!(json["maxTokens"], 1000);
        assert_eq!(json["temperature"], 0.7);
        assert_eq!(json["topP"], 0.9);
    }

    #[test]
    fn test_inference_config_minimal() {
        let config = InferenceConfig {
            max_tokens: None,
            temperature: None,
            top_p: None,
            stop_sequences: None,
        };

        let json = serde_json::to_value(&config).unwrap();
        // All fields should be omitted due to skip_serializing_if
        assert!(json.as_object().unwrap().is_empty());
    }

    #[test]
    fn test_tool_spec() {
        let spec = ToolSpec {
            tool_spec: ToolSpecDefinition {
                name: "calculator".to_string(),
                description: "Performs calculations".to_string(),
                input_schema: InputSchema {
                    json: serde_json::json!({
                        "type": "object",
                        "properties": {
                            "expression": {"type": "string"}
                        }
                    }),
                },
            },
        };

        let json = serde_json::to_value(&spec).unwrap();
        assert_eq!(json["toolSpec"]["name"], "calculator");
        assert_eq!(json["toolSpec"]["description"], "Performs calculations");
    }

    #[test]
    fn test_tool_choice_auto() {
        let choice = ToolChoice::Auto;
        let json = serde_json::to_value(&choice).unwrap();
        assert_eq!(json, "auto");
    }

    #[test]
    fn test_tool_choice_any() {
        let choice = ToolChoice::Any;
        let json = serde_json::to_value(&choice).unwrap();
        assert_eq!(json, "any");
    }

    #[test]
    fn test_tool_choice_specific_tool() {
        let choice = ToolChoice::Tool {
            name: "get_weather".to_string(),
        };
        let json = serde_json::to_value(&choice).unwrap();
        assert_eq!(json["tool"]["name"], "get_weather");
    }

    #[test]
    fn test_guardrail_config() {
        let config = GuardrailConfig {
            guardrail_identifier: "guardrail-123".to_string(),
            guardrail_version: "1.0".to_string(),
            trace: Some(true),
        };

        let json = serde_json::to_value(&config).unwrap();
        assert_eq!(json["guardrailIdentifier"], "guardrail-123");
        assert_eq!(json["guardrailVersion"], "1.0");
        assert_eq!(json["trace"], true);
    }

    #[test]
    fn test_image_source_bytes() {
        let source = ImageSource::Bytes {
            bytes: "base64imagedata".to_string(),
        };

        let json = serde_json::to_value(&source).unwrap();
        assert_eq!(json["bytes"]["bytes"], "base64imagedata");
    }

    #[test]
    fn test_document_source_bytes() {
        let source = DocumentSource::Bytes {
            bytes: "base64docdata".to_string(),
        };

        let json = serde_json::to_value(&source).unwrap();
        assert_eq!(json["bytes"]["bytes"], "base64docdata");
    }

    // ==================== Transform Tests ====================

    #[test]
    fn test_transform_simple_user_message() {
        let request = ChatRequest {
            model: "anthropic.claude-3-sonnet".to_string(),
            messages: vec![ChatMessage {
                role: MessageRole::User,
                content: Some(MessageContent::Text("Hello".to_string())),
                name: None,
                tool_calls: None,
                tool_call_id: None,
                ..Default::default()
            }],
            ..Default::default()
        };

        let result = transform_to_converse(&request);
        assert!(result.is_ok());

        let converse = result.unwrap();
        assert_eq!(converse.messages.len(), 1);
        assert_eq!(converse.messages[0].role, "user");
    }

    #[test]
    fn test_transform_with_system_message() {
        let request = ChatRequest {
            model: "anthropic.claude-3-sonnet".to_string(),
            messages: vec![
                ChatMessage {
                    role: MessageRole::System,
                    content: Some(MessageContent::Text("You are helpful".to_string())),
                    ..Default::default()
                },
                ChatMessage {
                    role: MessageRole::User,
                    content: Some(MessageContent::Text("Hello".to_string())),
                    ..Default::default()
                },
            ],
            ..Default::default()
        };

        let result = transform_to_converse(&request);
        assert!(result.is_ok());

        let converse = result.unwrap();
        assert!(converse.system.is_some());
        let system = converse.system.unwrap();
        assert_eq!(system.len(), 1);
        assert_eq!(system[0].text, Some("You are helpful".to_string()));
    }

    #[test]
    fn test_transform_with_inference_config() {
        let request = ChatRequest {
            model: "anthropic.claude-3-sonnet".to_string(),
            messages: vec![ChatMessage {
                role: MessageRole::User,
                content: Some(MessageContent::Text("Hello".to_string())),
                ..Default::default()
            }],
            max_tokens: Some(500),
            temperature: Some(0.8),
            top_p: Some(0.95),
            stop: Some(vec!["END".to_string()]),
            ..Default::default()
        };

        let result = transform_to_converse(&request);
        assert!(result.is_ok());

        let converse = result.unwrap();
        assert!(converse.inference_config.is_some());

        let config = converse.inference_config.unwrap();
        assert_eq!(config.max_tokens, Some(500));
        assert!((config.temperature.unwrap() - 0.8).abs() < 0.001);
        assert!((config.top_p.unwrap() - 0.95).abs() < 0.001);
        assert_eq!(config.stop_sequences, Some(vec!["END".to_string()]));
    }

    #[test]
    fn test_transform_conversation() {
        let request = ChatRequest {
            model: "anthropic.claude-3-sonnet".to_string(),
            messages: vec![
                ChatMessage {
                    role: MessageRole::User,
                    content: Some(MessageContent::Text("Hi".to_string())),
                    ..Default::default()
                },
                ChatMessage {
                    role: MessageRole::Assistant,
                    content: Some(MessageContent::Text("Hello!".to_string())),
                    ..Default::default()
                },
                ChatMessage {
                    role: MessageRole::User,
                    content: Some(MessageContent::Text("How are you?".to_string())),
                    ..Default::default()
                },
            ],
            ..Default::default()
        };

        let result = transform_to_converse(&request);
        assert!(result.is_ok());

        let converse = result.unwrap();
        assert_eq!(converse.messages.len(), 3);
        assert_eq!(converse.messages[0].role, "user");
        assert_eq!(converse.messages[1].role, "assistant");
        assert_eq!(converse.messages[2].role, "user");
    }

    #[test]
    fn test_transform_empty_messages() {
        let request = ChatRequest {
            model: "anthropic.claude-3-sonnet".to_string(),
            messages: vec![],
            ..Default::default()
        };

        let result = transform_to_converse(&request);
        assert!(result.is_ok());

        let converse = result.unwrap();
        assert!(converse.messages.is_empty());
        assert!(converse.system.is_none());
    }

    #[test]
    fn test_transform_message_without_content() {
        let request = ChatRequest {
            model: "anthropic.claude-3-sonnet".to_string(),
            messages: vec![ChatMessage {
                role: MessageRole::User,
                content: None,
                ..Default::default()
            }],
            ..Default::default()
        };

        let result = transform_to_converse(&request);
        assert!(result.is_ok());

        let converse = result.unwrap();
        assert_eq!(converse.messages.len(), 1);
        assert!(converse.messages[0].content.is_empty());
    }

    // ==================== Converse Request Full Tests ====================

    #[test]
    fn test_converse_request_serialization() {
        let request = ConverseRequest {
            messages: vec![ConverseMessage {
                role: "user".to_string(),
                content: vec![ContentBlock::Text {
                    text: "Hello".to_string(),
                }],
            }],
            system: Some(vec![SystemMessage {
                text: Some("Be helpful".to_string()),
                guardrail_content: None,
            }]),
            inference_config: Some(InferenceConfig {
                max_tokens: Some(100),
                temperature: Some(0.5),
                top_p: None,
                stop_sequences: None,
            }),
            tool_config: None,
            guardrail_config: None,
            additional_model_request_fields: None,
        };

        let json = serde_json::to_value(&request).unwrap();
        assert!(json["messages"].is_array());
        assert!(json["system"].is_array());
        assert_eq!(json["inferenceConfig"]["maxTokens"], 100);
    }

    #[test]
    fn test_converse_request_deserialization() {
        let json = serde_json::json!({
            "messages": [{
                "role": "user",
                "content": [{"text": {"text": "Hello"}}]
            }],
            "inferenceConfig": {
                "maxTokens": 200
            }
        });

        let request: ConverseRequest = serde_json::from_value(json).unwrap();
        assert_eq!(request.messages.len(), 1);
        assert_eq!(request.messages[0].role, "user");
    }

    // ==================== Tool Result Content Tests ====================

    #[test]
    fn test_tool_result_content_text() {
        let content = ToolResultContent::Text {
            text: "Result text".to_string(),
        };

        let json = serde_json::to_value(&content).unwrap();
        assert_eq!(json["text"]["text"], "Result text");
    }

    #[test]
    fn test_tool_result_content_image() {
        let content = ToolResultContent::Image {
            image: ImageBlock {
                format: "jpeg".to_string(),
                source: ImageSource::Bytes {
                    bytes: "imagedata".to_string(),
                },
            },
        };

        let json = serde_json::to_value(&content).unwrap();
        assert_eq!(json["image"]["image"]["format"], "jpeg");
    }

    #[test]
    fn test_tool_result_content_document() {
        let content = ToolResultContent::Document {
            document: DocumentBlock {
                format: "txt".to_string(),
                name: "result.txt".to_string(),
                source: DocumentSource::Bytes {
                    bytes: "docdata".to_string(),
                },
            },
        };

        let json = serde_json::to_value(&content).unwrap();
        assert_eq!(json["document"]["document"]["name"], "result.txt");
    }

    // ==================== Tool Config Tests ====================

    #[test]
    fn test_tool_config_with_tools() {
        let config = ToolConfig {
            tools: vec![
                ToolSpec {
                    tool_spec: ToolSpecDefinition {
                        name: "tool1".to_string(),
                        description: "First tool".to_string(),
                        input_schema: InputSchema {
                            json: serde_json::json!({}),
                        },
                    },
                },
                ToolSpec {
                    tool_spec: ToolSpecDefinition {
                        name: "tool2".to_string(),
                        description: "Second tool".to_string(),
                        input_schema: InputSchema {
                            json: serde_json::json!({}),
                        },
                    },
                },
            ],
            tool_choice: Some(ToolChoice::Auto),
        };

        let json = serde_json::to_value(&config).unwrap();
        assert_eq!(json["tools"].as_array().unwrap().len(), 2);
        // ToolConfig has no rename_all, so field stays as tool_choice
        assert_eq!(json["tool_choice"], "auto");
    }

    #[test]
    fn test_guardrail_content() {
        let content = GuardrailContent {
            text: "Safety message".to_string(),
        };

        let json = serde_json::to_value(&content).unwrap();
        assert_eq!(json["text"], "Safety message");
    }

    #[test]
    fn test_content_block_guardrail() {
        let block = ContentBlock::GuardrailContent {
            guardrail_content: GuardrailContent {
                text: "Guardrail text".to_string(),
            },
        };

        let json = serde_json::to_value(&block).unwrap();
        assert!(json.get("guardrailContent").is_some());
    }
}