Agent

Struct Agent 

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

An AI Agent with goal-oriented capabilities, memory, and tool integration.

Agent is the core component of the Ceylon framework. It manages:

  • LLM interactions for generating responses
  • Goal analysis and tracking
  • Conversation history and memory
  • Tool execution and management

§Examples

use ceylon_next::agent::Agent;
use ceylon_next::tasks::TaskRequest;

#[tokio::main]
async fn main() {
    let mut agent = Agent::new("Assistant", "openai::gpt-4");

    let task = TaskRequest::new("Hello, how are you?");
    let response = agent.run(task).await;

    println!("{:?}", response.result());
}

Implementations§

Source§

impl Agent

Source

pub fn new(name: &str, model: &str) -> Self

Creates a new Agent with the specified name and LLM model.

§Arguments
  • name - The name of the agent (used in system prompts)
  • model - The LLM model to use (e.g., “openai::gpt-4”, “claude-3-opus”, “llama2”)
§Examples
use ceylon_next::agent::Agent;

let agent = Agent::new("MyAssistant", "openai::gpt-4");
§Supported Models
  • OpenAI: “openai::gpt-4”, “gpt-3.5-turbo”
  • Anthropic: “claude-3-opus”, “claude-3-sonnet”
  • Ollama: “llama2”, “mistral”
§Panics

Panics if the model format is invalid or if an API key is required but not found in environment variables. Use Agent::new_with_config to provide API keys explicitly.

Examples found in repository?
examples/02_with_tools.rs (line 141)
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 17)
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 130)
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 26)
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 (line 42)
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 117)
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 new_with_config( name: &str, llm_config: LLMConfig, ) -> Result<Self, String>

Creates a new Agent with the specified name and LLM configuration.

This method allows you to provide comprehensive LLM configuration including API keys, temperature, max tokens, and other provider-specific settings.

§Arguments
  • name - The name of the agent (used in system prompts)
  • llm_config - LLM configuration with model, API key, and other settings
§Examples
use ceylon_next::agent::Agent;
use ceylon_next::llm::LLMConfig;

// Create agent with explicit API key
let config = LLMConfig::new("openai::gpt-4")
    .with_api_key("your-api-key")
    .with_temperature(0.7)
    .with_max_tokens(2048);

let agent = Agent::new_with_config("Assistant", config).unwrap();
§Errors

Returns an error if:

  • The model format is invalid (should be “provider::model-name”)
  • An API key is required but not provided or found in environment variables
  • The LLM provider fails to initialize
Examples found in repository?
examples/08_llm_providers.rs (line 179)
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}
More examples
Hide additional examples
examples/09_test_groq.rs (line 23)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("🧪 Testing Groq LLM Provider with API Key\n");
8
9    // Test 1: Using Agent::new_with_config() - Recommended approach
10    println!("{}", "=".repeat(60));
11    println!("Test 1: Using Agent::new_with_config() with explicit API key");
12    println!("{}", "=".repeat(60));
13
14    match std::env::var("GROQ_API_KEY") {
15        Ok(api_key) => {
16            println!("✓ GROQ_API_KEY found in environment\n");
17
18            let groq_config = LLMConfig::new("groq::llama-3.3-70b-versatile")
19                .with_api_key(api_key)
20                .with_temperature(0.7)
21                .with_max_tokens(100);
22
23            match Agent::new_with_config("Groq Agent", groq_config) {
24                Ok(mut agent) => {
25                    println!("✓ Groq agent created successfully!\n");
26
27                    println!("Running task: 'What is 2 + 2?'");
28                    let task = TaskRequest::new("What is 2 + 2? Answer in one short sentence.");
29                    println!("Sending request to Groq API...\n");
30
31                    let response = agent.run(task).await;
32
33                    println!("Response received:");
34                    println!("================");
35                    println!("{:?}", response.result());
36                    println!("================\n");
37
38                    println!("🎉 Test 1 completed successfully!");
39                }
40                Err(e) => {
41                    println!("✗ Failed to create Groq agent: {}\n", e);
42                }
43            }
44        }
45        Err(_) => {
46            println!("✗ GROQ_API_KEY not found in environment");
47            println!("  Please set GROQ_API_KEY to run this test\n");
48        }
49    }
50
51    // Test 2: Using Agent::new() with environment variable - Simpler approach
52    println!("\n{}", "=".repeat(60));
53    println!("Test 2: Using Agent::new() with environment variable");
54    println!("{}", "=".repeat(60));
55
56    if std::env::var("GROQ_API_KEY").is_ok() {
57        println!("✓ GROQ_API_KEY is set, agent will use it automatically\n");
58
59        match std::panic::catch_unwind(|| {
60            Agent::new("Simple Groq Agent", "groq::llama-3.3-70b-versatile")
61        }) {
62            Ok(mut agent) => {
63                println!("✓ Groq agent created successfully with auto API key!\n");
64
65                println!("Running task: 'What is the capital of France?'");
66                let task = TaskRequest::new("What is the capital of France? Answer in one word.");
67
68                let response = agent.run(task).await;
69
70                println!("Response received:");
71                println!("================");
72                println!("{:?}", response.result());
73                println!("================\n");
74
75                println!("🎉 Test 2 completed successfully!");
76            }
77            Err(_) => {
78                println!("✗ Failed to create agent (unexpected panic)\n");
79            }
80        }
81    } else {
82        println!("✗ GROQ_API_KEY not set, skipping this test\n");
83    }
84
85    println!("\n{}", "=".repeat(60));
86    println!("All tests completed!");
87    println!("{}", "=".repeat(60));
88
89    Ok(())
90}
Source

