TaskRequest

Struct TaskRequest 

Source
pub struct TaskRequest { /* private fields */ }
Expand description

A request for an agent to perform a task.

TaskRequest encapsulates all the information needed for an agent to process a user request, including optional metadata like name, description, and priority.

§Examples

use ceylon_next::tasks::TaskRequest;

// Simple task
let task = TaskRequest::new("What is 2 + 2?");

// Task with metadata
let mut task = TaskRequest::new("Analyze this data");
task.with_name("Data Analysis")
    .with_description("Perform statistical analysis on user data")
    .with_priority(8);

Implementations§

Source§

impl TaskRequest

Source

pub fn new(input_data: &str) -> Self

Creates a new task request with the given input.

§Arguments
  • input_data - The user’s request or question
§Examples
use ceylon_next::tasks::TaskRequest;

let task = TaskRequest::new("Explain quantum computing");
Examples found in repository?
examples/02_with_tools.rs (lines 156-158)
137async fn main() {
138    println!("🤖 Ceylon Agent - Tools Example\n");
139
140    // Step 1: Create an agent
141    let mut agent = Agent::new("MathAssistant", "ollama::gemma3:latest");
142
143    agent.with_system_prompt(
144        "You are a helpful math and text assistant. \
145         Use the available tools to help the user. \
146         Be clear about what tools you're using and why."
147    );
148
149    // Step 2: Register custom tools with the agent
150    println!("🔧 Registering tools...");
151    agent.add_tool(CalculatorTool);
152    agent.add_tool(StringToolTool);
153    println!("✓ Tools registered\n");
154
155    // Step 3: Create a task that requires tool usage
156    let mut task = TaskRequest::new(
157        "Please calculate 25 + 15 + 10, and then tell me the uppercase version of the word 'hello'"
158    );
159    task.with_name("Complex Task")
160        .with_description("A task requiring multiple tools")
161        .with_priority(8);
162
163    // Step 4: Run the agent
164    println!("📋 Task: {}\n", task.id());
165    let response = agent.run(task).await;
166
167    // Step 5: Display the result
168    match response.result() {
169        OutputData::Text(answer) => {
170            println!("📝 Agent Response:\n{}\n", answer);
171        }
172        _ => {
173            println!("❌ Unexpected response type");
174        }
175    }
176
177    println!("✅ Example completed successfully!");
178}
More examples
Hide additional examples
examples/01_basic_agent.rs (line 33)
12async fn main() {
13    println!("🤖 Ceylon Agent - Basic Example\n");
14
15    // Step 1: Create a new agent with a name and model
16    // The model should be one supported by the LLM library (openai, anthropic, ollama, etc.)
17    let mut agent = Agent::new("Assistant", "ollama::gemma3:latest");
18
19    // Step 2: (Optional) Configure the agent with custom settings
20    let config = AgentConfig::new(
21        3,   // max_retries
22        60,  // timeout in seconds
23    );
24    agent.with_config(config);
25
26    // Step 3: (Optional) Customize the system prompt
27    agent.with_system_prompt(
28        "You are a helpful assistant that answers questions accurately and concisely. \
29         Always provide well-structured responses."
30    );
31
32    // Step 4: Create a task request
33    let mut task = TaskRequest::new("What is the capital of France?");
34    task.with_name("Geography Question")
35        .with_description("A simple geography question")
36        .with_priority(5);
37
38    // Step 5: Run the agent with the task
39    println!("📋 Task: {}\n", "What is the capital of France?");
40    let response = agent.run(task).await;
41
42    // Step 6: Handle the response
43    match response.result() {
44        OutputData::Text(answer) => {
45            println!("📝 Agent Response:\n{}\n", answer);
46        }
47        _ => {
48            println!("❌ Unexpected response type");
49        }
50    }
51
52    println!("✅ Example completed successfully!");
53}
examples/08_llm_providers.rs (line 131)
125async fn basic_provider_usage() -> Result<(), Box<dyn std::error::Error>> {
126    println!("\n✨ Using different providers with simple syntax:\n");
127
128    // OpenAI
129    println!("📘 OpenAI GPT-4:");
130    let mut openai_agent = Agent::new("OpenAI Assistant", "openai::gpt-4");
131    let task1 = TaskRequest::new("What is 2 + 2? Answer briefly.");
132    let response = openai_agent.run(task1).await;
133    println!("   Response: {:?}\n", response.result());
134
135    // Anthropic Claude
136    println!("📗 Anthropic Claude:");
137    let mut anthropic_agent = Agent::new("Claude Assistant", "anthropic::claude-3-sonnet-20240229");
138    let task2 = TaskRequest::new("What is 2 + 2? Answer briefly.");
139    let response = anthropic_agent.run(task2).await;
140    println!("   Response: {:?}\n", response.result());
141
142    // Ollama (local)
143    println!("📙 Ollama (Local):");
144    let mut ollama_agent = Agent::new("Ollama Assistant", "ollama::llama3.2");
145    let task3 = TaskRequest::new("What is 2 + 2? Answer briefly.");
146    let response = ollama_agent.run(task3).await;
147    println!("   Response: {:?}\n", response.result());
148
149    // Google Gemini
150    println!("📕 Google Gemini:");
151    let mut gemini_agent = Agent::new("Gemini Assistant", "google::gemini-pro");
152    let task4 = TaskRequest::new("What is 2 + 2? Answer briefly.");
153    let response = gemini_agent.run(task4).await;
154    println!("   Response: {:?}\n", response.result());
155
156    // Groq
157    println!("📔 Groq:");
158    let mut groq_agent = Agent::new("Groq Assistant", "groq::mixtral-8x7b-32768");
159    let task5 = TaskRequest::new("What is 2 + 2? Answer briefly.");
160    let response = groq_agent.run(task5).await;
161    println!("   Response: {:?}\n", response.result());
162
163    Ok(())
164}
165
166/// Example 2: Advanced configuration with LLMConfig
167async fn advanced_configuration() -> Result<(), Box<dyn std::error::Error>> {
168    println!("\n✨ Using LLMConfig for advanced configuration:\n");
169
170    // Method 1: Using Agent::new_with_config() (Recommended for explicit API keys)
171    println!("📘 Using Agent::new_with_config() with explicit API key:");
172    if let Ok(api_key) = std::env::var("OPENAI_API_KEY") {
173        let config = LLMConfig::new("openai::gpt-4")
174            .with_api_key(api_key)
175            .with_temperature(0.7)
176            .with_max_tokens(150)
177            .with_top_p(0.9);
178
179        if let Ok(mut agent) = Agent::new_with_config("Configured Assistant", config) {
180            let task1 = TaskRequest::new("Explain quantum computing in one sentence.");
181            let response = agent.run(task1).await;
182            println!("   Response: {:?}\n", response.result());
183        }
184    } else {
185        println!("   Skipped (OPENAI_API_KEY not set)\n");
186    }
187
188    // Method 2: Using Agent::new() then with_llm_config() (Alternative approach)
189    println!("📗 Using Agent::new() then with_llm_config():");
190    let mut agent = Agent::new("Configured Assistant", "openai::gpt-4");
191
192    let config = LLMConfig::new("openai::gpt-4")
193        .with_temperature(0.8)
194        .with_max_tokens(200);
195
196    if let Ok(_) = agent.with_llm_config(config) {
197        let task2 = TaskRequest::new("What is machine learning in one sentence?");
198        let response = agent.run(task2).await;
199        println!("   Response: {:?}\n", response.result());
200    }
201
202    // Anthropic with reasoning
203    println!("📗 Anthropic with extended thinking:");
204    let mut claude_agent = Agent::new("Thinking Claude", "anthropic::claude-3-opus-20240229");
205
206    let claude_config = LLMConfig::new("anthropic::claude-3-opus-20240229")
207        .with_api_key(std::env::var("ANTHROPIC_API_KEY").unwrap_or_default())
208        .with_temperature(0.5)
209        .with_max_tokens(200)
210        .with_reasoning(true);
211
212    if let Ok(_) = claude_agent.with_llm_config(claude_config) {
213        let task2 = TaskRequest::new("Explain quantum computing in one sentence.");
214        let response = claude_agent.run(task2).await;
215        println!("   Response: {:?}\n", response.result());
216    }
217
218    // Ollama with custom system prompt
219    println!("📙 Ollama with custom system prompt:");
220    let mut ollama_agent = Agent::new("Custom Ollama", "ollama::llama3.2");
221
222    let ollama_config = LLMConfig::new("ollama::llama3.2")
223        .with_system("You are a concise and technical AI assistant.")
224        .with_max_tokens(100)
225        .with_temperature(0.3);
226
227    if let Ok(_) = ollama_agent.with_llm_config(ollama_config) {
228        let task3 = TaskRequest::new("Explain quantum computing in one sentence.");
229        let response = ollama_agent.run(task3).await;
230        println!("   Response: {:?}\n", response.result());
231    }
232
233    Ok(())
234}
235
236/// Example 3: Provider-specific features
237async fn provider_specific_features() -> Result<(), Box<dyn std::error::Error>> {
238    println!("\n✨ Provider-specific features:\n");
239
240    // Azure OpenAI
241    println!("☁️  Azure OpenAI with deployment configuration:");
242    let mut azure_agent = Agent::new("Azure Assistant", "azure::gpt-4");
243
244    let azure_config = LLMConfig::new("azure::gpt-4")
245        .with_api_key(std::env::var("AZURE_OPENAI_API_KEY").unwrap_or_default())
246        .with_deployment_id("your-deployment-id")
247        .with_api_version("2024-02-01")
248        .with_base_url("https://your-resource.openai.azure.com");
249
250    if let Ok(_) = azure_agent.with_llm_config(azure_config) {
251        println!("   ✓ Azure agent configured with deployment settings");
252    }
253
254    // OpenAI with web search
255    println!("\n🌐 OpenAI with web search enabled:");
256    let mut search_agent = Agent::new("Search Assistant", "openai::gpt-4");
257
258    let search_config = LLMConfig::new("openai::gpt-4")
259        .with_api_key(std::env::var("OPENAI_API_KEY").unwrap_or_default())
260        .with_openai_web_search(true);
261
262    if let Ok(_) = search_agent.with_llm_config(search_config) {
263        let task1 = TaskRequest::new("What are the latest developments in AI?");
264        let response = search_agent.run(task1).await;
265        println!("   Response (with web search): {:?}\n", response.result());
266    }
267
268    // DeepSeek
269    println!("🔍 DeepSeek for code-focused tasks:");
270    let mut deepseek_agent = Agent::new("DeepSeek Assistant", "deepseek::deepseek-coder");
271
272    let deepseek_config = LLMConfig::new("deepseek::deepseek-coder")
273        .with_api_key(std::env::var("DEEPSEEK_API_KEY").unwrap_or_default())
274        .with_temperature(0.2);
275
276    if let Ok(_) = deepseek_agent.with_llm_config(deepseek_config) {
277        let code_task = TaskRequest::new("Write a Rust function to calculate fibonacci numbers");
278        let response = deepseek_agent.run(code_task).await;
279        println!("   Response: {:?}\n", response.result());
280    }
281
282    // Mistral
283    println!("🌟 Mistral for European AI:");
284    let mut mistral_agent = Agent::new("Mistral Assistant", "mistral::mistral-large-latest");
285
286    let mistral_config = LLMConfig::new("mistral::mistral-large-latest")
287        .with_api_key(std::env::var("MISTRAL_API_KEY").unwrap_or_default())
288        .with_temperature(0.7)
289        .with_max_tokens(500);
290
291    if let Ok(_) = mistral_agent.with_llm_config(mistral_config) {
292        println!("   ✓ Mistral agent configured");
293    }
294
295    Ok(())
296}
297
298/// Example 4: Compare providers
299async fn compare_providers() -> Result<(), Box<dyn std::error::Error>> {
300    println!("\n✨ Comparing responses across providers:\n");
301
302    let providers = vec![
303        ("OpenAI GPT-4", "openai::gpt-4", std::env::var("OPENAI_API_KEY").ok()),
304        ("Anthropic Claude", "anthropic::claude-3-sonnet-20240229", std::env::var("ANTHROPIC_API_KEY").ok()),
305        ("Ollama Llama", "ollama::llama3.2", None),
306        ("Google Gemini", "google::gemini-pro", std::env::var("GOOGLE_API_KEY").ok()),
307        ("Groq Mixtral", "groq::mixtral-8x7b-32768", std::env::var("GROQ_API_KEY").ok()),
308    ];
309
310    for (name, model, api_key) in providers {
311        println!("🤖 {}:", name);
312
313        let mut agent = Agent::new(name, model);
314
315        // Configure with LLMConfig if API key is available
316        if let Some(key) = api_key {
317            let config = LLMConfig::new(model)
318                .with_api_key(key)
319                .with_temperature(0.7)
320                .with_max_tokens(100);
321
322            if let Ok(_) = agent.with_llm_config(config) {
323                let task = TaskRequest::new("Explain the concept of 'ownership' in Rust in one sentence.");
324                let response = agent.run(task).await;
325                println!("   ✓ {:?}", response.result());
326            }
327        } else {
328            // Try without explicit API key (for Ollama or env vars)
329            let task = TaskRequest::new("Explain the concept of 'ownership' in Rust in one sentence.");
330            let response = agent.run(task).await;
331            println!("   ✓ {:?}", response.result());
332        }
333
334        println!();
335    }
336
337    Ok(())
338}
examples/05_with_goals.rs (line 58)
22async fn example_1_manual_goal() {
23    println!("=== Example 1: Manual Goal Creation ===\n");
24
25    // Create an agent
26    let mut agent = Agent::new("MealPlanner", "ollama::gemma3:latest");
27
28    // Create a goal manually for a complex task
29    let mut goal = Goal::new(
30        "Plan a healthy meal prep for the week".to_string()
31    );
32
33    // Define what success looks like
34    println!("📋 Setting success criteria...");
35    goal.add_criterion("7 breakfast recipes selected".to_string());
36    goal.add_criterion("7 lunch recipes selected".to_string());
37    goal.add_criterion("7 dinner recipes selected".to_string());
38    goal.add_criterion("Shopping list created".to_string());
39    goal.add_criterion("Prep schedule created".to_string());
40
41    // Break down into steps (sub-goals)
42    println!("🎯 Breaking down into sub-goals...\n");
43    goal.add_sub_goal("Ask user about dietary preferences".to_string(), 0);
44    goal.add_sub_goal("Ask about time available for prep".to_string(), 1);
45    goal.add_sub_goal("Suggest breakfast options".to_string(), 2);
46    goal.add_sub_goal("Suggest lunch options".to_string(), 3);
47    goal.add_sub_goal("Suggest dinner options".to_string(), 4);
48    goal.add_sub_goal("Create shopping list".to_string(), 5);
49    goal.add_sub_goal("Create prep schedule".to_string(), 6);
50
51    // Start working on the goal
52    goal.status = GoalStatus::InProgress;
53
54    // Set the goal on the agent
55    agent.set_goal(goal.clone());
56
57    // Create a task aligned with the goal
58    let task = TaskRequest::new("I need help with meal planning");
59
60    // Run the agent
61    println!("⏳ Agent is working on the meal planning task...\n");
62    let _response = agent.run(task).await;
63
64    // Show the goal summary
65    println!("\n📊 Goal Summary:");
66    println!("{}", goal.get_summary());
67
68    println!("\n✅ Example 1 completed!\n");
69}
70
71// ============================================
72// Example 2: Goal Progress Tracking
73// ============================================
74
75async fn example_2_goal_progress_tracking() {
76    println!("\n=== Example 2: Goal Progress Tracking ===\n");
77
78    // Create a goal for a project
79    let mut goal = Goal::new(
80        "Create a project plan for building a mobile app".to_string()
81    );
82
83    // Add success criteria
84    goal.add_criterion("Project requirements documented".to_string());
85    goal.add_criterion("Timeline created with milestones".to_string());
86    goal.add_criterion("Resource allocation plan completed".to_string());
87    goal.add_criterion("Risk assessment performed".to_string());
88
89    // Add sub-goals
90    goal.add_sub_goal("Gather stakeholder requirements".to_string(), 0);
91    goal.add_sub_goal("Define project scope".to_string(), 1);
92    goal.add_sub_goal("Create development timeline".to_string(), 2);
93    goal.add_sub_goal("Allocate resources".to_string(), 3);
94    goal.add_sub_goal("Identify risks and mitigation strategies".to_string(), 4);
95
96    goal.status = GoalStatus::InProgress;
97
98    // Simulate progress through the goal
99    println!("📈 Tracking goal progress...\n");
100
101    // Complete first sub-goal
102    println!("Step 1: Gathering requirements");
103    goal.complete_sub_goal(0, Some("Interviewed 5 stakeholders".to_string()));
104    goal.mark_criterion_met(0, "Requirements documented".to_string());
105    println!("  Progress: {}%\n", goal.get_progress());
106
107    // Complete second sub-goal
108    println!("Step 2: Defining scope");
109    goal.complete_sub_goal(1, Some("Scope document created".to_string()));
110    println!("  Progress: {}%\n", goal.get_progress());
111
112    // Complete third sub-goal
113    println!("Step 3: Creating timeline");
114    goal.complete_sub_goal(2, Some("12-month timeline with milestones".to_string()));
115    goal.mark_criterion_met(1, "Timeline created".to_string());
116    println!("  Progress: {}%\n", goal.get_progress());
117
118    // Complete fourth sub-goal
119    println!("Step 4: Allocating resources");
120    goal.complete_sub_goal(3, Some("Resource allocation table created".to_string()));
121    goal.mark_criterion_met(2, "Resources allocated".to_string());
122    println!("  Progress: {}%\n", goal.get_progress());
123
124    // Complete fifth sub-goal
125    println!("Step 5: Assessing risks");
126    goal.complete_sub_goal(4, Some("Risk register created with 8 identified risks".to_string()));
127    goal.mark_criterion_met(3, "Risks identified".to_string());
128    println!("  Progress: {}%\n", goal.get_progress());
129
130    // Show final status
131    println!("\n📊 Final Goal Status:");
132    println!("{}", goal.get_summary());
133
134    println!("\n✅ Example 2 completed!\n");
135}
136
137// ============================================
138// Example 3: Job Interview Preparation Goal
139// ============================================
140
141async fn example_3_interview_preparation() {
142    println!("\n=== Example 3: Job Interview Preparation Goal ===\n");
143
144    let mut agent = Agent::new("InterviewCoach", "ollama::gemma3:latest");
145
146    // Create a structured goal for interview prep
147    let mut goal = Goal::new(
148        "Prepare for a senior software engineer interview at a tech company".to_string()
149    );
150
151    // Define success criteria
152    println!("🎯 Success criteria:");
153    goal.add_criterion("Technical topics reviewed (algorithms, data structures, system design)".to_string());
154    goal.add_criterion("Behavioral questions prepared with STAR method examples".to_string());
155    goal.add_criterion("Company research completed".to_string());
156    goal.add_criterion("Practice mock interview conducted".to_string());
157    goal.add_criterion("Questions to ask the interviewer prepared".to_string());
158
159    for criterion in &goal.success_criteria {
160        println!("  • {}", criterion.description);
161    }
162
163    // Define steps
164    println!("\n📋 Steps to take:");
165    goal.add_sub_goal("Review core algorithms and data structures".to_string(), 0);
166    goal.add_sub_goal("Study system design patterns".to_string(), 1);
167    goal.add_sub_goal("Prepare STAR method stories from past projects".to_string(), 2);
168    goal.add_sub_goal("Research company background and culture".to_string(), 3);
169    goal.add_sub_goal("Practice mock interview with a friend".to_string(), 4);
170    goal.add_sub_goal("Prepare thoughtful questions about the role".to_string(), 5);
171
172    for sub_goal in &goal.sub_goals {
173        println!("  {}. {}", sub_goal.priority + 1, sub_goal.description);
174    }
175
176    goal.status = GoalStatus::InProgress;
177
178    // Set goal on agent
179    agent.set_goal(goal.clone());
180
181    // Create related task
182    let task = TaskRequest::new("Help me prepare for my senior engineer interview");
183
184    println!("\n⏳ Agent is creating interview preparation plan...\n");
185    let _response = agent.run(task).await;
186
187    println!("\n📊 Goal Summary:");
188    println!("{}", goal.get_summary());
189
190    println!("\n✅ Example 3 completed!\n");
191}
examples/06_nextjs_app_generator.rs (lines 70-74)
38async fn example_1_basic_nextjs_app() {
39    println!("=== Example 1: Generate a Basic Next.js App ===\n");
40
41    // Create an agent that will generate the app
42    let mut agent = Agent::new("NextJsGenerator", "ollama::gemma3:latest");
43
44    // Create a goal for generating a Next.js app
45    let mut goal = Goal::new(
46        "Generate a Next.js web application with essential structure".to_string()
47    );
48
49    // Define success criteria
50    goal.add_criterion("package.json created with dependencies".to_string());
51    goal.add_criterion("next.config.js configuration file generated".to_string());
52    goal.add_criterion("pages directory with index and api route created".to_string());
53    goal.add_criterion("styles directory with global CSS".to_string());
54    goal.add_criterion("README.md with setup instructions".to_string());
55
56    // Define sub-goals (steps to generate the app)
57    goal.add_sub_goal("Analyze Next.js requirements and best practices".to_string(), 0);
58    goal.add_sub_goal("Generate package.json with required dependencies".to_string(), 1);
59    goal.add_sub_goal("Create next.config.js configuration".to_string(), 2);
60    goal.add_sub_goal("Generate pages (index.tsx, _app.tsx, _document.tsx)".to_string(), 3);
61    goal.add_sub_goal("Create API route examples".to_string(), 4);
62    goal.add_sub_goal("Generate styling setup (global.css, utilities)".to_string(), 5);
63    goal.add_sub_goal("Create components directory with example components".to_string(), 6);
64    goal.add_sub_goal("Generate README with setup and usage instructions".to_string(), 7);
65
66    goal.status = GoalStatus::InProgress;
67    agent.set_goal(goal.clone());
68
69    // Create a task to generate a Next.js app
70    let task = TaskRequest::new(
71        "Generate a modern Next.js 14 application with TypeScript, Tailwind CSS, and best practices. \
72         Include package.json, next.config.js, sample pages, API routes, and components. \
73         The app should be production-ready and follow Next.js conventions."
74    );
75
76    println!("📝 Task: Generate a Next.js application\n");
77    println!("🎯 Success Criteria:");
78    for criterion in &goal.success_criteria {
79        println!("  • {}", criterion.description);
80    }
81
82    println!("\n⏳ Agent is generating the Next.js app...\n");
83    let response = agent.run(task).await;
84
85    // Extract and display the output
86    let output = extract_output_text(&response.result());
87    println!("📄 Generated Output:\n");
88    println!("{}\n", output);
89
90    // Show progress
91    println!("📊 Goal Progress: {}%", goal.get_progress());
92    println!("Status: {:?}", goal.status);
93
94    println!("\n✅ Example 1 completed!\n");
95}
96
97// ============================================
98// Example 2: E-Commerce Next.js App
99// ============================================
100
101async fn example_2_ecommerce_app() {
102    println!("\n=== Example 2: Generate E-Commerce Next.js App ===\n");
103
104    let mut agent = Agent::new("EcommerceGenerator", "ollama::gemma3:latest");
105
106    let mut goal = Goal::new(
107        "Generate a complete e-commerce Next.js application".to_string()
108    );
109
110    // Success criteria for e-commerce
111    goal.add_criterion("Product listing page with filtering and sorting".to_string());
112    goal.add_criterion("Product detail pages with dynamic routes".to_string());
113    goal.add_criterion("Shopping cart functionality".to_string());
114    goal.add_criterion("User authentication setup".to_string());
115    goal.add_criterion("Payment integration structure".to_string());
116    goal.add_criterion("Database models and API endpoints".to_string());
117    goal.add_criterion("Admin dashboard layout".to_string());
118
119    // Sub-goals
120    goal.add_sub_goal("Design database schema for products and orders".to_string(), 0);
121    goal.add_sub_goal("Create product API endpoints".to_string(), 1);
122    goal.add_sub_goal("Build product listing and search components".to_string(), 2);
123    goal.add_sub_goal("Implement product detail pages".to_string(), 3);
124    goal.add_sub_goal("Create shopping cart context and management".to_string(), 4);
125    goal.add_sub_goal("Build checkout flow pages".to_string(), 5);
126    goal.add_sub_goal("Integrate payment gateway API".to_string(), 6);
127    goal.add_sub_goal("Create admin dashboard pages".to_string(), 7);
128    goal.add_sub_goal("Add authentication middleware".to_string(), 8);
129
130    goal.status = GoalStatus::InProgress;
131    agent.set_goal(goal.clone());
132
133    let task = TaskRequest::new(
134        "Generate a complete e-commerce Next.js application with: \
135         1. Product management system (listing, search, filters)\n\
136         2. Shopping cart with add/remove/update functionality\n\
137         3. User authentication and profile pages\n\
138         4. Payment integration endpoints\n\
139         5. Order history and tracking\n\
140         6. Admin dashboard for managing products and orders\n\
141         7. Database models for PostgreSQL or MongoDB\n\
142         8. RESTful API endpoints\n\
143         Use TypeScript, Tailwind CSS, and modern React patterns."
144    );
145
146    println!("📝 Task: Generate E-Commerce Next.js Application\n");
147    println!("🎯 Features to Generate:");
148    for criterion in &goal.success_criteria {
149        println!("  ✓ {}", criterion.description);
150    }
151
152    println!("\n⏳ Agent is generating e-commerce app...\n");
153    let response = agent.run(task).await;
154
155    let output = extract_output_text(&response.result());
156    println!("📄 Generated Output:\n");
157    println!("{}\n", output);
158
159    println!("📊 Goal Progress: {}%", goal.get_progress());
160    println!("\n✅ Example 2 completed!\n");
161}
162
163// ============================================
164// Example 3: SaaS Dashboard App
165// ============================================
166
167async fn example_3_saas_dashboard() {
168    println!("\n=== Example 3: Generate SaaS Dashboard Next.js App ===\n");
169
170    let mut agent = Agent::new("SaasDashboardGenerator", "ollama::gemma3:latest");
171
172    let mut goal = Goal::new(
173        "Generate a SaaS dashboard application with user management".to_string()
174    );
175
176    goal.add_criterion("User authentication and authorization".to_string());
177    goal.add_criterion("Multi-tenant database structure".to_string());
178    goal.add_criterion("Dashboard with analytics and metrics".to_string());
179    goal.add_criterion("User and team management pages".to_string());
180    goal.add_criterion("Settings and preferences pages".to_string());
181    goal.add_criterion("Billing and subscription management".to_string());
182    goal.add_criterion("API for data collection and reporting".to_string());
183
184    goal.add_sub_goal("Design multi-tenant database schema".to_string(), 0);
185    goal.add_sub_goal("Implement OAuth authentication".to_string(), 1);
186    goal.add_sub_goal("Create dashboard with charts and metrics".to_string(), 2);
187    goal.add_sub_goal("Build team and user management interfaces".to_string(), 3);
188    goal.add_sub_goal("Create settings pages for users and organization".to_string(), 4);
189    goal.add_sub_goal("Implement billing API integration".to_string(), 5);
190    goal.add_sub_goal("Create analytics and reporting system".to_string(), 6);
191    goal.add_sub_goal("Add email notification templates".to_string(), 7);
192
193    goal.status = GoalStatus::InProgress;
194    agent.set_goal(goal.clone());
195
196    let task = TaskRequest::new(
197        "Generate a complete SaaS dashboard Next.js application with:\n\
198         1. Multi-tenant authentication (OAuth + JWT)\n\
199         2. Organization and team management\n\
200         3. Comprehensive dashboard with charts and analytics\n\
201         4. User permission and role management\n\
202         5. Billing integration with Stripe\n\
203         6. Settings pages for users and teams\n\
204         7. Email notifications system\n\
205         8. API logging and activity tracking\n\
206         9. Dark mode support\n\
207         10. Mobile responsive design\n\
208         Include TypeScript, Tailwind CSS, Recharts for visualizations, \
209         and PostgreSQL database models."
210    );
211
212    println!("📝 Task: Generate SaaS Dashboard Application\n");
213    println!("🎯 Dashboard Features:");
214    for criterion in &goal.success_criteria {
215        println!("  ✓ {}", criterion.description);
216    }
217
218    println!("\n⏳ Agent is generating SaaS dashboard...\n");
219    let response = agent.run(task).await;
220
221    let output = extract_output_text(&response.result());
222    println!("📄 Generated Output:\n");
223    println!("{}\n", output);
224
225    println!("📊 Goal Progress: {}%", goal.get_progress());
226    println!("\n✅ Example 3 completed!\n");
227}
228
229// ============================================
230// Example 4: Blog Platform with CMS
231// ============================================
232
233async fn example_4_blog_platform() {
234    println!("\n=== Example 4: Generate Blog Platform with CMS ===\n");
235
236    let mut agent = Agent::new("BlogCMSGenerator", "ollama::gemma3:latest");
237
238    let mut goal = Goal::new(
239        "Generate a comprehensive blog platform with CMS".to_string()
240    );
241
242    goal.add_criterion("Blog post management system".to_string());
243    goal.add_criterion("Rich text editor with markdown support".to_string());
244    goal.add_criterion("Category and tag system".to_string());
245    goal.add_criterion("Search and filtering functionality".to_string());
246    goal.add_criterion("Comments system with moderation".to_string());
247    goal.add_criterion("SEO optimization (meta tags, sitemap)".to_string());
248    goal.add_criterion("Author management and permissions".to_string());
249    goal.add_criterion("Analytics and engagement tracking".to_string());
250
251    goal.add_sub_goal("Design blog database schema".to_string(), 0);
252    goal.add_sub_goal("Create CMS backend API".to_string(), 1);
253    goal.add_sub_goal("Build post editor with markdown".to_string(), 2);
254    goal.add_sub_goal("Create blog listing and search pages".to_string(), 3);
255    goal.add_sub_goal("Build individual post pages with SEO".to_string(), 4);
256    goal.add_sub_goal("Implement comments system".to_string(), 5);
257    goal.add_sub_goal("Create author profiles and bio".to_string(), 6);
258    goal.add_sub_goal("Build admin dashboard for content management".to_string(), 7);
259    goal.add_sub_goal("Add analytics tracking and reporting".to_string(), 8);
260
261    goal.status = GoalStatus::InProgress;
262    agent.set_goal(goal.clone());
263
264    let task = TaskRequest::new(
265        "Generate a full-featured blog platform with CMS:\n\
266         1. Post creation and editing with rich text editor\n\
267         2. Markdown support with preview\n\
268         3. Category and tag system\n\
269         4. Advanced search with filters\n\
270         5. Comments system with nested replies\n\
271         6. Author profiles with biography\n\
272         7. SEO optimization (sitemaps, meta tags, structured data)\n\
273         8. Social sharing integration\n\
274         9. Email newsletter subscription\n\
275         10. Analytics dashboard for authors\n\
276         11. Reading time estimates\n\
277         12. Related posts suggestions\n\
278         Include TypeScript, Tailwind CSS, next-mdx-remote for markdown, \
279         and MongoDB/PostgreSQL models."
280    );
281
282    println!("📝 Task: Generate Blog Platform with CMS\n");
283    println!("🎯 Blog Features:");
284    for criterion in &goal.success_criteria {
285        println!("  ✓ {}", criterion.description);
286    }
287
288    println!("\n⏳ Agent is generating blog platform...\n");
289    let response = agent.run(task).await;
290
291    let output = extract_output_text(&response.result());
292    println!("📄 Generated Output:\n");
293    println!("{}\n", output);
294
295    println!("📊 Goal Progress: {}%", goal.get_progress());
296    println!("\n✅ Example 4 completed!\n");
297}
298
299// ============================================
300// Example 5: Extracting and Processing Output
301// ============================================
302
303async fn example_5_output_extraction() {
304    println!("\n=== Example 5: Output Extraction and Processing ===\n");
305
306    let mut agent = Agent::new("OutputProcessor", "ollama::gemma3:latest");
307
308    // Create a simple task to generate specific file outputs
309    let task = TaskRequest::new(
310        "Generate ONLY the following files in proper format:\n\
311         1. A complete package.json file for a Next.js project\n\
312         2. A next.config.js configuration\n\
313         3. A TypeScript types file for common types\n\
314         Format each file with proper headers like:\n\
315         === FILE: package.json ===\n\
316         [file content]\n\
317         === FILE: next.config.js ===\n\
318         [file content]"
319    );
320
321    println!("📝 Task: Generate Specific Configuration Files\n");
322    println!("⏳ Processing...\n");
323
324    let response = agent.run(task).await;
325    let output = extract_output_text(&response.result());
326
327    // Parse output by file
328    let files: HashMap<String, String> = parse_output_by_file(&output);
329
330    println!("📦 Generated Files:\n");
331    for (filename, content) in &files {
332        println!("📄 File: {}", filename);
333        println!("   Lines: {}", content.lines().count());
334        println!("   Size: {} bytes\n", content.len());
335    }
336
337    println!("✅ Example 5 completed!\n");
338}
examples/04_advanced_agent.rs (line 164)
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}
Source

