java_analysis/
java_analysis.rs

1use env_logger;
2use kowalski_code_agent::agent::CodeAgent;
3use kowalski_core::{
4    agent::Agent,
5    config::Config,
6    role::{Audience, Preset, Role},
7};
8use std::io::{self, Write};
9
10#[tokio::main]
11async fn main() -> Result<(), Box<dyn std::error::Error>> {
12    // Initialize logging
13    env_logger::init();
14
15    // Load configuration
16    let config = Config::default();
17    let mut code_agent = CodeAgent::new(config).await?;
18
19    // Start a conversation
20    println!("ā˜• Starting Java Code Analysis...");
21    let conversation_id = code_agent.start_conversation("llama3.2");
22    println!("Code Agent Conversation ID: {}", conversation_id);
23
24    // Set up the role for code analysis
25    let role = Role::new(
26        "Java Code Analysis Assistant",
27        "You are an expert at analyzing Java code, providing insights on code quality, best practices, and potential improvements.",
28    )
29    .with_audience(Audience::new(
30        "Java Developer",
31        "You are speaking to a Java developer who needs detailed code analysis.",
32    ))
33    .with_preset(Preset::new(
34        "Analysis",
35        "Provide comprehensive analysis with specific recommendations for improvement.",
36    ));
37
38    // Sample Java code for analysis
39    let java_code = r#"
40import java.util.*;
41
42public class Calculator {
43    private int result;
44    
45    public Calculator() {
46        this.result = 0;
47    }
48    
49    public int add(int a, int b) {
50        result = a + b;
51        return result;
52    }
53    
54    public int subtract(int a, int b) {
55        result = a - b;
56        return result;
57    }
58    
59    public int multiply(int a, int b) {
60        result = a * b;
61        return result;
62    }
63    
64    public double divide(int a, int b) {
65        if (b == 0) {
66            System.out.println("Error: Division by zero");
67            return 0;
68        }
69        result = a / b;
70        return (double) result;
71    }
72    
73    public static void main(String[] args) {
74        Calculator calc = new Calculator();
75        System.out.println("Addition: " + calc.add(10, 5));
76        System.out.println("Subtraction: " + calc.subtract(10, 5));
77        System.out.println("Multiplication: " + calc.multiply(10, 5));
78        System.out.println("Division: " + calc.divide(10, 5));
79    }
80}
81"#;
82
83    println!("\nšŸ“ Java Code to Analyze:");
84    println!("{}", java_code);
85
86    // Analyze the Java code
87    let analysis_result = code_agent.analyze_java(java_code).await?;
88
89    println!("\nšŸ“Š Java Analysis Results:");
90    println!("Language: {}", analysis_result.language);
91    println!(
92        "Metrics: {}",
93        serde_json::to_string_pretty(&analysis_result.metrics)?
94    );
95    println!("Suggestions: {:?}", analysis_result.suggestions);
96    println!("Issues: {:?}", analysis_result.issues);
97
98    // Ask the agent to analyze the code
99    let analysis_prompt = format!(
100        "Please analyze this Java code and provide insights:\n\n{}\n\nAnalysis results:\nMetrics: {}\nSuggestions: {:?}\nIssues: {:?}",
101        java_code,
102        serde_json::to_string_pretty(&analysis_result.metrics)?,
103        analysis_result.suggestions,
104        analysis_result.issues
105    );
106
107    let mut response = code_agent
108        .chat_with_history(&conversation_id, &analysis_prompt, Some(role))
109        .await?;
110
111    println!("\nšŸ¤– AI Analysis:");
112
113    // Process the streaming response
114    let mut buffer = String::new();
115    while let Some(chunk) = response.chunk().await? {
116        match code_agent
117            .process_stream_response(&conversation_id, &chunk)
118            .await
119        {
120            Ok(Some(message)) => {
121                // Print the content if it exists
122                if !message.content.is_empty() {
123                    print!("{}", message.content);
124                    io::stdout().flush()?;
125                    buffer.push_str(&message.content);
126                }
127
128                // Handle tool calls if they exist
129                if let Some(tool_calls) = &message.tool_calls {
130                    for tool_call in tool_calls {
131                        print!("\n[Tool Call] {}(", tool_call.function.name);
132                        if let Some(obj) = tool_call.function.arguments.as_object() {
133                            for (key, value) in obj {
134                                print!("{}: {}, ", key, value);
135                            }
136                        }
137                        println!(")");
138                        io::stdout().flush()?;
139                    }
140                }
141            }
142            Ok(None) => {
143                code_agent
144                    .add_message(&conversation_id, "assistant", &buffer)
145                    .await;
146                println!("\nāœ… Analysis complete!\n");
147                break;
148            }
149            Err(e) => {
150                eprintln!("\nāŒ Error processing stream: {}", e);
151                break;
152            }
153        }
154    }
155
156    // Ask a follow-up question about specific improvements
157    let follow_up = "What specific improvements would you recommend for this Java code?";
158    let mut follow_up_response = code_agent
159        .chat_with_history(&conversation_id, follow_up, None)
160        .await?;
161
162    println!("\nšŸ” Follow-up Analysis:");
163    let mut buffer = String::new();
164    while let Some(chunk) = follow_up_response.chunk().await? {
165        match code_agent
166            .process_stream_response(&conversation_id, &chunk)
167            .await
168        {
169            Ok(Some(message)) => {
170                // Print the content if it exists
171                if !message.content.is_empty() {
172                    print!("{}", message.content);
173                    io::stdout().flush()?;
174                    buffer.push_str(&message.content);
175                }
176
177                // Handle tool calls if they exist
178                if let Some(tool_calls) = &message.tool_calls {
179                    for tool_call in tool_calls {
180                        print!("\n[Tool Call] {}(", tool_call.function.name);
181                        if let Some(obj) = tool_call.function.arguments.as_object() {
182                            for (key, value) in obj {
183                                print!("{}: {}, ", key, value);
184                            }
185                        }
186                        println!(")");
187                        io::stdout().flush()?;
188                    }
189                }
190            }
191            Ok(None) => {
192                code_agent
193                    .add_message(&conversation_id, "assistant", &buffer)
194                    .await;
195                println!("\n");
196                break;
197            }
198            Err(e) => {
199                eprintln!("\nāŒ Error processing stream: {}", e);
200                break;
201            }
202        }
203    }
204
205    Ok(())
206}