pub fn with_memory(&mut self, memory: Arc<dyn Memory>) -> &mut Self

Sets a custom memory implementation for the agent.

By default, agents use InMemoryStore. You can provide a custom implementation of the Memory trait for persistent storage.

§Arguments
  • memory - An Arc-wrapped implementation of the Memory trait
§Examples
use ceylon_next::agent::Agent;
use std::sync::Arc;
// Assuming you have a custom RedisMemory implementation
// let redis_memory = Arc::new(RedisMemory::new());
// let mut agent = Agent::new("Assistant", "openai::gpt-4");
// agent.with_memory(redis_memory);
Examples found in repository?
examples/11_persistent_memory.rs (line 31)
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

pub async fn get_history(&self, limit: Option<usize>) -> Vec<MemoryEntry>

Retrieves conversation history from memory.

§Arguments
  • limit - Optional limit on number of conversations to retrieve. If None, returns all history.
§Returns

A vector of MemoryEntry objects sorted by recency (newest first).

§Examples
use ceylon_next::agent::Agent;

let agent = Agent::new("Assistant", "openai::gpt-4");

// Get last 5 conversations
let recent = agent.get_history(Some(5)).await;

// Get all history
let all = agent.get_history(None).await;
Examples found in repository?
examples/03_with_memory.rs (line 59)
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}
Source

pub async fn search_memory(&self, query: &str) -> Vec<MemoryEntry>

Searches conversation history for messages containing the query string.

Performs a case-insensitive text search across all stored messages.

§Arguments
  • query - The search query string
§Returns

A vector of MemoryEntry objects containing the query.

§Examples
use ceylon_next::agent::Agent;

let agent = Agent::new("Assistant", "openai::gpt-4");

let results = agent.search_memory("Python").await;
println!("Found {} conversations about Python", results.len());
Examples found in repository?
examples/03_with_memory.rs (line 93)
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}
Source

pub async fn clear_memory(&self) -> Result<(), String>

Clears all conversation history for this agent.

§Returns

Ok(()) if successful, Err(String) with error message if failed.

§Examples
use ceylon_next::agent::Agent;

let agent = Agent::new("Assistant", "openai::gpt-4");

if let Err(e) = agent.clear_memory().await {
    eprintln!("Failed to clear memory: {}", e);
}
Source

pub fn get_current_goal(&self) -> Option<&Goal>

Returns the current goal the agent is working on, if any.

§Examples
use ceylon_next::agent::Agent;
use ceylon_next::tasks::TaskRequest;

let mut agent = Agent::new("Assistant", "openai::gpt-4");

let task = TaskRequest::new("Build a web server");
agent.run(task).await;

