siumai 0.10.3

A unified LLM interface library for Rust
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
//! Parameter Validation Test
//!
//! This test verifies that we correctly handle both common_params and provider-specific params
//! across all providers, ensuring proper parameter precedence and merging.

use siumai::prelude::*;

#[test]
fn test_common_params_structure() {
    println!("๐Ÿ” Testing CommonParams structure and defaults");

    let default_params = CommonParams::default();
    println!("   Default model: '{}'", default_params.model);
    println!("   Default temperature: {:?}", default_params.temperature);
    println!("   Default max_tokens: {:?}", default_params.max_tokens);
    println!("   Default top_p: {:?}", default_params.top_p);
    println!(
        "   Default stop_sequences: {:?}",
        default_params.stop_sequences
    );
    println!("   Default seed: {:?}", default_params.seed);

    // Verify that default creates empty/None values (as expected)
    assert!(
        default_params.model.is_empty(),
        "Default model should be empty"
    );
    assert!(
        default_params.temperature.is_none(),
        "Default temperature should be None"
    );
    assert!(
        default_params.max_tokens.is_none(),
        "Default max_tokens should be None"
    );

    println!("   โœ… CommonParams defaults are correct");
}

#[test]
fn test_provider_specific_params() {
    println!("\n๐Ÿ” Testing provider-specific parameters");

    // Test that we can import and use provider-specific params
    use siumai::params::{AnthropicParams, OpenAiParams};

    let openai_params = OpenAiParams::default();
    println!(
        "   OpenAI params created: {:?}",
        openai_params.response_format
    );

    let anthropic_params = AnthropicParams::default();
    println!("   Anthropic params created: {:?}", anthropic_params.system);

    println!("   โœ… Provider-specific params are accessible");
}

#[tokio::test]
async fn test_parameter_integration() {
    println!("\n๐Ÿงช Testing parameter integration with clients");

    // Test that clients can be created with parameters
    if let Ok(api_key) = std::env::var("OPENAI_API_KEY") {
        let client = Provider::openai()
            .api_key(&api_key)
            .model("gpt-4o-mini")
            .temperature(0.7)
            .max_tokens(50)
            .build()
            .await;

        match client {
            Ok(_) => println!("   โœ… OpenAI client created with parameters"),
            Err(e) => println!("   โš ๏ธ OpenAI client creation failed: {}", e),
        }
    } else {
        println!("   โญ๏ธ Skipping OpenAI test (no API key)");
    }

    if let Ok(api_key) = std::env::var("XAI_API_KEY") {
        let client = Provider::xai()
            .api_key(&api_key)
            .model("grok-3")
            .temperature(0.8)
            .max_tokens(30)
            .build()
            .await;

        match client {
            Ok(_) => println!("   โœ… xAI client created with parameters"),
            Err(e) => println!("   โš ๏ธ xAI client creation failed: {}", e),
        }
    } else {
        println!("   โญ๏ธ Skipping xAI test (no API key)");
    }

    if let Ok(api_key) = std::env::var("ANTHROPIC_API_KEY") {
        let client = Provider::anthropic()
            .api_key(&api_key)
            .model("claude-3-5-haiku-20241022")
            .temperature(0.9)
            .max_tokens(40)
            .build()
            .await;

        match client {
            Ok(_) => println!("   โœ… Anthropic client created with parameters"),
            Err(e) => println!("   โš ๏ธ Anthropic client creation failed: {}", e),
        }
    } else {
        println!("   โญ๏ธ Skipping Anthropic test (no API key)");
    }

    println!("   โœ… Parameter integration test completed");
}