pub fn with_name(&mut self, name: &str) -> &mut Self

Sets the name of the task.

§Arguments
  • name - A short name for the task
Examples found in repository?
examples/02_with_tools.rs (line 159)
137async fn main() {
138    println!("🤖 Ceylon Agent - Tools Example\n");
139
140    // Step 1: Create an agent
141    let mut agent = Agent::new("MathAssistant", "ollama::gemma3:latest");
142
143    agent.with_system_prompt(
144        "You are a helpful math and text assistant. \
145         Use the available tools to help the user. \
146         Be clear about what tools you're using and why."
147    );
148
149    // Step 2: Register custom tools with the agent
150    println!("🔧 Registering tools...");
151    agent.add_tool(CalculatorTool);
152    agent.add_tool(StringToolTool);
153    println!("✓ Tools registered\n");
154
155    // Step 3: Create a task that requires tool usage
156    let mut task = TaskRequest::new(
157        "Please calculate 25 + 15 + 10, and then tell me the uppercase version of the word 'hello'"
158    );
159    task.with_name("Complex Task")
160        .with_description("A task requiring multiple tools")
161        .with_priority(8);
162
163    // Step 4: Run the agent
164    println!("📋 Task: {}\n", task.id());
165    let response = agent.run(task).await;
166
167    // Step 5: Display the result
168    match response.result() {
169        OutputData::Text(answer) => {
170            println!("📝 Agent Response:\n{}\n", answer);
171        }
172        _ => {
173            println!("❌ Unexpected response type");
174        }
175    }
176
177    println!("✅ Example completed successfully!");
178}
More examples
Hide additional examples
examples/01_basic_agent.rs (line 34)
12async fn main() {
13    println!("🤖 Ceylon Agent - Basic Example\n");
14
15    // Step 1: Create a new agent with a name and model
16    // The model should be one supported by the LLM library (openai, anthropic, ollama, etc.)
17    let mut agent = Agent::new("Assistant", "ollama::gemma3:latest");
18
19    // Step 2: (Optional) Configure the agent with custom settings
20    let config = AgentConfig::new(
21        3,   // max_retries
22        60,  // timeout in seconds
23    );
24    agent.with_config(config);
25
26    // Step 3: (Optional) Customize the system prompt
27    agent.with_system_prompt(
28        "You are a helpful assistant that answers questions accurately and concisely. \
29         Always provide well-structured responses."
30    );
31
32    // Step 4: Create a task request
33    let mut task = TaskRequest::new("What is the capital of France?");
34    task.with_name("Geography Question")
35        .with_description("A simple geography question")
36        .with_priority(5);
37
38    // Step 5: Run the agent with the task
39    println!("📋 Task: {}\n", "What is the capital of France?");
40    let response = agent.run(task).await;
41
42    // Step 6: Handle the response
43    match response.result() {
44        OutputData::Text(answer) => {
45            println!("📝 Agent Response:\n{}\n", answer);
46        }
47        _ => {
48            println!("❌ Unexpected response type");
49        }
50    }
51
52    println!("✅ Example completed successfully!");
53}
examples/04_advanced_agent.rs (line 165)
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}
examples/03_with_memory.rs (line 38)
12async fn main() {
13    println!("🤖 Ceylon Agent - Memory Example\n");
14
15    // Step 1: Create an agent
16    let mut agent = Agent::new("MemoryAssistant", "ollama::gemma3:latest");
17
18    agent.with_system_prompt(
19        "You are a helpful assistant with persistent memory. \
20         Remember important details from our previous conversations \
21         and refer back to them when relevant."
22    );
23
24    // Step 2: Run multiple tasks to build conversation history
25    let tasks_and_prompts = vec![
26        ("Tell me about your favorite color", "Learn about preferences"),
27        ("What color did I mention?", "Test memory recall"),
28        ("Can you suggest a hobby based on what you know about me?", "Use memory for suggestions"),
29    ];
30
31    for (prompt, description) in tasks_and_prompts {
32        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
33        println!("📋 Task: {}", prompt);
34        println!("📝 Description: {}", description);
35        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
36
37        let mut task = TaskRequest::new(prompt);
38        task.with_name(description)
39            .with_priority(5);
40
41        // Run the agent
42        let response = agent.run(task).await;
43
44        // Display response
45        match response.result() {
46            OutputData::Text(answer) => {
47                println!("✓ Response received\n");
48            }
49            _ => {
50                println!("❌ Unexpected response type\n");
51            }
52        }
53    }
54
55    // Step 3: Retrieve conversation history
56    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
57    println!("📚 Retrieving conversation history...\n");
58
59    let history = agent.get_history(Some(5)).await;
60    println!("Found {} recent conversations\n", history.len());
61
62    if !history.is_empty() {
63        println!("📖 Conversation Summary:");
64        for (i, entry) in history.iter().enumerate() {
65            println!("\n--- Conversation {} ---", i + 1);
66            println!("Messages: {}", entry.messages.len());
67
68            // Show first and last message
69            if let Some(first) = entry.messages.first() {
70                println!("First: {} - {}", first.role,
71                    if first.content.len() > 50 {
72                        format!("{}...", &first.content[..50])
73                    } else {
74                        first.content.clone()
75                    });
76            }
77
78            if let Some(last) = entry.messages.last() {
79                println!("Last: {} - {}", last.role,
80                    if last.content.len() > 50 {
81                        format!("{}...", &last.content[..50])
82                    } else {
83                        last.content.clone()
84                    });
85            }
86        }
87    }
88
89    // Step 4: Search memory
90    println!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
91    println!("🔍 Searching memory for 'color'...\n");
92
93    let search_results = agent.search_memory("color").await;
94    println!("Found {} conversations mentioning 'color'\n", search_results.len());
95
96    // Step 5: Clear memory (optional)
97    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
98    println!("🧹 Memory management options:");
99    println!("- Use agent.get_history() to retrieve conversation history");
100    println!("- Use agent.search_memory(query) to search conversations");
101    println!("- Use agent.clear_memory() to clear all agent memory\n");
102
103    println!("✅ Example completed successfully!");
104}
examples/10_file_saving.rs (line 130)
83async fn main() {
84    println!("🤖 Ceylon Agent - File Saving Example\n");
85
86    // Define the output directory
87    let output_dir = "test/web_project_output";
88
89    // Create the output directory if it doesn't exist
90    if let Err(e) = fs::create_dir_all(output_dir) {
91        eprintln!("❌ Failed to create output directory: {}", e);
92        return;
93    }
94    println!("📁 Output directory: {}/\n", output_dir);
95
96    // Step 1: Create an agent
97    let mut agent = Agent::new("ContentGenerator", "ollama::gemma3:latest");
98
99    agent.with_system_prompt(
100        &format!(
101            "You are a helpful assistant that can generate content and save it to files. \
102             When asked to create content, generate it and use the file_saver tool to save it. \
103             \
104             IMPORTANT: All files MUST be saved inside the '{}' directory. \
105             For example, to save 'server.js', use '{}/server.js' as the filename. \
106             For files in subdirectories, use '{}/src/app.js' format. \
107             \
108             Be clear about what you're creating and where you're saving it.",
109            output_dir, output_dir, output_dir
110        )
111    );
112
113    // Step 2: Register the file saver tool
114    println!("🔧 Registering file saver tool...");
115    agent.add_tool(FileSaverTool);
116    println!("✓ Tool registered\n");
117
118    // Step 3: Create a task that generates content and saves it
119    let mut task = TaskRequest::new(
120        &format!(
121            "Create a simple web project with a file upload API. Save all files in the '{}' directory:\
122             \n1. server.js - A Node.js Express server with POST /upload endpoint\
123             \n2. package.json - Package configuration with dependencies\
124             \n3. test.http - HTTP test file to test the upload endpoint\
125             \n4. README.md - Instructions on how to install and run the server\
126             \n\nMake sure ALL files are saved in the '{}' directory!",
127            output_dir, output_dir
128        )
129    );
130    task.with_name("Generate and Save Web Project")
131        .with_description("Generate a complete web project with file upload API")
132        .with_priority(7);
133
134    // Step 4: Run the agent
135    println!("📋 Task: {}\n", task.id());
136    println!("🔄 Running agent...\n");
137
138    let response = agent.run(task).await;
139
140    // Step 5: Display the result
141    match response.result() {
142        OutputData::Text(answer) => {
143            println!("\n📝 Agent Response:\n{}\n", answer);
144        }
145        _ => {
146            println!("❌ Unexpected response type");
147        }
148    }
149
150    // Step 6: Verify files were created
151    println!("🔍 Checking created files in '{}/'\n", output_dir);
152
153    let expected_files = vec![
154        "server.js",
155        "package.json",
156        "test.http",
157        "README.md"
158    ];
159
160    let mut created_count = 0;
161
162    for file in &expected_files {
163        let file_path = format!("{}/{}", output_dir, file);
164        if Path::new(&file_path).exists() {
165            created_count += 1;
166            println!("✓ {} created successfully", file);
167
168            if let Ok(content) = fs::read_to_string(&file_path) {
169                let preview: String = content.chars().take(100).collect();
170                println!("  Preview: {}", preview.replace('\n', " "));
171            }
172        } else {
173            println!("⚠ {} not found", file);
174        }
175    }
176
177    println!("\n📊 Summary: {}/{} expected files created", created_count, expected_files.len());
178
179    // Show directory structure
180    println!("\n📂 Directory structure:");
181    if let Ok(entries) = fs::read_dir(output_dir) {
182        for entry in entries.flatten() {
183            let path = entry.path();
184            if path.is_file() {
185                if let Some(filename) = path.file_name() {
186                    if let Ok(metadata) = entry.metadata() {
187                        println!("  - {} ({} bytes)",
188                                 filename.to_string_lossy(),
189                                 metadata.len());
190                    }
191                }
192            }
193        }
194    }
195
196    println!("\n✅ Example completed successfully!");
197    println!("📁 All files are in: {}/", output_dir);
198}
Source