if let Some(goal) = agent.get_current_goal() {
    println!("Current goal: {}", goal.description);
}
Source

pub fn set_goal(&mut self, goal: Goal)

Manually sets a goal for the agent to work on.

This is useful when you want to provide a pre-structured goal instead of having the agent analyze the task automatically.

§Arguments
  • goal - The goal to set
§Examples
use ceylon_next::agent::Agent;
use ceylon_next::goal::Goal;

let mut agent = Agent::new("Assistant", "openai::gpt-4");

let mut goal = Goal::new("Create a REST API".to_string());
goal.add_sub_goal("Design endpoints".to_string(), 1);
goal.add_sub_goal("Implement handlers".to_string(), 2);

agent.set_goal(goal);
Examples found in repository?
examples/05_with_goals.rs (line 55)
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}
More examples
Hide additional examples
examples/06_nextjs_app_generator.rs (line 67)
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}
examples/07_python_project_generator.rs (line 140)
109async fn example_1_basic_cli_app() {
110    println!("=== Example 1: Generate a Basic Python CLI Application ===\n");
111
112    let mut agent = Agent::new("PythonCliGenerator", "ollama::gemma3:latest");
113
114    // Create a goal for generating a Python CLI app
115    let mut goal = Goal::new(
116        "Generate a Python command-line application with core structure".to_string()
117    );
118
119    // Define success criteria
120    goal.add_criterion("requirements.txt with dependencies listed".to_string());
121    goal.add_criterion("setup.py or pyproject.toml for packaging".to_string());
122    goal.add_criterion("Main CLI entry point with argument parsing".to_string());
123    goal.add_criterion("Command structure with subcommands".to_string());
124    goal.add_criterion("Basic error handling and logging".to_string());
125    goal.add_criterion("README.md with usage instructions".to_string());
126    goal.add_criterion(".gitignore for Python projects".to_string());
127
128    // Define sub-goals (steps to generate the app)
129    goal.add_sub_goal("Analyze Python CLI best practices".to_string(), 0);
130    goal.add_sub_goal("Generate project structure and directories".to_string(), 1);
131    goal.add_sub_goal("Create requirements.txt with dependencies (Click, Typer, etc)".to_string(), 2);
132    goal.add_sub_goal("Generate pyproject.toml or setup.py".to_string(), 3);
133    goal.add_sub_goal("Create main CLI module with argument parser".to_string(), 4);
134    goal.add_sub_goal("Generate subcommands and command handlers".to_string(), 5);
135    goal.add_sub_goal("Create utility modules and helpers".to_string(), 6);
136    goal.add_sub_goal("Add logging and error handling".to_string(), 7);
137    goal.add_sub_goal("Generate README with installation and usage".to_string(), 8);
138
139    goal.status = GoalStatus::InProgress;
140    agent.set_goal(goal.clone());
141
142    // Create a task to generate a Python CLI app
143    let task = TaskRequest::new(
144        "Generate a professional Python command-line application with the following structure:\n\
145         1. Modern argument parsing using Click or Typer\n\
146         2. Multiple subcommands (e.g., init, run, config, help)\n\
147         3. Configuration file support (YAML or JSON)\n\
148         4. Logging with different verbosity levels\n\
149         5. Error handling and graceful failure messages\n\
150         6. Proper project structure with src/ and tests/ directories\n\
151         7. pyproject.toml or setup.py for packaging\n\
152         8. requirements.txt with dev dependencies\n\
153         9. .gitignore for Python\n\
154         10. Comprehensive README with examples\n\
155         The app should be production-ready and follow Python best practices (PEP 8)."
156    );
157
158    println!("📝 Task: Generate a Python CLI Application\n");
159    println!("🎯 Success Criteria:");
160    for criterion in &goal.success_criteria {
161        println!("  • {}", criterion.description);
162    }
163
164    println!("\n⏳ Agent is generating the Python CLI app...\n");
165    let response = agent.run(task).await;
166
167    // Extract and display the output
168    let output = extract_output_text(&response.result());
169    println!("📄 Generated Output:\n");
170    println!("{}\n", output);
171
172    // Show progress
173    println!("📊 Goal Progress: {}%", goal.get_progress());
174    println!("Status: {:?}", goal.status);
175
176    println!("\n✅ Example 1 completed!\n");
177}
178
179// ============================================
180// Example 2: Python Web API with FastAPI
181// ============================================
182
183async fn example_2_fastapi_web_app() {
184    println!("\n=== Example 2: Generate Python FastAPI Web Application ===\n");
185
186    let mut agent = Agent::new("FastApiGenerator", "ollama::gemma3:latest");
187
188    let mut goal = Goal::new(
189        "Generate a complete FastAPI web application with database integration".to_string()
190    );
191
192    // Success criteria for FastAPI app
193    goal.add_criterion("FastAPI application structure with routers".to_string());
194    goal.add_criterion("Database models using SQLAlchemy".to_string());
195    goal.add_criterion("RESTful API endpoints with CRUD operations".to_string());
196    goal.add_criterion("Request/response schemas using Pydantic".to_string());
197    goal.add_criterion("Authentication and authorization middleware".to_string());
198    goal.add_criterion("Database migrations with Alembic".to_string());
199    goal.add_criterion("Configuration management with environment variables".to_string());
200    goal.add_criterion("Unit and integration test examples".to_string());
201    goal.add_criterion("Docker setup for containerization".to_string());
202
203    // Sub-goals
204    goal.add_sub_goal("Design REST API endpoints structure".to_string(), 0);
205    goal.add_sub_goal("Create Pydantic models for request/response validation".to_string(), 1);
206    goal.add_sub_goal("Set up SQLAlchemy ORM with database models".to_string(), 2);
207    goal.add_sub_goal("Implement CRUD routers for resources".to_string(), 3);
208    goal.add_sub_goal("Add authentication and JWT tokens".to_string(), 4);
209    goal.add_sub_goal("Create Alembic migrations setup".to_string(), 5);
210    goal.add_sub_goal("Set up configuration with environment variables".to_string(), 6);
211    goal.add_sub_goal("Create test fixtures and example tests".to_string(), 7);
212    goal.add_sub_goal("Generate Docker and docker-compose files".to_string(), 8);
213    goal.add_sub_goal("Create comprehensive API documentation".to_string(), 9);
214
215    goal.status = GoalStatus::InProgress;
216    agent.set_goal(goal.clone());
217
218    let task = TaskRequest::new(
219        "Generate a production-ready FastAPI web application with:\n\
220         1. Modular project structure with routers for different resources\n\
221         2. Pydantic models for request/response validation\n\
222         3. SQLAlchemy ORM setup with database models\n\
223         4. CRUD operations for users, products, and orders\n\
224         5. JWT authentication and authorization middleware\n\
225         6. Role-based access control (RBAC)\n\
226         7. Alembic database migrations\n\
227         8. Environment configuration (.env support)\n\
228         9. Error handling with proper HTTP status codes\n\
229         10. Logging configuration\n\
230         11. Unit tests with pytest\n\
231         12. Integration tests with test database\n\
232         13. Docker and docker-compose for local development\n\
233         14. requirements.txt with all dependencies\n\
234         15. Comprehensive API documentation\n\
235         Use async/await patterns, follow REST conventions, and include examples."
236    );
237
238    println!("📝 Task: Generate FastAPI Web Application\n");
239    println!("🎯 FastAPI Features:");
240    for criterion in &goal.success_criteria {
241        println!("  ✓ {}", criterion.description);
242    }
243
244    println!("\n⏳ Agent is generating FastAPI app...\n");
245    let response = agent.run(task).await;
246
247    let output = extract_output_text(&response.result());
248    println!("📄 Generated Output:\n");
249    println!("{}\n", output);
250
251    println!("📊 Goal Progress: {}%", goal.get_progress());
252    println!("\n✅ Example 2 completed!\n");
253}
254
255// ============================================
256// Example 3: Python Data Science Project
257// ============================================
258
259async fn example_3_data_science_project() {
260    println!("\n=== Example 3: Generate Python Data Science Project ===\n");
261
262    let mut agent = Agent::new("DataScienceGenerator", "ollama::gemma3:latest");
263
264    let mut goal = Goal::new(
265        "Generate a data science project with ML pipeline and analysis".to_string()
266    );
267
268    goal.add_criterion("Project structure following cookiecutter-data-science".to_string());
269    goal.add_criterion("Data loading and preprocessing modules".to_string());
270    goal.add_criterion("Exploratory data analysis (EDA) notebooks".to_string());
271    goal.add_criterion("Feature engineering pipeline".to_string());
272    goal.add_criterion("Model training and evaluation".to_string());
273    goal.add_criterion("Hyperparameter tuning setup".to_string());
274    goal.add_criterion("Model persistence and versioning".to_string());
275    goal.add_criterion("Visualization utilities".to_string());
276    goal.add_criterion("Unit tests for data pipeline".to_string());
277
278    goal.add_sub_goal("Create cookiecutter-style directory structure".to_string(), 0);
279    goal.add_sub_goal("Set up Jupyter notebook for EDA".to_string(), 1);
280    goal.add_sub_goal("Create data loading and preprocessing modules".to_string(), 2);
281    goal.add_sub_goal("Implement feature engineering pipeline".to_string(), 3);
282    goal.add_sub_goal("Set up scikit-learn model training".to_string(), 4);
283    goal.add_sub_goal("Create model evaluation and metrics".to_string(), 5);
284    goal.add_sub_goal("Implement hyperparameter tuning with GridSearchCV".to_string(), 6);
285    goal.add_sub_goal("Add model persistence with joblib/pickle".to_string(), 7);
286    goal.add_sub_goal("Create visualization utilities with matplotlib/seaborn".to_string(), 8);
287    goal.add_sub_goal("Write tests for data pipeline".to_string(), 9);
288
289    goal.status = GoalStatus::InProgress;
290    agent.set_goal(goal.clone());
291
292    let task = TaskRequest::new(
293        "Generate a comprehensive Python data science project with:\n\
294         1. Proper project structure for data science work\n\
295         2. Data loading module supporting CSV, JSON, Parquet\n\
296         3. Data preprocessing and validation pipeline\n\
297         4. Exploratory Data Analysis (EDA) notebook template\n\
298         5. Feature engineering module\n\
299         6. Model training with scikit-learn or XGBoost\n\
300         7. Cross-validation and evaluation metrics\n\
301         8. Hyperparameter tuning with GridSearchCV/RandomSearch\n\
302         9. Model persistence and loading utilities\n\
303         10. Visualization utilities (matplotlib, seaborn, plotly)\n\
304         11. Unit tests for data loading and preprocessing\n\
305         12. Configuration management for experiments\n\
306         13. Logging for training pipeline\n\
307         14. Requirements.txt with ML libraries (pandas, numpy, scikit-learn)\n\
308         15. Makefile for common tasks\n\
309         16. README with dataset description and results\n\
310         Include example workflows and best practices for reproducibility."
311    );
312
313    println!("📝 Task: Generate Data Science Project\n");
314    println!("🎯 Data Science Features:");
315    for criterion in &goal.success_criteria {
316        println!("  ✓ {}", criterion.description);
317    }
318
319    println!("\n⏳ Agent is generating data science project...\n");
320    let response = agent.run(task).await;
321
322    let output = extract_output_text(&response.result());
323    println!("📄 Generated Output:\n");
324    println!("{}\n", output);
325
326    println!("📊 Goal Progress: {}%", goal.get_progress());
327    println!("\n✅ Example 3 completed!\n");
328}
329
330// ============================================
331// Example 4: Python Package/Library
332// ============================================
333
334async fn example_4_python_library() {
335    println!("\n=== Example 4: Generate Python Library/Package ===\n");
336
337    let mut agent = Agent::new("PythonLibraryGenerator", "ollama::gemma3:latest");
338
339    let mut goal = Goal::new(
340        "Generate a well-structured Python package ready for distribution".to_string()
341    );
342
343    goal.add_criterion("Proper package structure with namespace".to_string());
344    goal.add_criterion("setup.py and pyproject.toml for distribution".to_string());
345    goal.add_criterion("Comprehensive docstrings and type hints".to_string());
346    goal.add_criterion("Unit tests with pytest".to_string());
347    goal.add_criterion("Documentation with Sphinx".to_string());
348    goal.add_criterion("CI/CD configuration (GitHub Actions)".to_string());
349    goal.add_criterion("Version management strategy".to_string());
350    goal.add_criterion("Contributing guidelines".to_string());
351
352    goal.add_sub_goal("Create package structure with __init__.py files".to_string(), 0);
353    goal.add_sub_goal("Write setup.py and pyproject.toml".to_string(), 1);
354    goal.add_sub_goal("Create core modules with type hints".to_string(), 2);
355    goal.add_sub_goal("Add comprehensive docstrings".to_string(), 3);
356    goal.add_sub_goal("Create test structure with pytest".to_string(), 4);
357    goal.add_sub_goal("Set up documentation with Sphinx".to_string(), 5);
358    goal.add_sub_goal("Create GitHub Actions workflows".to_string(), 6);
359    goal.add_sub_goal("Add CONTRIBUTING.md and CODE_OF_CONDUCT.md".to_string(), 7);
360    goal.add_sub_goal("Create MANIFEST.in and manifest files".to_string(), 8);
361
362    goal.status = GoalStatus::InProgress;
363    agent.set_goal(goal.clone());
364
365    let task = TaskRequest::new(
366        "Generate a professional Python library/package with:\n\
367         1. Standard package structure (src layout)\n\
368         2. __init__.py with version and exports\n\
369         3. Core modules with complete implementations\n\
370         4. Type hints throughout (PEP 484)\n\
371         5. Comprehensive docstrings (Google style)\n\
372         6. setup.py with metadata\n\
373         7. pyproject.toml with build system\n\
374         8. MANIFEST.in for package data\n\
375         9. Pytest test structure with fixtures\n\
376         10. pytest.ini configuration\n\
377         11. Sphinx documentation setup\n\
378         12. GitHub Actions workflow for CI/CD\n\
379         13. Pre-commit hooks configuration\n\
380         14. LICENSE (MIT or Apache 2.0)\n\
381         15. .gitignore for Python\n\
382         16. README.md with installation and usage\n\
383         17. CONTRIBUTING.md for contributors\n\
384         18. CODE_OF_CONDUCT.md\n\
385         19. Changelog/HISTORY.md template\n\
386         20. Version management with __version__\n\
387         Include examples for public API and best practices for library development."
388    );
389
390    println!("📝 Task: Generate Python Library Package\n");
391    println!("🎯 Library Features:");
392    for criterion in &goal.success_criteria {
393        println!("  ✓ {}", criterion.description);
394    }
395
396    println!("\n⏳ Agent is generating Python library...\n");
397    let response = agent.run(task).await;
398
399    let output = extract_output_text(&response.result());
400    println!("📄 Generated Output:\n");
401    println!("{}\n", output);
402
403    println!("📊 Goal Progress: {}%", goal.get_progress());
404    println!("\n✅ Example 4 completed!\n");
405}
406
407// ============================================
408// Example 5: Django Web Application
409// ============================================
410
411async fn example_5_django_web_app() {
412    println!("\n=== Example 5: Generate Django Web Application ===\n");
413
414    let mut agent = Agent::new("DjangoGenerator", "ollama::gemma3:latest");
415
416    let mut goal = Goal::new(
417        "Generate a complete Django web application with admin and authentication".to_string()
418    );
419
420    goal.add_criterion("Django project structure with multiple apps".to_string());
421    goal.add_criterion("Custom user model implementation".to_string());
422    goal.add_criterion("Database models for core features".to_string());
423    goal.add_criterion("Admin interface customization".to_string());
424    goal.add_criterion("Views and URL routing".to_string());
425    goal.add_criterion("Templates with Bootstrap styling".to_string());
426    goal.add_criterion("Authentication and permissions".to_string());
427    goal.add_criterion("Database migrations".to_string());
428    goal.add_criterion("Django REST Framework API".to_string());
429
430    goal.add_sub_goal("Create Django project and app structure".to_string(), 0);
431    goal.add_sub_goal("Design and implement custom user model".to_string(), 1);
432    goal.add_sub_goal("Create models for core features".to_string(), 2);
433    goal.add_sub_goal("Configure admin interface".to_string(), 3);
434    goal.add_sub_goal("Create views and templates".to_string(), 4);
435    goal.add_sub_goal("Set up URL routing".to_string(), 5);
436    goal.add_sub_goal("Implement authentication views".to_string(), 6);
437    goal.add_sub_goal("Create Django REST Framework serializers".to_string(), 7);
438    goal.add_sub_goal("Set up static files and media handling".to_string(), 8);
439
440    goal.status = GoalStatus::InProgress;
441    agent.set_goal(goal.clone());
442
443    let task = TaskRequest::new(
444        "Generate a full-featured Django web application with:\n\
445         1. Django project structure with multiple apps\n\
446         2. Custom user model extending AbstractBaseUser\n\
447         3. Models for main features (e.g., Blog posts, Comments, Categories)\n\
448         4. Django ORM relationships (ForeignKey, ManyToMany)\n\
449         5. Admin interface with custom actions\n\
450         6. Class-based views (ListView, DetailView, CreateView)\n\
451         7. Django templates with template inheritance\n\
452         8. Bootstrap styling integration\n\
453         9. Authentication and login required decorators\n\
454         10. Permission-based access control\n\
455         11. Database migrations\n\
456         12. Forms with validation\n\
457         13. Django REST Framework setup\n\
458         14. API serializers and viewsets\n\
459         15. Pagination and filtering\n\
460         16. Settings for dev and production\n\
461         17. Environment variable configuration\n\
462         18. Logging configuration\n\
463         19. Tests with Django TestCase\n\
464         20. Static files and media management\n\
465         21. Docker setup\n\
466         22. Requirements.txt\n\
467         Include examples and docstrings following Django conventions."
468    );
469
470    println!("📝 Task: Generate Django Web Application\n");
471    println!("🎯 Django Features:");
472    for criterion in &goal.success_criteria {
473        println!("  ✓ {}", criterion.description);
474    }
475
476    println!("\n⏳ Agent is generating Django app...\n");
477    let response = agent.run(task).await;
478
479    let output = extract_output_text(&response.result());
480    println!("📄 Generated Output:\n");
481    println!("{}\n", output);
482
483    println!("📊 Goal Progress: {}%", goal.get_progress());
484    println!("\n✅ Example 5 completed!\n");
485}
Source

