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
//! Gemini Code Execution Support
//!
//! This module implements Google Gemini's code execution feature which allows
//! the model to write and execute Python code to solve problems.
//!
//! API Reference: <https://ai.google.dev/gemini-api/docs/code-execution>

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::error::LlmError;
use crate::types::ChatResponse;

/// Code execution configuration for Gemini
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeExecutionConfig {
    /// Whether code execution is enabled
    pub enabled: bool,
    /// Maximum execution time in seconds
    pub timeout: Option<u32>,
    /// Allowed libraries/packages
    pub allowed_packages: Option<Vec<String>>,
    /// Code execution environment
    pub environment: CodeExecutionEnvironment,
    /// Whether to include execution output in response
    pub include_output: bool,
}

impl Default for CodeExecutionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            timeout: Some(30),
            allowed_packages: None,
            environment: CodeExecutionEnvironment::Python,
            include_output: true,
        }
    }
}

impl CodeExecutionConfig {
    /// Create a new code execution configuration
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable code execution
    pub const fn enable(mut self) -> Self {
        self.enabled = true;
        self
    }

    /// Disable code execution
    pub const fn disable(mut self) -> Self {
        self.enabled = false;
        self
    }

    /// Set execution timeout
    pub const fn with_timeout(mut self, timeout_seconds: u32) -> Self {
        self.timeout = Some(timeout_seconds);
        self
    }

    /// Set allowed packages
    pub fn with_allowed_packages(mut self, packages: Vec<String>) -> Self {
        self.allowed_packages = Some(packages);
        self
    }

    /// Set execution environment
    pub const fn with_environment(mut self, environment: CodeExecutionEnvironment) -> Self {
        self.environment = environment;
        self
    }

    /// Set whether to include output
    pub const fn include_output(mut self, include: bool) -> Self {
        self.include_output = include;
        self
    }

    /// Convert to request parameters
    pub fn to_request_params(&self) -> HashMap<String, serde_json::Value> {
        let mut params = HashMap::new();

        if self.enabled {
            let mut tools = Vec::new();

            let mut code_execution_tool = serde_json::json!({
                "code_execution": {}
            });

            // Add timeout if specified
            if let Some(timeout) = self.timeout {
                code_execution_tool["code_execution"]["timeout"] =
                    serde_json::Value::Number(timeout.into());
            }

            // Add allowed packages if specified
            if let Some(ref packages) = self.allowed_packages {
                code_execution_tool["code_execution"]["allowed_packages"] =
                    serde_json::Value::Array(
                        packages
                            .iter()
                            .map(|p| serde_json::Value::String(p.clone()))
                            .collect(),
                    );
            }

            tools.push(code_execution_tool);
            params.insert("tools".to_string(), serde_json::Value::Array(tools));
        }

        params
    }
}

/// Code execution environment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CodeExecutionEnvironment {
    /// Python environment
    Python,
    /// JavaScript environment (if supported)
    JavaScript,
}

/// Code execution result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeExecutionResult {
    /// Executed code
    pub code: String,
    /// Execution output
    pub output: Option<String>,
    /// Execution error (if any)
    pub error: Option<String>,
    /// Execution time in milliseconds
    pub execution_time: Option<u64>,
    /// Generated files or artifacts
    pub artifacts: Vec<CodeArtifact>,
}

/// Code artifact (generated files, plots, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeArtifact {
    /// Artifact type
    pub artifact_type: ArtifactType,
    /// Artifact name/filename
    pub name: String,
    /// Artifact content (base64 encoded for binary)
    pub content: String,
    /// MIME type
    pub mime_type: String,
    /// Artifact metadata
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Artifact type enumeration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ArtifactType {
    /// Text file
    Text,
    /// Image file
    Image,
    /// Data file (CSV, JSON, etc.)
    Data,
    /// Plot/visualization
    Plot,
    /// Other binary file
    Binary,
}

/// Code execution parser
pub struct CodeExecutionParser;

impl CodeExecutionParser {
    /// Extract code execution results from Gemini response
    pub fn extract_execution_results(response: &ChatResponse) -> Vec<CodeExecutionResult> {
        let mut results = Vec::new();

        // Check provider data for code execution results
        if let Some(execution_data) = response.metadata.get("code_execution") {
            if let Some(executions) = execution_data.as_array() {
                for execution in executions {
                    if let Ok(result) = Self::parse_execution_result(execution) {
                        results.push(result);
                    }
                }
            } else if let Ok(result) = Self::parse_execution_result(execution_data) {
                results.push(result);
            }
        }

        results
    }