#[tokio::test]
async fn test_chat_capability_streaming_parameter_passing() {
    println!("\n๐Ÿ”ง Testing ChatCapability STREAMING parameter passing");

    // This test verifies that our ChatCapability fix correctly passes parameters in streaming mode
    if let Ok(api_key) = std::env::var("XAI_API_KEY") {
        let client = Provider::xai()
            .api_key(&api_key)
            .model("grok-3")
            .temperature(0.5)
            .max_tokens(20)
            .build()
            .await
            .expect("Failed to create xAI client");

        println!("   โœ… xAI client created with specific parameters");

        // Test that ChatCapability trait method works with parameters
        use siumai::traits::ChatCapability;
        let capability: &dyn ChatCapability = &client;

        let messages = vec![user!("Say 'test' in one word")];

        match capability.chat_stream(messages, None).await {
            Ok(mut stream) => {
                use futures_util::StreamExt;
                println!("   โœ… ChatCapability.chat_stream() works with parameters");

                let mut content = String::new();
                let mut count = 0;
                while let Some(event) = stream.next().await {
                    match event {
                        Ok(ChatStreamEvent::ContentDelta { delta, .. }) => {
                            content.push_str(&delta);
                            count += 1;
                            if count >= 3 {
                                break;
                            }
                        }
                        Ok(ChatStreamEvent::StreamEnd { .. }) => break,
                        Err(e) => {
                            println!("      โš ๏ธ Stream error: {}", e);
                            break;
                        }
                        _ => {}
                    }
                }

                if !content.is_empty() {
                    println!("      Streaming response: {}", content.trim());
                    println!(
                        "   โœ… Parameters correctly passed through ChatCapability (streaming)"
                    );
                } else {
                    println!(
                        "   โš ๏ธ No content received, but no model errors (parameters likely correct)"
                    );
                }
            }
            Err(e) => {
                if e.to_string().contains("model") || e.to_string().contains("404") {
                    println!("   โŒ Model error suggests parameter passing issue: {}", e);
                    println!("   โš ๏ธ This may indicate incompatibility with the provider");
                } else {
                    println!("   โš ๏ธ Non-model error (likely API key issue): {}", e);
                }
            }
        }
    } else {
        println!("   โญ๏ธ Skipping xAI ChatCapability streaming test (no API key)");
    }
}

#[tokio::test]
async fn test_chat_capability_non_streaming_parameter_passing() {
    println!("\n๐Ÿ”ง Testing ChatCapability NON-STREAMING parameter passing");

    // This test verifies that our ChatCapability fix correctly passes parameters in non-streaming mode
    if let Ok(api_key) = std::env::var("XAI_API_KEY") {
        let client = Provider::xai()
            .api_key(&api_key)
            .model("grok-3")
            .temperature(0.5)
            .max_tokens(20)
            .build()
            .await
            .expect("Failed to create xAI client");

        println!("   โœ… xAI client created with specific parameters");

        // Test that ChatCapability trait method works with parameters
        use siumai::traits::ChatCapability;
        let capability: &dyn ChatCapability = &client;

        let messages = vec![user!("Say 'test' in one word")];

        match capability.chat(messages).await {
            Ok(response) => {
                println!("   โœ… ChatCapability.chat() works with parameters");
                let content_str = match &response.content {
                    siumai::types::MessageContent::Text(text) => text.as_str(),
                    _ => "[non-text content]",
                };
                println!(
                    "      Non-streaming response: {}",
                    content_str.chars().take(50).collect::<String>()
                );
                println!(
                    "   โœ… Parameters correctly passed through ChatCapability (non-streaming)"
                );
            }
            Err(e) => {
                if e.to_string().contains("model") || e.to_string().contains("404") {
                    println!("   โŒ Model error suggests parameter passing issue: {}", e);
                    println!("   โš ๏ธ This may indicate incompatibility with the provider");
                } else {
                    println!("   โš ๏ธ Non-model error (likely API key issue): {}", e);
                }
            }
        }
    } else {
        println!("   โญ๏ธ Skipping xAI ChatCapability non-streaming test (no API key)");
    }
}