pub fn with_system_prompt(&mut self, prompt: &str) -> &mut Self

Sets a custom system prompt for the agent.

The system prompt defines the agent’s behavior, personality, and instructions. By default, a goal-oriented system prompt is used.

§Arguments
  • prompt - The system prompt text
§Examples
use ceylon_next::agent::Agent;

let mut agent = Agent::new("Assistant", "openai::gpt-4");
agent.with_system_prompt("You are a helpful coding assistant specializing in Rust.");
Examples found in repository?
examples/02_with_tools.rs (lines 143-147)
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 (lines 27-30)
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 (lines 127-132)
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 (lines 18-22)
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 (lines 99-111)
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 32)
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

pub fn get_system_prompt(&self) -> &str

Returns the current system prompt.

§Examples
use ceylon_next::agent::Agent;

let agent = Agent::new("Assistant", "openai::gpt-4");
println!("System prompt: {}", agent.get_system_prompt());
Source

pub fn with_config(&mut self, config: AgentConfig) -> &mut Self

Sets the agent configuration.

§Arguments
§Examples
use ceylon_next::agent::{Agent, AgentConfig};

let mut agent = Agent::new("Assistant", "openai::gpt-4");

let mut config = AgentConfig::new(5, 120);
config.with_goal_analysis(true);