pub fn with_description(&mut self, description: &str) -> &mut Self

Sets the description of the task.

§Arguments
  • description - A detailed description of what the task should accomplish
Examples found in repository?
examples/02_with_tools.rs (line 160)
137async fn main() {
138    println!("🤖 Ceylon Agent - Tools Example\n");
139
140    // Step 1: Create an agent
141    let mut agent = Agent::new("MathAssistant", "ollama::gemma3:latest");
142
143    agent.with_system_prompt(
144        "You are a helpful math and text assistant. \
145         Use the available tools to help the user. \
146         Be clear about what tools you're using and why."
147    );
148
149    // Step 2: Register custom tools with the agent
150    println!("🔧 Registering tools...");
151    agent.add_tool(CalculatorTool);
152    agent.add_tool(StringToolTool);
153    println!("✓ Tools registered\n");
154
155    // Step 3: Create a task that requires tool usage
156    let mut task = TaskRequest::new(
157        "Please calculate 25 + 15 + 10, and then tell me the uppercase version of the word 'hello'"
158    );
159    task.with_name("Complex Task")
160        .with_description("A task requiring multiple tools")
161        .with_priority(8);
162
163    // Step 4: Run the agent
164    println!("📋 Task: {}\n", task.id());
165    let response = agent.run(task).await;
166
167    // Step 5: Display the result
168    match response.result() {
169        OutputData::Text(answer) => {
170            println!("📝 Agent Response:\n{}\n", answer);
171        }
172        _ => {
173            println!("❌ Unexpected response type");
174        }
175    }
176
177    println!("✅ Example completed successfully!");
178}
More examples
Hide additional examples
examples/01_basic_agent.rs (line 35)
12async fn main() {
13    println!("🤖 Ceylon Agent - Basic Example\n");
14
15    // Step 1: Create a new agent with a name and model
16    // The model should be one supported by the LLM library (openai, anthropic, ollama, etc.)
17    let mut agent = Agent::new("Assistant", "ollama::gemma3:latest");
18
19    // Step 2: (Optional) Configure the agent with custom settings
20    let config = AgentConfig::new(
21        3,   // max_retries
22        60,  // timeout in seconds
23    );
24    agent.with_config(config);
25
26    // Step 3: (Optional) Customize the system prompt
27    agent.with_system_prompt(
28        "You are a helpful assistant that answers questions accurately and concisely. \
29         Always provide well-structured responses."
30    );
31
32    // Step 4: Create a task request
33    let mut task = TaskRequest::new("What is the capital of France?");
34    task.with_name("Geography Question")
35        .with_description("A simple geography question")
36        .with_priority(5);
37
38    // Step 5: Run the agent with the task
39    println!("📋 Task: {}\n", "What is the capital of France?");
40    let response = agent.run(task).await;
41
42    // Step 6: Handle the response
43    match response.result() {
44        OutputData::Text(answer) => {
45            println!("📝 Agent Response:\n{}\n", answer);
46        }
47        _ => {
48            println!("❌ Unexpected response type");
49        }
50    }
51
52    println!("✅ Example completed successfully!");
53}
examples/04_advanced_agent.rs (line 166)
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}
examples/10_file_saving.rs (line 131)
83async fn main() {
84    println!("🤖 Ceylon Agent - File Saving Example\n");
85
86    // Define the output directory
87    let output_dir = "test/web_project_output";
88
89    // Create the output directory if it doesn't exist
90    if let Err(e) = fs::create_dir_all(output_dir) {
91        eprintln!("❌ Failed to create output directory: {}", e);
92        return;
93    }
94    println!("📁 Output directory: {}/\n", output_dir);
95
96    // Step 1: Create an agent
97    let mut agent = Agent::new("ContentGenerator", "ollama::gemma3:latest");
98
99    agent.with_system_prompt(
100        &format!(
101            "You are a helpful assistant that can generate content and save it to files. \
102             When asked to create content, generate it and use the file_saver tool to save it. \
103             \
104             IMPORTANT: All files MUST be saved inside the '{}' directory. \
105             For example, to save 'server.js', use '{}/server.js' as the filename. \
106             For files in subdirectories, use '{}/src/app.js' format. \
107             \
108             Be clear about what you're creating and where you're saving it.",
109            output_dir, output_dir, output_dir
110        )
111    );
112
113    // Step 2: Register the file saver tool
114    println!("🔧 Registering file saver tool...");
115    agent.add_tool(FileSaverTool);
116    println!("✓ Tool registered\n");
117
118    // Step 3: Create a task that generates content and saves it
119    let mut task = TaskRequest::new(
120        &format!(
121            "Create a simple web project with a file upload API. Save all files in the '{}' directory:\
122             \n1. server.js - A Node.js Express server with POST /upload endpoint\
123             \n2. package.json - Package configuration with dependencies\
124             \n3. test.http - HTTP test file to test the upload endpoint\
125             \n4. README.md - Instructions on how to install and run the server\
126             \n\nMake sure ALL files are saved in the '{}' directory!",
127            output_dir, output_dir
128        )
129    );
130    task.with_name("Generate and Save Web Project")
131        .with_description("Generate a complete web project with file upload API")
132        .with_priority(7);
133
134    // Step 4: Run the agent
135    println!("📋 Task: {}\n", task.id());
136    println!("🔄 Running agent...\n");
137
138    let response = agent.run(task).await;
139
140    // Step 5: Display the result
141    match response.result() {
142        OutputData::Text(answer) => {
143            println!("\n📝 Agent Response:\n{}\n", answer);
144        }
145        _ => {
146            println!("❌ Unexpected response type");
147        }
148    }
149
150    // Step 6: Verify files were created
151    println!("🔍 Checking created files in '{}/'\n", output_dir);
152
153    let expected_files = vec![
154        "server.js",
155        "package.json",
156        "test.http",
157        "README.md"
158    ];
159
160    let mut created_count = 0;
161
162    for file in &expected_files {
163        let file_path = format!("{}/{}", output_dir, file);
164        if Path::new(&file_path).exists() {
165            created_count += 1;
166            println!("✓ {} created successfully", file);
167
168            if let Ok(content) = fs::read_to_string(&file_path) {
169                let preview: String = content.chars().take(100).collect();
170                println!("  Preview: {}", preview.replace('\n', " "));
171            }
172        } else {
173            println!("⚠ {} not found", file);
174        }
175    }
176
177    println!("\n📊 Summary: {}/{} expected files created", created_count, expected_files.len());
178
179    // Show directory structure
180    println!("\n📂 Directory structure:");
181    if let Ok(entries) = fs::read_dir(output_dir) {
182        for entry in entries.flatten() {
183            let path = entry.path();
184            if path.is_file() {
185                if let Some(filename) = path.file_name() {
186                    if let Ok(metadata) = entry.metadata() {
187                        println!("  - {} ({} bytes)",
188                                 filename.to_string_lossy(),
189                                 metadata.len());
190                    }
191                }
192            }
193        }
194    }
195
196    println!("\n✅ Example completed successfully!");
197    println!("📁 All files are in: {}/", output_dir);
198}
Source

