assistants_code_interpreter/
assistants_code_interpreter.rs

1#![allow(clippy::uninlined_format_args)]
2#![allow(clippy::doc_markdown)]
3#![allow(clippy::unnecessary_wraps)]
4//! Assistants API Code Interpreter Example
5//!
6//! This example demonstrates how to use the OpenAI Assistants API with the Code Interpreter tool
7//! to perform data analysis, mathematical computations, and code execution tasks.
8//!
9//! ## Features Demonstrated
10//!
11//! - Creating assistants with code interpreter capabilities
12//! - Uploading data files for analysis
13//! - Running code execution tasks
14//! - Handling code interpreter outputs (text, images, data files)
15//! - Best practices for data analysis workflows
16//!
17//! ## Prerequisites
18//!
19//! Set your OpenAI API key:
20//! ```bash
21//! export OPENAI_API_KEY="your-key-here"
22//! ```
23//!
24//! ## Usage
25//!
26//! ```bash
27//! cargo run --example assistants_code_interpreter
28//! ```
29//!
30//! ## Note on Implementation Status
31//!
32//! This example demonstrates the intended API design for code interpreter functionality.
33//! The code shows how the ergonomic builders would work with the actual OpenAI API.
34
35use openai_ergonomic::{
36    builders::assistants::{
37        assistant_with_instructions, simple_run, simple_thread, tool_code_interpreter,
38        AssistantBuilder,
39    },
40    Client, Error,
41};
42
43#[tokio::main]
44async fn main() -> Result<(), Box<dyn std::error::Error>> {
45    println!(" OpenAI Ergonomic - Code Interpreter Assistant Example\n");
46
47    // Initialize client from environment variables
48    let _client = match Client::from_env() {
49        Ok(client_builder) => {
50            println!(" Client initialized successfully");
51            client_builder.build()
52        }
53        Err(e) => {
54            eprintln!(" Failed to initialize client: {e}");
55            eprintln!(" Make sure OPENAI_API_KEY is set in your environment");
56            return Err(e.into());
57        }
58    };
59
60    // Demonstrate different code interpreter use cases
61    run_data_analysis_example()?;
62    run_mathematical_computation_example()?;
63    run_visualization_example()?;
64    run_file_processing_example()?;
65
66    println!("\n Code Interpreter examples completed successfully!");
67    Ok(())
68}
69
70/// Example 1: Data Analysis with CSV Processing
71fn run_data_analysis_example() -> Result<(), Error> {
72    println!(" Example 1: Data Analysis with CSV Processing");
73    println!("{}", "=".repeat(60));
74
75    // Create an assistant specifically for data analysis
76    let assistant = assistant_with_instructions(
77        "gpt-4-1106-preview", // Model that supports code interpreter
78        "Data Analysis Assistant",
79        "You are a data analysis expert. Help users analyze datasets, create visualizations, and derive insights from data. Always explain your methodology and findings clearly.",
80    )
81    .description("A specialized assistant for data analysis tasks")
82    .add_tool(tool_code_interpreter());
83
84    println!(" Created data analysis assistant:");
85    println!("   Model: {}", assistant.model());
86    println!("   Name: {}", assistant.name_ref().unwrap_or("unnamed"));
87    println!(
88        "   Description: {}",
89        assistant.description_ref().unwrap_or("no description")
90    );
91
92    // Create a thread for the data analysis conversation
93    let _thread = simple_thread().metadata("purpose", "data-analysis");
94
95    println!("\n Created thread with metadata:");
96    println!("   Purpose: data-analysis");
97
98    // Simulate data analysis workflow
99    println!("\n Analysis Request:");
100    println!("   'I have sales data from the last quarter. Please analyze trends, identify top-performing products, and create visualizations showing monthly performance.'");
101
102    println!("\n Code Interpreter Workflow:");
103    println!("   1.  Assistant receives and processes CSV data");
104    println!("   2.  Executes Python code for data analysis");
105    println!("   3.  Generates visualizations (charts, graphs)");
106    println!("   4.  Calculates key metrics and trends");
107    println!("   5.  Provides summary report with insights");
108
109    println!("\n Expected Outputs:");
110    println!("   • Data summary statistics");
111    println!("   • Trend analysis charts");
112    println!("   • Top product performance metrics");
113    println!("   • Monthly comparison visualizations");
114    println!("   • Actionable business insights");
115
116    Ok(())
117}
118
119/// Example 2: Mathematical Computations and Modeling
120fn run_mathematical_computation_example() -> Result<(), Error> {
121    println!("\n Example 2: Mathematical Computations and Modeling");
122    println!("{}", "=".repeat(60));
123
124    // Create an assistant for mathematical tasks
125    let math_assistant = AssistantBuilder::new("gpt-4-1106-preview")
126        .name("Mathematics Professor")
127        .description("Expert in mathematical computations, modeling, and problem solving")
128        .instructions("You are a mathematics expert. Solve complex mathematical problems, create models, perform numerical analysis, and explain mathematical concepts clearly. Always show your work step by step.")
129        .add_tool(tool_code_interpreter());
130
131    println!(" Created mathematics assistant:");
132    println!("   Name: {}", math_assistant.name_ref().unwrap());
133    println!("   Focus: Complex mathematical computations");
134
135    // Create thread for mathematical discussion
136    let _math_thread = simple_thread()
137        .metadata("type", "mathematics")
138        .metadata("complexity", "advanced");
139
140    println!("\n Mathematics Problem:");
141    println!("   'Solve the differential equation dy/dx = x*y with initial condition y(0) = 1.'");
142    println!("   'Then plot the solution and analyze its behavior.'");
143
144    println!("\n Code Interpreter Mathematics Workflow:");
145    println!("   1.  Parse the differential equation");
146    println!("   2.  Apply analytical or numerical methods");
147    println!("   3.  Implement solution in Python/SymPy");
148    println!("   4.  Generate solution plots");
149    println!("   5.  Provide step-by-step explanation");
150
151    // Simulate creating a run for mathematical computation
152    let math_run = simple_run("assistant-math-123")
153        .instructions("Focus on providing clear mathematical explanations alongside code execution")
154        .temperature(0.1); // Lower temperature for mathematical precision
155
156    println!("\n Run Configuration:");
157    println!("   Assistant ID: {}", math_run.assistant_id());
158    println!(
159        "   Temperature: {:?} (low for precision)",
160        math_run.temperature_ref()
161    );
162
163    println!("\n Expected Mathematical Outputs:");
164    println!("   • Step-by-step solution derivation");
165    println!("   • Python code for numerical verification");
166    println!("   • Interactive plots showing solution behavior");
167    println!("   • Analysis of solution properties (growth rate, asymptotes)");
168    println!("   • Verification of initial conditions");
169
170    Ok(())
171}
172
173/// Example 3: Data Visualization and Chart Generation
174fn run_visualization_example() -> Result<(), Error> {
175    println!("\n Example 3: Data Visualization and Chart Generation");
176    println!("{}", "=".repeat(60));
177
178    // Create visualization-focused assistant
179    let _viz_assistant = assistant_with_instructions(
180        "gpt-4-1106-preview",
181        "Visualization Specialist",
182        "You are a data visualization expert. Create compelling, informative charts and graphs that effectively communicate data insights. Always consider best practices for visual design and choose appropriate chart types for the data."
183    )
184    .description("Creates professional data visualizations and charts")
185    .add_tool(tool_code_interpreter());
186
187    println!(" Created visualization assistant:");
188    println!("   Specialty: Data visualization and chart creation");
189
190    println!("\n Visualization Request:");
191    println!("   'Create a comprehensive dashboard showing website traffic data:'");
192    println!("   • Monthly visitor trends (line chart)");
193    println!("   • Traffic sources breakdown (pie chart)");
194    println!("   • Page performance heatmap");
195    println!("   • Conversion funnel visualization");
196
197    println!("\n Code Interpreter Visualization Workflow:");
198    println!("   1.  Analyze data structure and requirements");
199    println!("   2.  Select appropriate visualization types");
200    println!("   3.  Generate Python code using matplotlib/seaborn/plotly");
201    println!("   4.  Apply professional styling and color schemes");
202    println!("   5.  Create interactive or static visualizations");
203    println!("   6.  Export charts in various formats (PNG, SVG, HTML)");
204
205    println!("\n Expected Visualization Outputs:");
206    println!("   • Professional-quality charts and graphs");
207    println!("   • Interactive dashboards (when using plotly)");
208    println!("   • Downloadable image files");
209    println!("   • Chart customization code");
210    println!("   • Data insights derived from visualizations");
211
212    Ok(())
213}
214
215/// Example 4: File Processing and Analysis
216fn run_file_processing_example() -> Result<(), Error> {
217    println!("\n Example 4: File Processing and Analysis");
218    println!("{}", "=".repeat(60));
219
220    // Create file processing assistant
221    let _file_assistant = AssistantBuilder::new("gpt-4-1106-preview")
222        .name("File Processing Expert")
223        .description("Processes various file formats and performs analysis")
224        .instructions(
225            "You are a file processing expert. Handle various file formats (CSV, JSON, Excel, text files), clean and transform data, and perform comprehensive analysis. Always validate data integrity and handle edge cases."
226        )
227        .add_tool(tool_code_interpreter());
228
229    println!(" Created file processing assistant:");
230    println!("   Capabilities: Multi-format file processing and analysis");
231
232    println!("\n File Processing Tasks:");
233    println!("   • Process uploaded CSV files with sales data");
234    println!("   • Clean and validate data integrity");
235    println!("   • Transform data formats (CSV → JSON → Excel)");
236    println!("   • Generate summary statistics");
237    println!("   • Create processed output files");
238
239    println!("\n Code Interpreter File Processing Workflow:");
240    println!("   1.  Accept and validate uploaded files");
241    println!("   2.  Inspect file structure and content");
242    println!("   3.  Clean and preprocess data");
243    println!("   4.  Transform between formats");
244    println!("   5.  Perform statistical analysis");
245    println!("   6.  Generate processed output files");
246    println!("   7.  Provide processing summary and quality report");
247
248    // Demonstrate error handling for file processing
249    println!("\n Error Handling for File Processing:");
250    println!("   • File format validation");
251    println!("   • Data type checking and conversion");
252    println!("   • Missing value handling");
253    println!("   • Memory-efficient processing for large files");
254    println!("   • Graceful handling of corrupted data");
255
256    println!("\n Expected File Processing Outputs:");
257    println!("   • Cleaned and validated datasets");
258    println!("   • Multiple output formats (CSV, JSON, Excel)");
259    println!("   • Data quality reports");
260    println!("   • Processing logs and statistics");
261    println!("   • Transformed data ready for analysis");
262
263    Ok(())
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn test_data_analysis_assistant_creation() {
272        let assistant = assistant_with_instructions(
273            "gpt-4-1106-preview",
274            "Test Data Analyst",
275            "Test instructions for data analysis",
276        )
277        .add_tool(tool_code_interpreter());
278
279        assert_eq!(assistant.model(), "gpt-4-1106-preview");
280        assert_eq!(assistant.name_ref(), Some("Test Data Analyst"));
281        assert_eq!(
282            assistant.instructions_ref(),
283            Some("Test instructions for data analysis")
284        );
285    }
286
287    #[test]
288    fn test_math_assistant_builder() {
289        let assistant = AssistantBuilder::new("gpt-4")
290            .name("Math Assistant")
291            .description("Mathematics expert")
292            .instructions("Solve math problems")
293            .add_tool(tool_code_interpreter());
294
295        assert_eq!(assistant.model(), "gpt-4");
296        assert_eq!(assistant.name_ref(), Some("Math Assistant"));
297        assert_eq!(assistant.description_ref(), Some("Mathematics expert"));
298    }
299
300    #[test]
301    fn test_thread_metadata() {
302        let thread = simple_thread()
303            .metadata("purpose", "testing")
304            .metadata("type", "unit-test");
305
306        assert_eq!(thread.metadata_ref().len(), 2);
307        assert_eq!(
308            thread.metadata_ref().get("purpose"),
309            Some(&"testing".to_string())
310        );
311        assert_eq!(
312            thread.metadata_ref().get("type"),
313            Some(&"unit-test".to_string())
314        );
315    }
316
317    #[test]
318    fn test_run_configuration() {
319        let run = simple_run("test-assistant")
320            .temperature(0.1)
321            .stream(true)
322            .instructions("Custom instructions for testing");
323
324        assert_eq!(run.assistant_id(), "test-assistant");
325        assert_eq!(run.temperature_ref(), Some(0.1));
326        assert!(run.is_streaming());
327        assert_eq!(
328            run.instructions_ref(),
329            Some("Custom instructions for testing")
330        );
331    }
332}