agent.with_config(config);
Examples found in repository?
examples/01_basic_agent.rs (line 24)
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}
More examples
Hide additional examples
examples/04_advanced_agent.rs (line 124)
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_llm_config( &mut self, llm_config: LLMConfig, ) -> Result<&mut Self, String>

Configures the agent with comprehensive LLM settings using LLMConfig.

This allows you to set advanced LLM parameters like temperature, top_p, reasoning, provider-specific options, and more.

§Arguments
  • llm_config - The LLMConfig containing comprehensive LLM settings
§Examples
use ceylon_next::agent::Agent;
use ceylon_next::llm::LLMConfig;

let mut agent = Agent::new("Assistant", "openai::gpt-4");

// Configure with advanced settings
let llm_config = LLMConfig::new("openai::gpt-4")
    .with_api_key("your-api-key")
    .with_temperature(0.7)
    .with_max_tokens(2048)
    .with_top_p(0.9);

agent.with_llm_config(llm_config);
§Provider-Specific Examples
§Azure OpenAI
use ceylon_next::agent::Agent;
use ceylon_next::llm::LLMConfig;

let mut agent = Agent::new("Assistant", "azure::gpt-4");

let config = LLMConfig::new("azure::gpt-4")
    .with_api_key("your-azure-key")
    .with_deployment_id("your-deployment-id")
    .with_api_version("2024-02-01");