#[test]
fn test_parameter_architecture() {
    println!("\n๐Ÿ—๏ธ Testing parameter architecture");

    // Test that we have the expected parameter structure
    let common_params = CommonParams {
        model: "test-model".to_string(),
        temperature: Some(0.7),
        max_tokens: Some(100),
        top_p: Some(0.9),
        stop_sequences: Some(vec!["STOP".to_string()]),
        seed: Some(12345),
    };

    println!("   Common params structure:");
    println!("     Model: {}", common_params.model);
    println!("     Temperature: {:?}", common_params.temperature);
    println!("     Max tokens: {:?}", common_params.max_tokens);
    println!("     Top P: {:?}", common_params.top_p);
    println!("     Stop sequences: {:?}", common_params.stop_sequences);
    println!("     Seed: {:?}", common_params.seed);

    // Test provider-specific params
    use siumai::params::{AnthropicParams, OpenAiParams};

    let openai_params = OpenAiParams {
        response_format: None,
        tool_choice: None,
        parallel_tool_calls: Some(true),
        store: Some(false),
        ..Default::default()
    };

    println!("   OpenAI-specific params:");
    println!("     Response format: {:?}", openai_params.response_format);
    println!("     Tool choice: {:?}", openai_params.tool_choice);
    println!(
        "     Parallel tool calls: {:?}",
        openai_params.parallel_tool_calls
    );
    println!("     Store: {:?}", openai_params.store);

    let anthropic_params = AnthropicParams {
        system: Some("You are a helpful assistant".to_string()),
        ..Default::default()
    };

    println!("   Anthropic-specific params:");
    println!("     System: {:?}", anthropic_params.system);

    println!("   โœ… Parameter architecture is well-structured");
    println!("   ๐Ÿ’ก Common params provide shared functionality");
    println!("   ๐Ÿ’ก Provider-specific params allow customization");
    println!("   ๐Ÿ’ก Both types work together in our fixed ChatCapability implementation");
}

#[test]
fn test_simple_verification() {
    println!("๐Ÿงช Simple parameter verification test");

    // Test that CommonParams can be created
    use siumai::types::CommonParams;
    let params = CommonParams {
        model: "test-model".to_string(),
        temperature: Some(0.7),
        max_tokens: Some(100),
        top_p: Some(0.9),
        stop_sequences: Some(vec!["STOP".to_string()]),
        seed: Some(12345),
    };

    assert_eq!(params.model, "test-model");
    assert_eq!(params.temperature, Some(0.7));
    assert_eq!(params.max_tokens, Some(100));

    println!("   โœ… CommonParams creation and access works");

    // Test that ProviderParams can be created
    use siumai::types::ProviderParams;
    let provider_params = ProviderParams::openai()
        .with_param("frequency_penalty", 0.1)
        .with_param("presence_penalty", 0.2);

    println!("   โœ… ProviderParams creation works");

    // Test that we can get values back
    let freq_penalty: Option<f64> = provider_params.get("frequency_penalty");
    assert_eq!(freq_penalty, Some(0.1));

    println!("   โœ… ProviderParams value retrieval works");
    println!("   ๐ŸŽฏ Parameter handling is working correctly!");
}

