04_advanced_agent/
04_advanced_agent.rs

1//! Advanced Agent Example
2//!
3//! This example demonstrates advanced features including:
4//! - Custom tools with complex logic
5//! - Agent configuration
6//! - Task prioritization
7//! - Response handling with different output types
8//!
9//! Run with: cargo run --example 04_advanced_agent --manifest-path ceylon/Cargo.toml
10
11use ceylon_next::agent::{Agent, AgentConfig};
12use ceylon_next::tasks::{OutputData, TaskRequest};
13use ceylon_next::tools::ToolTrait;
14use serde_json::{Value, json};
15
16// A tool that simulates fetching weather data
17struct WeatherTool;
18
19impl ToolTrait for WeatherTool {
20    fn name(&self) -> String {
21        "get_weather".to_string()
22    }
23
24    fn description(&self) -> String {
25        "Fetches weather information for a given city. \
26         Returns temperature, conditions, and humidity."
27            .to_string()
28    }
29
30    fn input_schema(&self) -> Value {
31        json!({
32            "type": "object",
33            "properties": {
34                "city": {
35                    "type": "string",
36                    "description": "The city name to get weather for"
37                }
38            },
39            "required": ["city"]
40        })
41    }
42
43    fn execute(&self, input: Value) -> Value {
44        let city = input["city"].as_str().unwrap_or("Unknown");
45
46        // Simulate weather data
47        let (temp, conditions) = match city.to_lowercase().as_str() {
48            "london" => (15, "Cloudy with occasional rain"),
49            "paris" => (18, "Partly cloudy"),
50            "tokyo" => (22, "Sunny"),
51            "new york" => (12, "Clear skies"),
52            _ => (20, "Mild conditions"),
53        };
54
55        json!({
56            "city": city,
57            "temperature_celsius": temp,
58            "conditions": conditions,
59            "humidity": 65,
60            "wind_speed_kmh": 12
61        })
62    }
63}
64
65// A tool for text analysis
66struct TextAnalyzerTool;
67
68impl ToolTrait for TextAnalyzerTool {
69    fn name(&self) -> String {
70        "analyze_text".to_string()
71    }
72
73    fn description(&self) -> String {
74        "Analyzes text and provides statistics like word count, character count, and readability."
75            .to_string()
76    }
77
78    fn input_schema(&self) -> Value {
79        json!({
80            "type": "object",
81            "properties": {
82                "text": {
83                    "type": "string",
84                    "description": "The text to analyze"
85                }
86            },
87            "required": ["text"]
88        })
89    }
90
91    fn execute(&self, input: Value) -> Value {
92        let text = input["text"].as_str().unwrap_or("");
93
94        let words: Vec<&str> = text.split_whitespace().collect();
95        let sentences = text.split('.').filter(|s| !s.trim().is_empty()).count();
96        let avg_word_length = if !words.is_empty() {
97            words.iter().map(|w| w.len()).sum::<usize>() / words.len()
98        } else {
99            0
100        };
101
102        json!({
103            "text_length": text.len(),
104            "word_count": words.len(),
105            "sentence_count": sentences,
106            "average_word_length": avg_word_length,
107            "readability_score": 75.0 // Simplified score
108        })
109    }
110}
111
112#[tokio::main]
113async fn main() {
114    println!("🤖 Ceylon Agent - Advanced Example\n");
115
116    // Step 1: Create an agent with custom configuration
117    let mut agent = Agent::new("AdvancedAssistant", "ollama::gemma3:latest");
118
119    // Configure with custom settings
120    let config = AgentConfig::new(
121        5,   // Allow more retries for complex tasks
122        120, // Longer timeout
123    );
124    agent.with_config(config);
125
126    // Custom system prompt for the advanced agent
127    agent.with_system_prompt(
128        "You are an advanced AI assistant with access to specialized tools. \
129         You can fetch weather data and analyze text. \
130         Always explain your reasoning and use tools appropriately. \
131         Provide detailed and accurate responses.",
132    );
133
134    // Step 2: Register multiple tools
135    println!("🔧 Registering tools...");
136    agent.add_tool(WeatherTool);
137    agent.add_tool(TextAnalyzerTool);
138    println!("✓ Tools registered: get_weather, analyze_text\n");
139
140    // Step 3: Create and run multiple tasks with different priorities
141    let tasks_data = vec![
142        (
143            "What's the weather in Paris and London? Compare them.",
144            "Weather Comparison",
145            "Compare weather in two cities",
146            9, // High priority
147        ),
148        (
149            "Analyze this text for readability: 'The quick brown fox jumps over the lazy dog. \
150             This sentence demonstrates all letters of the English alphabet.'",
151            "Text Analysis",
152            "Analyze readability",
153            5, // Medium priority
154        ),
155    ];
156
157    for (prompt, name, description, priority) in tasks_data {
158        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
159        println!("📋 Task: {}", name);
160        println!("⭐ Priority: {}/10", priority);
161        println!("📝 Description: {}", description);
162        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
163
164        let mut task = TaskRequest::new(prompt);
165        task.with_name(name)
166            .with_description(description)
167            .with_priority(priority);
168
169        // Run the agent
170        println!("⏳ Running agent...\n");
171        let response = agent.run(task).await;
172
173        // Handle response
174        match response.result() {
175            OutputData::Text(answer) => {
176                println!("✅ Task completed\n");
177            }
178            _ => {
179                println!("⚠️ Unexpected response type\n");
180            }
181        }
182    }
183
184    // Step 4: Demonstrate memory capabilities
185    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
186    println!("📚 Agent Status Summary:");
187    println!("• System Prompt: Custom advanced prompt");
188    println!("• Tools Available: 2 (weather, text analyzer)");
189    println!("• Memory Enabled: Yes");
190    println!("• Max Retries: 5");
191    println!("• Timeout: 120 seconds");
192    println!("• Tasks Completed: 2\n");
193
194    println!("✅ Advanced example completed successfully!");
195}