pub fn with_priority(&mut self, priority: u64) -> &mut Self

Sets the priority of the task (1-10, where 10 is highest).

§Arguments
  • priority - Task priority level
Examples found in repository?
examples/02_with_tools.rs (line 161)
137async fn main() {
138    println!("🤖 Ceylon Agent - Tools Example\n");
139
140    // Step 1: Create an agent
141    let mut agent = Agent::new("MathAssistant", "ollama::gemma3:latest");
142
143    agent.with_system_prompt(
144        "You are a helpful math and text assistant. \
145         Use the available tools to help the user. \
146         Be clear about what tools you're using and why."
147    );
148
149    // Step 2: Register custom tools with the agent
150    println!("🔧 Registering tools...");
151    agent.add_tool(CalculatorTool);
152    agent.add_tool(StringToolTool);
153    println!("✓ Tools registered\n");
154
155    // Step 3: Create a task that requires tool usage
156    let mut task = TaskRequest::new(
157        "Please calculate 25 + 15 + 10, and then tell me the uppercase version of the word 'hello'"
158    );
159    task.with_name("Complex Task")
160        .with_description("A task requiring multiple tools")
161        .with_priority(8);
162
163    // Step 4: Run the agent
164    println!("📋 Task: {}\n", task.id());
165    let response = agent.run(task).await;
166
167    // Step 5: Display the result
168    match response.result() {
169        OutputData::Text(answer) => {
170            println!("📝 Agent Response:\n{}\n", answer);
171        }
172        _ => {
173            println!("❌ Unexpected response type");
174        }
175    }
176
177    println!("✅ Example completed successfully!");
178}
More examples
Hide additional examples
examples/01_basic_agent.rs (line 36)
12async fn main() {
13    println!("🤖 Ceylon Agent - Basic Example\n");
14
15    // Step 1: Create a new agent with a name and model
16    // The model should be one supported by the LLM library (openai, anthropic, ollama, etc.)
17    let mut agent = Agent::new("Assistant", "ollama::gemma3:latest");
18
19    // Step 2: (Optional) Configure the agent with custom settings
20    let config = AgentConfig::new(
21        3,   // max_retries
22        60,  // timeout in seconds
23    );
24    agent.with_config(config);
25
26    // Step 3: (Optional) Customize the system prompt
27    agent.with_system_prompt(
28        "You are a helpful assistant that answers questions accurately and concisely. \
29         Always provide well-structured responses."
30    );
31
32    // Step 4: Create a task request
33    let mut task = TaskRequest::new("What is the capital of France?");
34    task.with_name("Geography Question")
35        .with_description("A simple geography question")
36        .with_priority(5);
37
38    // Step 5: Run the agent with the task
39    println!("📋 Task: {}\n", "What is the capital of France?");
40    let response = agent.run(task).await;
41
42    // Step 6: Handle the response
43    match response.result() {
44        OutputData::Text(answer) => {
45            println!("📝 Agent Response:\n{}\n", answer);
46        }
47        _ => {
48            println!("❌ Unexpected response type");
49        }
50    }
51
52    println!("✅ Example completed successfully!");
53}
examples/04_advanced_agent.rs (line 167)
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}
examples/03_with_memory.rs (line 39)
12async fn main() {
13    println!("🤖 Ceylon Agent - Memory Example\n");
14
15    // Step 1: Create an agent
16    let mut agent = Agent::new("MemoryAssistant", "ollama::gemma3:latest");
17
18    agent.with_system_prompt(
19        "You are a helpful assistant with persistent memory. \
20         Remember important details from our previous conversations \
21         and refer back to them when relevant."
22    );
23
24    // Step 2: Run multiple tasks to build conversation history
25    let tasks_and_prompts = vec![
26        ("Tell me about your favorite color", "Learn about preferences"),
27        ("What color did I mention?", "Test memory recall"),
28        ("Can you suggest a hobby based on what you know about me?", "Use memory for suggestions"),
29    ];
30
31    for (prompt, description) in tasks_and_prompts {
32        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
33        println!("📋 Task: {}", prompt);
34        println!("📝 Description: {}", description);
35        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
36
37        let mut task = TaskRequest::new(prompt);
38        task.with_name(description)
39            .with_priority(5);
40
41        // Run the agent
42        let response = agent.run(task).await;
43
44        // Display response
45        match response.result() {
46            OutputData::Text(answer) => {
47                println!("✓ Response received\n");
48            }
49            _ => {
50                println!("❌ Unexpected response type\n");
51            }
52        }
53    }
54
55    // Step 3: Retrieve conversation history
56    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
57    println!("📚 Retrieving conversation history...\n");
58
59    let history = agent.get_history(Some(5)).await;
60    println!("Found {} recent conversations\n", history.len());
61
62    if !history.is_empty() {
63        println!("📖 Conversation Summary:");
64        for (i, entry) in history.iter().enumerate() {
65            println!("\n--- Conversation {} ---", i + 1);
66            println!("Messages: {}", entry.messages.len());
67
68            // Show first and last message
69            if let Some(first) = entry.messages.first() {
70                println!("First: {} - {}", first.role,
71                    if first.content.len() > 50 {
72                        format!("{}...", &first.content[..50])
73                    } else {
74                        first.content.clone()
75                    });
76            }
77
78            if let Some(last) = entry.messages.last() {
79                println!("Last: {} - {}", last.role,
80                    if last.content.len() > 50 {
81                        format!("{}...", &last.content[..50])
82                    } else {
83                        last.content.clone()
84                    });
85            }
86        }
87    }
88
89    // Step 4: Search memory
90    println!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
91    println!("🔍 Searching memory for 'color'...\n");
92
93    let search_results = agent.search_memory("color").await;
94    println!("Found {} conversations mentioning 'color'\n", search_results.len());
95
96    // Step 5: Clear memory (optional)
97    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
98    println!("🧹 Memory management options:");
99    println!("- Use agent.get_history() to retrieve conversation history");
100    println!("- Use agent.search_memory(query) to search conversations");
101    println!("- Use agent.clear_memory() to clear all agent memory\n");
102
103    println!("✅ Example completed successfully!");
104}
examples/10_file_saving.rs (line 132)
83async fn main() {
84    println!("🤖 Ceylon Agent - File Saving Example\n");
85
86    // Define the output directory
87    let output_dir = "test/web_project_output";
88
89    // Create the output directory if it doesn't exist
90    if let Err(e) = fs::create_dir_all(output_dir) {
91        eprintln!("❌ Failed to create output directory: {}", e);
92        return;
93    }
94    println!("📁 Output directory: {}/\n", output_dir);
95
96    // Step 1: Create an agent
97    let mut agent = Agent::new("ContentGenerator", "ollama::gemma3:latest");
98
99    agent.with_system_prompt(
100        &format!(
101            "You are a helpful assistant that can generate content and save it to files. \
102             When asked to create content, generate it and use the file_saver tool to save it. \
103             \
104             IMPORTANT: All files MUST be saved inside the '{}' directory. \
105             For example, to save 'server.js', use '{}/server.js' as the filename. \
106             For files in subdirectories, use '{}/src/app.js' format. \
107             \
108             Be clear about what you're creating and where you're saving it.",
109            output_dir, output_dir, output_dir
110        )
111    );
112
113    // Step 2: Register the file saver tool
114    println!("🔧 Registering file saver tool...");
115    agent.add_tool(FileSaverTool);
116    println!("✓ Tool registered\n");
117
118    // Step 3: Create a task that generates content and saves it
119    let mut task = TaskRequest::new(
120        &format!(
121            "Create a simple web project with a file upload API. Save all files in the '{}' directory:\
122             \n1. server.js - A Node.js Express server with POST /upload endpoint\
123             \n2. package.json - Package configuration with dependencies\
124             \n3. test.http - HTTP test file to test the upload endpoint\
125             \n4. README.md - Instructions on how to install and run the server\
126             \n\nMake sure ALL files are saved in the '{}' directory!",
127            output_dir, output_dir
128        )
129    );
130    task.with_name("Generate and Save Web Project")
131        .with_description("Generate a complete web project with file upload API")
132        .with_priority(7);
133
134    // Step 4: Run the agent
135    println!("📋 Task: {}\n", task.id());
136    println!("🔄 Running agent...\n");
137
138    let response = agent.run(task).await;
139
140    // Step 5: Display the result
141    match response.result() {
142        OutputData::Text(answer) => {
143            println!("\n📝 Agent Response:\n{}\n", answer);
144        }
145        _ => {
146            println!("❌ Unexpected response type");
147        }
148    }
149
150    // Step 6: Verify files were created
151    println!("🔍 Checking created files in '{}/'\n", output_dir);
152
153    let expected_files = vec![
154        "server.js",
155        "package.json",
156        "test.http",
157        "README.md"
158    ];
159
160    let mut created_count = 0;
161
162    for file in &expected_files {
163        let file_path = format!("{}/{}", output_dir, file);
164        if Path::new(&file_path).exists() {
165            created_count += 1;
166            println!("✓ {} created successfully", file);
167
168            if let Ok(content) = fs::read_to_string(&file_path) {
169                let preview: String = content.chars().take(100).collect();
170                println!("  Preview: {}", preview.replace('\n', " "));
171            }
172        } else {
173            println!("⚠ {} not found", file);
174        }
175    }
176
177    println!("\n📊 Summary: {}/{} expected files created", created_count, expected_files.len());
178
179    // Show directory structure
180    println!("\n📂 Directory structure:");
181    if let Ok(entries) = fs::read_dir(output_dir) {
182        for entry in entries.flatten() {
183            let path = entry.path();
184            if path.is_file() {
185                if let Some(filename) = path.file_name() {
186                    if let Ok(metadata) = entry.metadata() {
187                        println!("  - {} ({} bytes)",
188                                 filename.to_string_lossy(),
189                                 metadata.len());
190                    }
191                }
192            }
193        }
194    }
195
196    println!("\n✅ Example completed successfully!");
197    println!("📁 All files are in: {}/", output_dir);
198}
examples/11_persistent_memory.rs (line 45)
16async fn main() {
17    println!("🤖 Ceylon Agent - Persistent Memory Example\n");
18
19    // ============================================
20    // Part 1: SQLite Backend
21    // ============================================
22    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
23    println!("📦 Part 1: SQLite Backend");
24    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
25
26    let sqlite_path = "agent_memory.db";
27    let sqlite_store = SqliteStore::new(sqlite_path).await
28        .expect("Failed to create SQLite store");
29
30    let mut agent = Agent::new("PersistentAssistant", "ollama::gemma3:latest");
31    agent.with_memory(Arc::new(sqlite_store))
32         .with_system_prompt("You are a helpful assistant with persistent memory across sessions.");
33
34    println!("✅ Created agent with SQLite backend at {}\n", sqlite_path);
35
36    // Run some tasks to populate memory
37    let tasks = vec![
38        "My name is Alice and I love programming in Rust",
39        "What programming language do I like?",
40    ];
41
42    for prompt in tasks {
43        println!("📋 Task: {}", prompt);
44        let mut task = TaskRequest::new(prompt);
45        task.with_priority(5);
46
47        let response = agent.run(task).await;
48        if let OutputData::Text(_) = response.result() {
49            println!("✓ Task completed\n");
50        }
51    }
52
53    println!("📊 SQLite database now contains conversation history");
54    println!("   This data persists even after the program exits!\n");
55
56    // ============================================
57    // Part 2: File-based Backend (JSON)
58    // ============================================
59    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
60    println!("📄 Part 2: File-based Backend (JSON)");
61    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
62
63    let json_path = "agent_memory.json";
64    let file_store = FileStore::new(json_path, StorageFormat::Json).await
65        .expect("Failed to create File store");
66
67    let mut agent2 = Agent::new("FileAssistant", "ollama::gemma3:latest");
68    agent2.with_memory(Arc::new(file_store))
69          .with_system_prompt("You are a helpful assistant storing memories in JSON files.");
70
71    println!("✅ Created agent with JSON file backend at {}\n", json_path);
72
73    let task = TaskRequest::new("Remember: My favorite color is blue");
74    let response = agent2.run(task).await;
75
76    if let OutputData::Text(_) = response.result() {
77        println!("✓ Memory saved to JSON file");
78        println!("   You can open {} to view the human-readable data!\n", json_path);
79    }
80
81    // ============================================
82    // Part 3: MessagePack Backend
83    // ============================================
84    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
85    println!("📦 Part 3: MessagePack Backend (Compact Binary)");
86    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
87
88    let msgpack_path = "agent_memory.msgpack";
89    let msgpack_store = FileStore::new(msgpack_path, StorageFormat::MessagePack).await
90        .expect("Failed to create MessagePack store");
91
92    let mut agent3 = Agent::new("BinaryAssistant", "ollama::gemma3:latest");
93    agent3.with_memory(Arc::new(msgpack_store))
94          .with_system_prompt("You are a helpful assistant using compact binary storage.");
95
96    println!("✅ Created agent with MessagePack backend at {}\n", msgpack_path);
97
98    let task = TaskRequest::new("Store this efficiently: The quick brown fox jumps over the lazy dog");
99    let response = agent3.run(task).await;
100
101    if let OutputData::Text(_) = response.result() {
102        println!("✓ Memory saved to MessagePack file");
103        println!("   Binary format is more compact than JSON!\n");
104    }
105
106    // ============================================
107    // Part 4: Memory Migration
108    // ============================================
109    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
110    println!("🔄 Part 4: Memory Migration Between Backends");
111    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
112
113    // Create source and destination stores
114    let source_db = SqliteStore::new("source.db").await.unwrap();
115
116    // Create an agent with source backend and add some data
117    let mut temp_agent = Agent::new("MigrationAgent", "ollama::gemma3:latest");
118    temp_agent.with_memory(Arc::new(source_db));
119
120    let task = TaskRequest::new("Migration test: This data will be migrated!");
121    temp_agent.run(task).await;
122
123    // Note: You would normally track your agent IDs. For this demo, we'll use
124    // a known pattern - the agent creates entries with its own ID
125    println!("💡 Tip: To migrate data, you need to know the agent's ID");
126    println!("   In production, track agent IDs when creating agents\n");
127
128    println!("✓ Migration between backends is available via migrate_memory()\n");
129    println!("   Example: migrate_memory(&source, &target, \"agent-id\").await\n");
130
131    // ============================================
132    // Part 5: Export/Import Utilities
133    // ============================================
134    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
135    println!("💾 Part 5: Export/Import Utilities");
136    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
137
138    // Demonstrate export/import with the existing SQLite database
139    println!("💡 Export and import utilities are available:\n");
140    println!("   • export_to_json(store, agent_id, path)");
141    println!("   • export_to_msgpack(store, agent_id, path)");
142    println!("   • import_from_json(store, path)");
143    println!("   • import_from_msgpack(store, path)\n");
144
145    println!("✓ These functions allow you to backup and restore agent memories\n");
146
147    // ============================================
148    // Summary
149    // ============================================
150    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
151    println!("📊 Summary: Available Backends");
152    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
153
154    println!("1. InMemoryStore (default)");
155    println!("   • Fast, but data lost on restart");
156    println!("   • Best for: Development, testing\n");
157
158    println!("2. SqliteStore");
159    println!("   • Persistent, efficient queries");
160    println!("   • Best for: Production apps, large datasets\n");
161
162    println!("3. FileStore (JSON)");
163    println!("   • Human-readable, easy to inspect");
164    println!("   • Best for: Debugging, data sharing\n");
165
166    println!("4. FileStore (MessagePack)");
167    println!("   • Compact binary format");
168    println!("   • Best for: Large datasets, bandwidth constraints\n");
169
170    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
171    println!("📝 Files Created:");
172    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
173
174    println!("• agent_memory.db         - SQLite database");
175    println!("• agent_memory.json       - JSON storage");
176    println!("• agent_memory.msgpack    - MessagePack storage");
177    println!("• backup.json             - Migrated data");
178    println!("• exported_memory.json    - Exported snapshot");
179    println!("• exported_memory.msgpack - Exported snapshot (binary)\n");
180
181    println!("✅ Example completed successfully!");
182    println!("\n💡 Tip: Check the created files to see your persisted data!");
183    println!("   Try running this example again - your SQLite data will persist!");
184}
Source§