    /// Parse a single execution result
    fn parse_execution_result(data: &serde_json::Value) -> Result<CodeExecutionResult, LlmError> {
        let code = data
            .get("code")
            .and_then(|c| c.as_str())
            .unwrap_or("")
            .to_string();

        let output = data
            .get("output")
            .and_then(|o| o.as_str())
            .map(std::string::ToString::to_string);

        let error = data
            .get("error")
            .and_then(|e| e.as_str())
            .map(std::string::ToString::to_string);

        let execution_time = data
            .get("execution_time")
            .and_then(serde_json::Value::as_u64);

        let artifacts = data
            .get("artifacts")
            .and_then(|a| a.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|item| Self::parse_artifact(item).ok())
                    .collect()
            })
            .unwrap_or_default();

        Ok(CodeExecutionResult {
            code,
            output,
            error,
            execution_time,
            artifacts,
        })
    }

    /// Parse a code artifact
    fn parse_artifact(data: &serde_json::Value) -> Result<CodeArtifact, LlmError> {
        let artifact_type = data
            .get("type")
            .and_then(|t| t.as_str())
            .map(|s| match s {
                "image" => ArtifactType::Image,
                "data" => ArtifactType::Data,
                "plot" => ArtifactType::Plot,
                "binary" => ArtifactType::Binary,
                _ => ArtifactType::Text,
            })
            .unwrap_or(ArtifactType::Text);

        let name = data
            .get("name")
            .and_then(|n| n.as_str())
            .unwrap_or("untitled")
            .to_string();

        let content = data
            .get("content")
            .and_then(|c| c.as_str())
            .unwrap_or("")
            .to_string();

        let mime_type = data
            .get("mime_type")
            .and_then(|m| m.as_str())
            .unwrap_or("text/plain")
            .to_string();

        let metadata = data
            .get("metadata")
            .and_then(|m| m.as_object())
            .map(|obj| obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
            .unwrap_or_default();

        Ok(CodeArtifact {
            artifact_type,
            name,
            content,
            mime_type,
            metadata,
        })
    }

    /// Format execution results for display
    pub fn format_execution_results(results: &[CodeExecutionResult]) -> String {
        let mut formatted = String::new();

        for (i, result) in results.iter().enumerate() {
            formatted.push_str(&format!("🔧 **Code Execution {}:**\n\n", i + 1));
            formatted.push_str(&format!("```python\n{}\n```\n\n", result.code));

            if let Some(ref output) = result.output {
                formatted.push_str(&format!("📤 **Output:**\n```\n{output}\n```\n\n"));
            }

            if let Some(ref error) = result.error {
                formatted.push_str(&format!("❌ **Error:**\n```\n{error}\n```\n\n"));
            }

            if let Some(time) = result.execution_time {
                formatted.push_str(&format!("⏱️ **Execution Time:** {time}ms\n\n"));
            }

            if !result.artifacts.is_empty() {
                formatted.push_str("📁 **Generated Artifacts:**\n");
                for artifact in &result.artifacts {
                    formatted.push_str(&format!("- {} ({})\n", artifact.name, artifact.mime_type));
                }
                formatted.push('\n');
            }
        }

        formatted
    }
}

/// Helper functions for common code execution patterns
pub mod patterns {
    use super::*;

    /// Create a data analysis configuration
    pub fn data_analysis_config() -> CodeExecutionConfig {
        CodeExecutionConfig::new()
            .enable()
            .with_timeout(60)
            .with_allowed_packages(vec![
                "pandas".to_string(),
                "numpy".to_string(),
                "matplotlib".to_string(),
                "seaborn".to_string(),
                "scipy".to_string(),
            ])
            .include_output(true)
    }

    /// Create a machine learning configuration
    pub fn machine_learning_config() -> CodeExecutionConfig {
        CodeExecutionConfig::new()
            .enable()
            .with_timeout(120)
            .with_allowed_packages(vec![
                "scikit-learn".to_string(),
                "pandas".to_string(),
                "numpy".to_string(),
                "matplotlib".to_string(),
                "seaborn".to_string(),
            ])
            .include_output(true)
    }

    /// Create a visualization configuration
    pub fn visualization_config() -> CodeExecutionConfig {
        CodeExecutionConfig::new()
            .enable()
            .with_timeout(45)
            .with_allowed_packages(vec![
                "matplotlib".to_string(),
                "seaborn".to_string(),
                "plotly".to_string(),
                "pandas".to_string(),
                "numpy".to_string(),
            ])
            .include_output(true)
    }

    /// Create a basic math configuration
    pub fn math_config() -> CodeExecutionConfig {
        CodeExecutionConfig::new()
            .enable()
            .with_timeout(30)
            .with_allowed_packages(vec![
                "numpy".to_string(),
                "scipy".to_string(),
                "sympy".to_string(),
                "math".to_string(),
            ])
            .include_output(true)
    }
}

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

    #[test]
    fn test_code_execution_config() {
        let config = CodeExecutionConfig::new()
            .enable()
            .with_timeout(60)
            .with_allowed_packages(vec!["pandas".to_string(), "numpy".to_string()])
            .include_output(true);

        assert!(config.enabled);
        assert_eq!(config.timeout, Some(60));
        assert_eq!(
            config.allowed_packages,
            Some(vec!["pandas".to_string(), "numpy".to_string()])
        );
        assert!(config.include_output);
    }

    #[test]
    fn test_request_params() {
        let config = CodeExecutionConfig::new().enable().with_timeout(30);

        let params = config.to_request_params();
        assert!(params.contains_key("tools"));

        let tools = params.get("tools").unwrap().as_array().unwrap();
        assert_eq!(tools.len(), 1);
        assert!(tools[0]["code_execution"].is_object());
    }

    #[test]
    fn test_data_analysis_pattern() {
        let config = patterns::data_analysis_config();
        assert!(config.enabled);
        assert_eq!(config.timeout, Some(60));
        assert!(config.allowed_packages.is_some());
        assert!(
            config
                .allowed_packages
                .as_ref()
                .unwrap()
                .contains(&"pandas".to_string())
        );
    }

    #[test]
    fn test_artifact_parsing() {
        let artifact_data = serde_json::json!({
            "type": "image",
            "name": "plot.png",
            "content": "base64encodeddata",
            "mime_type": "image/png",
            "metadata": {
                "width": 800,
                "height": 600
            }
        });

        let artifact = CodeExecutionParser::parse_artifact(&artifact_data).unwrap();
        assert!(matches!(artifact.artifact_type, ArtifactType::Image));
        assert_eq!(artifact.name, "plot.png");
        assert_eq!(artifact.mime_type, "image/png");
    }
}