agent.with_llm_config(config);
use ceylon_next::agent::Agent;
use ceylon_next::llm::LLMConfig;

let mut agent = Agent::new("Assistant", "openai::gpt-4");

let config = LLMConfig::new("openai::gpt-4")
    .with_api_key("your-api-key")
    .with_openai_web_search(true);

agent.with_llm_config(config);
§Anthropic with Reasoning
use ceylon_next::agent::Agent;
use ceylon_next::llm::LLMConfig;

let mut agent = Agent::new("Assistant", "anthropic::claude-3-opus");

let config = LLMConfig::new("anthropic::claude-3-opus")
    .with_api_key("your-api-key")
    .with_reasoning(true)
    .with_reasoning_effort("high");

agent.with_llm_config(config);
Examples found in repository?
examples/08_llm_providers.rs (line 196)
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}
Source

pub fn add_tool<T>(&mut self, tool: T) -> &mut Self
where T: ToolTrait + Send + Sync + 'static,

Adds a tool to the agent’s toolset.

Tools extend the agent’s capabilities by allowing it to perform external actions like web searches, calculations, database queries, etc.

§Arguments
§Examples
use ceylon_next::agent::Agent;
use ceylon_next::tools::ToolTrait;
use serde_json::{json, Value};

struct WeatherTool;