impl TaskRequest

Source

pub fn id(&self) -> &str

Returns the unique ID of this task.

Examples found in repository?
examples/02_with_tools.rs (line 164)
137async fn main() {
138    println!("🤖 Ceylon Agent - Tools Example\n");
139
140    // Step 1: Create an agent
141    let mut agent = Agent::new("MathAssistant", "ollama::gemma3:latest");
142
143    agent.with_system_prompt(
144        "You are a helpful math and text assistant. \
145         Use the available tools to help the user. \
146         Be clear about what tools you're using and why."
147    );
148
149    // Step 2: Register custom tools with the agent
150    println!("🔧 Registering tools...");
151    agent.add_tool(CalculatorTool);
152    agent.add_tool(StringToolTool);
153    println!("✓ Tools registered\n");
154
155    // Step 3: Create a task that requires tool usage
156    let mut task = TaskRequest::new(
157        "Please calculate 25 + 15 + 10, and then tell me the uppercase version of the word 'hello'"
158    );
159    task.with_name("Complex Task")
160        .with_description("A task requiring multiple tools")
161        .with_priority(8);
162
163    // Step 4: Run the agent
164    println!("📋 Task: {}\n", task.id());
165    let response = agent.run(task).await;
166
167    // Step 5: Display the result
168    match response.result() {
169        OutputData::Text(answer) => {
170            println!("📝 Agent Response:\n{}\n", answer);
171        }
172        _ => {
173            println!("❌ Unexpected response type");
174        }
175    }
176
177    println!("✅ Example completed successfully!");
178}
More examples
Hide additional examples
examples/10_file_saving.rs (line 135)
83async fn main() {
84    println!("🤖 Ceylon Agent - File Saving Example\n");
85
86    // Define the output directory
87    let output_dir = "test/web_project_output";
88
89    // Create the output directory if it doesn't exist
90    if let Err(e) = fs::create_dir_all(output_dir) {
91        eprintln!("❌ Failed to create output directory: {}", e);
92        return;
93    }
94    println!("📁 Output directory: {}/\n", output_dir);
95
96    // Step 1: Create an agent
97    let mut agent = Agent::new("ContentGenerator", "ollama::gemma3:latest");
98
99    agent.with_system_prompt(
100        &format!(
101            "You are a helpful assistant that can generate content and save it to files. \
102             When asked to create content, generate it and use the file_saver tool to save it. \
103             \
104             IMPORTANT: All files MUST be saved inside the '{}' directory. \
105             For example, to save 'server.js', use '{}/server.js' as the filename. \
106             For files in subdirectories, use '{}/src/app.js' format. \
107             \
108             Be clear about what you're creating and where you're saving it.",
109            output_dir, output_dir, output_dir
110        )
111    );
112
113    // Step 2: Register the file saver tool
114    println!("🔧 Registering file saver tool...");
115    agent.add_tool(FileSaverTool);
116    println!("✓ Tool registered\n");
117
118    // Step 3: Create a task that generates content and saves it
119    let mut task = TaskRequest::new(
120        &format!(
121            "Create a simple web project with a file upload API. Save all files in the '{}' directory:\
122             \n1. server.js - A Node.js Express server with POST /upload endpoint\
123             \n2. package.json - Package configuration with dependencies\
124             \n3. test.http - HTTP test file to test the upload endpoint\
125             \n4. README.md - Instructions on how to install and run the server\
126             \n\nMake sure ALL files are saved in the '{}' directory!",
127            output_dir, output_dir
128        )
129    );
130    task.with_name("Generate and Save Web Project")
131        .with_description("Generate a complete web project with file upload API")
132        .with_priority(7);
133
134    // Step 4: Run the agent
135    println!("📋 Task: {}\n", task.id());
136    println!("🔄 Running agent...\n");
137
138    let response = agent.run(task).await;
139
140    // Step 5: Display the result
141    match response.result() {
142        OutputData::Text(answer) => {
143            println!("\n📝 Agent Response:\n{}\n", answer);
144        }
145        _ => {
146            println!("❌ Unexpected response type");
147        }
148    }
149
150    // Step 6: Verify files were created
151    println!("🔍 Checking created files in '{}/'\n", output_dir);
152
153    let expected_files = vec![
154        "server.js",
155        "package.json",
156        "test.http",
157        "README.md"
158    ];
159
160    let mut created_count = 0;
161
162    for file in &expected_files {
163        let file_path = format!("{}/{}", output_dir, file);
164        if Path::new(&file_path).exists() {
165            created_count += 1;
166            println!("✓ {} created successfully", file);
167
168            if let Ok(content) = fs::read_to_string(&file_path) {
169                let preview: String = content.chars().take(100).collect();
170                println!("  Preview: {}", preview.replace('\n', " "));
171            }
172        } else {
173            println!("⚠ {} not found", file);
174        }
175    }
176
177    println!("\n📊 Summary: {}/{} expected files created", created_count, expected_files.len());
178
179    // Show directory structure
180    println!("\n📂 Directory structure:");
181    if let Ok(entries) = fs::read_dir(output_dir) {
182        for entry in entries.flatten() {
183            let path = entry.path();
184            if path.is_file() {
185                if let Some(filename) = path.file_name() {
186                    if let Ok(metadata) = entry.metadata() {
187                        println!("  - {} ({} bytes)",
188                                 filename.to_string_lossy(),
189                                 metadata.len());
190                    }
191                }
192            }
193        }
194    }
195
196    println!("\n✅ Example completed successfully!");
197    println!("📁 All files are in: {}/", output_dir);
198}
Source

pub fn message(&self) -> Message

Converts the task to an LLM message.

This is used internally by the agent to send the task to the LLM.

Source

pub fn description(&self) -> &str

Returns the task description.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,