pub struct TaskResponse { /* private fields */ }Expand description
The response from an agent after completing a task.
Contains the task ID and the output data produced by the agent.
ยงExamples
use ceylon_next::agent::Agent;
use ceylon_next::tasks::{TaskRequest, OutputData};
let mut agent = Agent::new("Assistant", "openai::gpt-4");
let task = TaskRequest::new("Say hello");
let response = agent.run(task).await;
match response.result() {
OutputData::Text(text) => println!("Agent said: {}", text),
_ => println!("Non-text response"),
}Implementationsยง
Sourceยงimpl TaskResponse
impl TaskResponse
Sourcepub fn result(&self) -> OutputData
pub fn result(&self) -> OutputData
Returns a clone of the output data.
ยงExamples
use ceylon_next::tasks::{TaskResponse, OutputData};
let response = TaskResponse::new("task-123", OutputData::Text("Hello".to_string()));
let output = response.result();Examples found in repository?
examples/02_with_tools.rs (line 168)
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
examples/01_basic_agent.rs (line 43)
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 133)
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/06_nextjs_app_generator.rs (line 86)
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 174)
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/09_test_groq.rs (line 35)
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}Additional examples can be found in:
Sourceยงimpl TaskResponse
impl TaskResponse
Sourcepub fn new(id: &str, output: OutputData) -> Self
pub fn new(id: &str, output: OutputData) -> Self
Creates a new task response.
ยงArguments
id- The ID of the task this is responding tooutput- The output data produced by the agent
Auto Trait Implementationsยง
impl Freeze for TaskResponse
impl RefUnwindSafe for TaskResponse
impl Send for TaskResponse
impl Sync for TaskResponse
impl Unpin for TaskResponse
impl UnwindSafe for TaskResponse
Blanket Implementationsยง
Sourceยงimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Sourceยงfn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Sourceยงimpl<T> Instrument for T
impl<T> Instrument for T
Sourceยงfn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Sourceยงfn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Sourceยงimpl<T> IntoEither for T
impl<T> IntoEither for T
Sourceยงfn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSourceยงfn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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