impl ToolTrait for WeatherTool {
    fn name(&self) -> String { "get_weather".to_string() }
    fn description(&self) -> String { "Get weather for a location".to_string() }
    fn input_schema(&self) -> Value { json!({"type": "object"}) }
    fn execute(&self, input: Value) -> Value { json!({"temp": 72}) }
}

let mut agent = Agent::new("Assistant", "openai::gpt-4");
agent.add_tool(WeatherTool);
Examples found in repository?
examples/02_with_tools.rs (line 151)
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/04_advanced_agent.rs (line 136)
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 115)
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 get_tool_invoker(&self) -> &ToolInvoker

Returns a reference to the agent’s tool invoker.

This can be used to inspect registered tools or invoke them manually.

Source

pub async fn run(&mut self, task: TaskRequest) -> TaskResponse

Executes a task using the agent.

This is the main method for running the agent. It:

  1. Analyzes the task and creates a goal structure (if enabled)
  2. Loads relevant conversation history from memory
  3. Iteratively processes the task with the LLM
  4. Invokes tools as needed
  5. Tracks progress towards goal completion
  6. Saves the conversation to memory
§Arguments
§Returns

A TaskResponse containing the agent’s final output

§Examples
use ceylon_next::agent::Agent;
use ceylon_next::tasks::{TaskRequest, OutputData};

#[tokio::main]
async fn main() {
    let mut agent = Agent::new("Assistant", "openai::gpt-4");

    let task = TaskRequest::new("Write a haiku about Rust");
    let response = agent.run(task).await;

    match response.result() {
        OutputData::Text(text) => println!("{}", text),
        _ => println!("Unexpected output type"),
    }
}
Examples found in repository?
examples/02_with_tools.rs (line 165)
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 40)
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 132)
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 62)
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 (line 83)
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 171)
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}

Trait Implementations§

Source§

impl Clone for Agent

Source§

fn clone(&self) -> Agent

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl Freeze for Agent

§

impl !RefUnwindSafe for Agent

§

impl Send for Agent

§

impl Sync for Agent

§

impl Unpin for Agent

§

impl !UnwindSafe for Agent

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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,