#[tokio::test]
async fn test_comprehensive_parameter_passing() {
    println!("\n๐ŸŽฏ Comprehensive parameter passing test (streaming + non-streaming)");

    // Test OpenAI if available
    if let Ok(api_key) = std::env::var("OPENAI_API_KEY") {
        println!("   ๐Ÿ” Testing OpenAI parameter passing...");

        let client = Provider::openai()
            .api_key(&api_key)
            .model("gpt-4o-mini")
            .temperature(0.3)
            .max_tokens(15)
            .build()
            .await
            .expect("Failed to create OpenAI client");

        let messages = vec![user!("Say 'hello' in one word")];

        // Test non-streaming
        match client.chat(messages.clone()).await {
            Ok(response) => {
                let content_str = match &response.content {
                    siumai::types::MessageContent::Text(text) => text.as_str(),
                    _ => "[non-text]",
                };
                println!(
                    "      โœ… OpenAI non-streaming: {}",
                    content_str.chars().take(30).collect::<String>()
                );
            }
            Err(e) => println!("      โš ๏ธ OpenAI non-streaming failed: {}", e),
        }

        // Test streaming
        match client.chat_stream(messages, None).await {
            Ok(mut stream) => {
                use futures_util::StreamExt;
                let mut content = String::new();
                let mut count = 0;
                while let Some(event) = stream.next().await {
                    match event {
                        Ok(ChatStreamEvent::ContentDelta { delta, .. }) => {
                            content.push_str(&delta);
                            count += 1;
                            if count >= 3 {
                                break;
                            }
                        }
                        Ok(ChatStreamEvent::StreamEnd { .. }) => break,
                        Err(_) => break,
                        _ => {}
                    }
                }
                if !content.is_empty() {
                    println!(
                        "      โœ… OpenAI streaming: {}",
                        content.chars().take(30).collect::<String>()
                    );
                }
            }
            Err(e) => println!("      โš ๏ธ OpenAI streaming failed: {}", e),
        }
    } else {
        println!("   โญ๏ธ Skipping OpenAI tests (no API key)");
    }

    // Test Anthropic if available
    if let Ok(api_key) = std::env::var("ANTHROPIC_API_KEY") {
        println!("   ๐Ÿ” Testing Anthropic parameter passing...");

        let client = Provider::anthropic()
            .api_key(&api_key)
            .model("claude-3-5-haiku-20241022")
            .temperature(0.3)
            .max_tokens(15)
            .build()
            .await
            .expect("Failed to create Anthropic client");

        let messages = vec![user!("Say 'hello' in one word")];

        // Test non-streaming
        match client.chat(messages.clone()).await {
            Ok(response) => {
                let content_str = match &response.content {
                    siumai::types::MessageContent::Text(text) => text.as_str(),
                    _ => "[non-text]",
                };
                println!(
                    "      โœ… Anthropic non-streaming: {}",
                    content_str.chars().take(30).collect::<String>()
                );
            }
            Err(e) => println!("      โš ๏ธ Anthropic non-streaming failed: {}", e),
        }

        // Test streaming
        match client.chat_stream(messages, None).await {
            Ok(mut stream) => {
                use futures_util::StreamExt;
                let mut content = String::new();
                let mut count = 0;
                while let Some(event) = stream.next().await {
                    match event {
                        Ok(ChatStreamEvent::ContentDelta { delta, .. }) => {
                            content.push_str(&delta);
                            count += 1;
                            if count >= 3 {
                                break;
                            }
                        }
                        Ok(ChatStreamEvent::StreamEnd { .. }) => break,
                        Err(_) => break,
                        _ => {}
                    }
                }
                if !content.is_empty() {
                    println!(
                        "      โœ… Anthropic streaming: {}",
                        content.chars().take(30).collect::<String>()
                    );
                }
            }
            Err(e) => println!("      โš ๏ธ Anthropic streaming failed: {}", e),
        }
    } else {
        println!("   โญ๏ธ Skipping Anthropic tests (no API key)");
    }

    // Test xAI if available
    if let Ok(api_key) = std::env::var("XAI_API_KEY") {
        println!("   ๐Ÿ” Testing xAI parameter passing...");

        let client = Provider::xai()
            .api_key(&api_key)
            .model("grok-3")
            .temperature(0.3)
            .max_tokens(15)
            .build()
            .await
            .expect("Failed to create xAI client");

        let messages = vec![user!("Say 'hello' in one word")];

        // Test non-streaming
        match client.chat(messages.clone()).await {
            Ok(response) => {
                let content_str = match &response.content {
                    siumai::types::MessageContent::Text(text) => text.as_str(),
                    _ => "[non-text]",
                };
                println!(
                    "      โœ… xAI non-streaming: {}",
                    content_str.chars().take(30).collect::<String>()
                );
            }
            Err(e) => println!("      โš ๏ธ xAI non-streaming failed: {}", e),
        }

        // Test streaming
        match client.chat_stream(messages, None).await {
            Ok(mut stream) => {
                use futures_util::StreamExt;
                let mut content = String::new();
                let mut count = 0;
                while let Some(event) = stream.next().await {
                    match event {
                        Ok(ChatStreamEvent::ContentDelta { delta, .. }) => {
                            content.push_str(&delta);
                            count += 1;
                            if count >= 3 {
                                break;
                            }
                        }
                        Ok(ChatStreamEvent::StreamEnd { .. }) => break,
                        Err(_) => break,
                        _ => {}
                    }
                }
                if !content.is_empty() {
                    println!(
                        "      โœ… xAI streaming: {}",
                        content.chars().take(30).collect::<String>()
                    );
                }
            }
            Err(e) => println!("      โš ๏ธ xAI streaming failed: {}", e),
        }
    } else {
        println!("   โญ๏ธ Skipping xAI tests (no API key)");
    }

    println!("   ๐ŸŽฏ Comprehensive parameter passing test completed!");
    println!("   ๐Ÿ’ก Both streaming and non-streaming modes tested for all available providers");
}