rcrewai 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,479 @@
1
+ ---
2
+ layout: example
3
+ title: Hierarchical Crew with Manager Coordination
4
+ description: Advanced example showing hierarchical team coordination with manager agents
5
+ ---
6
+
7
+ # Hierarchical Crew with Manager Coordination
8
+
9
+ This example demonstrates RCrewAI's hierarchical execution mode where a manager agent coordinates and delegates tasks to specialist agents. This pattern is ideal for complex workflows requiring coordination, delegation, and strategic oversight.
10
+
11
+ ## Overview
12
+
13
+ We'll create a software development crew with:
14
+ - **Project Manager**: Coordinates team and delegates tasks
15
+ - **Backend Developer**: Handles server-side development tasks
16
+ - **Frontend Developer**: Manages user interface development
17
+ - **QA Engineer**: Ensures quality and testing
18
+ - **DevOps Engineer**: Manages deployment and infrastructure
19
+
20
+ The manager will intelligently delegate tasks based on agent expertise and coordinate the overall project execution.
21
+
22
+ ## Complete Implementation
23
+
24
+ ```ruby
25
+ require 'rcrewai'
26
+
27
+ # Configure RCrewAI
28
+ RCrewAI.configure do |config|
29
+ config.llm_provider = :openai # or your preferred provider
30
+ config.temperature = 0.2 # Lower temperature for more consistent coordination
31
+ end
32
+
33
+ # Create hierarchical crew
34
+ software_team = RCrewAI::Crew.new("software_development_team", process: :hierarchical)
35
+
36
+ # ===== MANAGER AGENT =====
37
+ project_manager = RCrewAI::Agent.new(
38
+ name: "project_manager",
39
+ role: "Senior Technical Project Manager",
40
+ goal: "Coordinate software development projects efficiently and ensure high-quality deliverables",
41
+ backstory: "You are an experienced project manager with 15+ years in software development. You excel at breaking down complex projects, delegating tasks to the right specialists, and ensuring everything comes together seamlessly. You understand each team member's strengths and can provide strategic guidance.",
42
+ manager: true, # Designate as manager
43
+ allow_delegation: true, # Enable task delegation
44
+ tools: [
45
+ RCrewAI::Tools::FileReader.new, # Can review project files
46
+ RCrewAI::Tools::FileWriter.new # Can create project docs
47
+ ],
48
+ verbose: true,
49
+ max_iterations: 8
50
+ )
51
+
52
+ # ===== SPECIALIST AGENTS =====
53
+
54
+ backend_developer = RCrewAI::Agent.new(
55
+ name: "backend_developer",
56
+ role: "Senior Backend Developer",
57
+ goal: "Build robust, scalable backend systems and APIs",
58
+ backstory: "You are a seasoned backend developer with expertise in Ruby, Python, databases, and API design. You excel at creating efficient server-side solutions, optimizing database queries, and ensuring system reliability.",
59
+ tools: [
60
+ RCrewAI::Tools::FileReader.new,
61
+ RCrewAI::Tools::FileWriter.new,
62
+ RCrewAI::Tools::WebSearch.new # For researching best practices
63
+ ],
64
+ verbose: true,
65
+ max_execution_time: 600
66
+ )
67
+
68
+ frontend_developer = RCrewAI::Agent.new(
69
+ name: "frontend_developer",
70
+ role: "Frontend Developer",
71
+ goal: "Create intuitive and responsive user interfaces",
72
+ backstory: "You are a creative frontend developer skilled in React, Vue.js, and modern CSS frameworks. You focus on user experience, accessibility, and creating visually appealing interfaces that users love.",
73
+ tools: [
74
+ RCrewAI::Tools::FileReader.new,
75
+ RCrewAI::Tools::FileWriter.new,
76
+ RCrewAI::Tools::WebSearch.new
77
+ ],
78
+ verbose: true
79
+ )
80
+
81
+ qa_engineer = RCrewAI::Agent.new(
82
+ name: "qa_engineer",
83
+ role: "Quality Assurance Engineer",
84
+ goal: "Ensure software quality through comprehensive testing strategies",
85
+ backstory: "You are a detail-oriented QA engineer with expertise in both manual and automated testing. You excel at finding edge cases, creating comprehensive test plans, and ensuring applications are reliable and user-friendly.",
86
+ tools: [
87
+ RCrewAI::Tools::FileReader.new,
88
+ RCrewAI::Tools::FileWriter.new
89
+ ],
90
+ verbose: true
91
+ )
92
+
93
+ devops_engineer = RCrewAI::Agent.new(
94
+ name: "devops_engineer",
95
+ role: "DevOps Engineer",
96
+ goal: "Manage deployment pipelines and infrastructure efficiently",
97
+ backstory: "You are an experienced DevOps engineer skilled in containerization, CI/CD pipelines, and cloud infrastructure. You ensure smooth deployments and maintain reliable production environments.",
98
+ tools: [
99
+ RCrewAI::Tools::FileReader.new,
100
+ RCrewAI::Tools::FileWriter.new,
101
+ RCrewAI::Tools::WebSearch.new
102
+ ],
103
+ verbose: true
104
+ )
105
+
106
+ # ===== BUILD TEAM HIERARCHY =====
107
+
108
+ # Add manager first
109
+ software_team.add_agent(project_manager)
110
+
111
+ # Add specialists (manager will coordinate them)
112
+ software_team.add_agent(backend_developer)
113
+ software_team.add_agent(frontend_developer)
114
+ software_team.add_agent(qa_engineer)
115
+ software_team.add_agent(devops_engineer)
116
+
117
+ # ===== DEFINE COMPLEX PROJECT TASKS =====
118
+
119
+ # Phase 1: Planning and Architecture
120
+ architecture_task = RCrewAI::Task.new(
121
+ name: "system_architecture",
122
+ description: "Design the overall system architecture for a task management web application. Include database schema, API endpoints, frontend structure, and deployment strategy. Consider scalability, security, and maintainability.",
123
+ expected_output: "Comprehensive system architecture document with diagrams, technology stack decisions, and implementation plan",
124
+ async: true
125
+ )
126
+
127
+ # Phase 2: Backend Development
128
+ backend_api_task = RCrewAI::Task.new(
129
+ name: "backend_api_development",
130
+ description: "Implement the backend API for the task management system. Create RESTful endpoints for user management, task CRUD operations, team collaboration features, and authentication. Include proper error handling and validation.",
131
+ expected_output: "Complete backend API code with endpoints, models, database migrations, and API documentation",
132
+ context: [architecture_task], # Depends on architecture
133
+ async: true
134
+ )
135
+
136
+ database_task = RCrewAI::Task.new(
137
+ name: "database_design",
138
+ description: "Design and implement the database schema for the task management system. Optimize for performance and include proper indexing, relationships, and data integrity constraints.",
139
+ expected_output: "Database schema file, migration scripts, and performance optimization recommendations",
140
+ context: [architecture_task],
141
+ async: true
142
+ )
143
+
144
+ # Phase 3: Frontend Development
145
+ frontend_ui_task = RCrewAI::Task.new(
146
+ name: "frontend_ui_development",
147
+ description: "Create the user interface for the task management application. Build responsive components for task creation, team collaboration, dashboard views, and user management. Ensure excellent UX and accessibility.",
148
+ expected_output: "Complete frontend application with all UI components, routing, and state management",
149
+ context: [architecture_task, backend_api_task],
150
+ async: true
151
+ )
152
+
153
+ # Phase 4: Quality Assurance
154
+ testing_strategy_task = RCrewAI::Task.new(
155
+ name: "testing_strategy",
156
+ description: "Develop comprehensive testing strategy including unit tests, integration tests, and end-to-end testing. Create test cases for all critical user workflows and edge cases.",
157
+ expected_output: "Complete test suite with automated tests, test documentation, and quality assurance checklist",
158
+ context: [backend_api_task, frontend_ui_task],
159
+ async: true
160
+ )
161
+
162
+ # Phase 5: Deployment
163
+ deployment_task = RCrewAI::Task.new(
164
+ name: "deployment_pipeline",
165
+ description: "Set up production-ready deployment pipeline with CI/CD automation. Include containerization, environment configurations, monitoring, and rollback capabilities.",
166
+ expected_output: "Deployment scripts, CI/CD pipeline configuration, monitoring setup, and deployment documentation",
167
+ context: [backend_api_task, frontend_ui_task, testing_strategy_task],
168
+ async: true
169
+ )
170
+
171
+ # Phase 6: Integration and Documentation
172
+ integration_task = RCrewAI::Task.new(
173
+ name: "system_integration",
174
+ description: "Integrate all components and create comprehensive project documentation. Include setup instructions, API documentation, user guides, and maintenance procedures.",
175
+ expected_output: "Fully integrated system with complete documentation package",
176
+ context: [backend_api_task, frontend_ui_task, testing_strategy_task, deployment_task]
177
+ )
178
+
179
+ # ===== ADD TASKS TO CREW =====
180
+ software_team.add_task(architecture_task)
181
+ software_team.add_task(backend_api_task)
182
+ software_team.add_task(database_task)
183
+ software_team.add_task(frontend_ui_task)
184
+ software_team.add_task(testing_strategy_task)
185
+ software_team.add_task(deployment_task)
186
+ software_team.add_task(integration_task)
187
+
188
+ # ===== EXECUTE WITH HIERARCHICAL COORDINATION =====
189
+
190
+ puts "šŸš€ Starting Software Development Project with Hierarchical Team"
191
+ puts "="*60
192
+ puts "Manager: #{project_manager.name}"
193
+ puts "Team: #{[backend_developer, frontend_developer, qa_engineer, devops_engineer].map(&:name).join(', ')}"
194
+ puts "Tasks: #{software_team.tasks.length} tasks with dependencies"
195
+ puts "="*60
196
+
197
+ # Execute with async coordination - manager will:
198
+ # 1. Analyze all tasks and dependencies
199
+ # 2. Create execution phases based on dependencies
200
+ # 3. Delegate tasks to most appropriate specialists
201
+ # 4. Monitor progress and coordinate between phases
202
+ # 5. Handle any failures or blockers
203
+ results = software_team.execute(async: true, max_concurrency: 3)
204
+
205
+ # ===== ANALYZE RESULTS =====
206
+
207
+ puts "\n" + "="*60
208
+ puts "šŸ“Š PROJECT EXECUTION RESULTS"
209
+ puts "="*60
210
+
211
+ puts "Overall Success Rate: #{results[:success_rate]}%"
212
+ puts "Total Tasks: #{results[:total_tasks]}"
213
+ puts "Completed Tasks: #{results[:completed_tasks]}"
214
+ puts "Failed Tasks: #{results[:failed_tasks]}"
215
+ puts "Manager: #{results[:manager]}"
216
+ puts "Process Type: #{results[:process]}"
217
+
218
+ puts "\nšŸ“‹ TASK BREAKDOWN:"
219
+ puts "-"*40
220
+
221
+ results[:results].each_with_index do |task_result, index|
222
+ status_emoji = task_result[:status] == :completed ? "āœ…" : "āŒ"
223
+
224
+ puts "#{index + 1}. #{status_emoji} #{task_result[:task].name}"
225
+ puts " Assigned to: #{task_result[:assigned_agent]}"
226
+ puts " Phase: #{task_result[:phase]}"
227
+ puts " Status: #{task_result[:status]}"
228
+
229
+ if task_result[:status] == :completed
230
+ puts " Result preview: #{task_result[:result][0..100]}..."
231
+ else
232
+ puts " Error: #{task_result[:error]&.message}"
233
+ end
234
+ puts
235
+ end
236
+
237
+ # ===== SAVE PROJECT ARTIFACTS =====
238
+
239
+ puts "\nšŸ’¾ SAVING PROJECT ARTIFACTS:"
240
+ puts "-"*40
241
+
242
+ completed_tasks = results[:results].select { |r| r[:status] == :completed }
243
+
244
+ completed_tasks.each do |task_result|
245
+ filename = "#{task_result[:task].name.gsub(' ', '_')}_result.md"
246
+
247
+ content = <<~CONTENT
248
+ # #{task_result[:task].name.split('_').map(&:capitalize).join(' ')}
249
+
250
+ **Task:** #{task_result[:task].name}
251
+ **Assigned Agent:** #{task_result[:assigned_agent]}
252
+ **Execution Phase:** #{task_result[:phase]}
253
+ **Status:** #{task_result[:status]}
254
+
255
+ ## Result
256
+
257
+ #{task_result[:result]}
258
+
259
+ ---
260
+ Generated by RCrewAI Hierarchical Team
261
+ Manager: #{results[:manager]}
262
+ Execution Date: #{Time.now}
263
+ CONTENT
264
+
265
+ File.write(filename, content)
266
+ puts " āœ… Saved #{filename} (#{content.length} characters)"
267
+ end
268
+
269
+ # ===== MANAGER SUMMARY REPORT =====
270
+
271
+ summary_report = <<~REPORT
272
+ # Software Development Project Summary
273
+
274
+ **Project Manager:** #{results[:manager]}
275
+ **Team Size:** #{software_team.agents.length - 1} specialists
276
+ **Execution Mode:** Hierarchical with Async Coordination
277
+
278
+ ## Project Metrics
279
+ - **Success Rate:** #{results[:success_rate]}%
280
+ - **Total Tasks:** #{results[:total_tasks]}
281
+ - **Completed:** #{results[:completed_tasks]}
282
+ - **Failed:** #{results[:failed_tasks]}
283
+
284
+ ## Team Performance
285
+
286
+ #{software_team.agents.reject(&:is_manager?).map do |agent|
287
+ assigned_tasks = results[:results].select { |r| r[:assigned_agent] == agent.name }
288
+ completed = assigned_tasks.count { |r| r[:status] == :completed }
289
+
290
+ "- **#{agent.name}** (#{agent.role}): #{completed}/#{assigned_tasks.length} tasks completed"
291
+ end.join("\n")}
292
+
293
+ ## Task Execution Phases
294
+
295
+ The manager organized tasks into efficient execution phases:
296
+
297
+ #{results[:results].group_by { |r| r[:phase] }.map do |phase, tasks|
298
+ "### Phase #{phase}\n" + tasks.map { |t| "- #{t[:task].name} (#{t[:status]})" }.join("\n")
299
+ end.join("\n\n")}
300
+
301
+ ## Key Achievements
302
+
303
+ āœ… System architecture designed with scalability in mind
304
+ āœ… Backend API implemented with proper error handling
305
+ āœ… Database optimized for performance
306
+ āœ… Frontend UI created with excellent UX
307
+ āœ… Comprehensive testing strategy developed
308
+ āœ… Production deployment pipeline established
309
+ āœ… All components integrated successfully
310
+
311
+ ## Recommendations
312
+
313
+ Based on the hierarchical execution, the manager recommends:
314
+ 1. Continue using async execution for independent tasks
315
+ 2. Maintain clear task dependencies to optimize workflow
316
+ 3. Regular coordination meetings for complex integrations
317
+ 4. Implement automated quality gates in the CI/CD pipeline
318
+
319
+ ---
320
+ Report generated by RCrewAI Hierarchical Management System
321
+ Date: #{Time.now}
322
+ REPORT
323
+
324
+ File.write("project_summary_report.md", summary_report)
325
+ puts " āœ… Saved project_summary_report.md"
326
+
327
+ puts "\nšŸŽ‰ SOFTWARE DEVELOPMENT PROJECT COMPLETED!"
328
+ puts "The hierarchical team successfully coordinated #{results[:total_tasks]} tasks"
329
+ puts "with #{results[:success_rate]}% success rate using intelligent delegation."
330
+ ```
331
+
332
+ ## Key Features Demonstrated
333
+
334
+ ### 1. **Manager Coordination**
335
+ The project manager:
336
+ - Analyzes task dependencies and creates execution phases
337
+ - Delegates tasks to specialists based on expertise matching
338
+ - Monitors progress across multiple concurrent streams
339
+ - Makes strategic decisions about task prioritization
340
+
341
+ ### 2. **Intelligent Delegation**
342
+ ```ruby
343
+ # Manager automatically delegates based on:
344
+ # - Agent role and expertise keywords
345
+ # - Tool availability and requirements
346
+ # - Current workload and capacity
347
+ # - Task complexity and dependencies
348
+
349
+ # Backend tasks → Backend Developer
350
+ # UI tasks → Frontend Developer
351
+ # Testing tasks → QA Engineer
352
+ # Deployment tasks → DevOps Engineer
353
+ ```
354
+
355
+ ### 3. **Async Coordination**
356
+ ```ruby
357
+ # Tasks execute in coordinated phases:
358
+ # Phase 1: Architecture (foundation)
359
+ # Phase 2: Backend API + Database (parallel)
360
+ # Phase 3: Frontend UI (depends on backend)
361
+ # Phase 4: Testing (depends on implementation)
362
+ # Phase 5: Deployment (depends on testing)
363
+ # Phase 6: Integration (depends on all components)
364
+ ```
365
+
366
+ ### 4. **Failure Management**
367
+ The manager handles failures intelligently:
368
+ - Retries transient failures
369
+ - Reassigns failed tasks to other qualified agents
370
+ - Adjusts execution plan based on bottlenecks
371
+ - Provides detailed failure analysis
372
+
373
+ ## Advanced Coordination Patterns
374
+
375
+ ### Human-in-the-Loop Management
376
+ ```ruby
377
+ # Manager with human oversight for critical decisions
378
+ project_manager = RCrewAI::Agent.new(
379
+ name: "senior_pm",
380
+ role: "Senior Project Manager",
381
+ goal: "Coordinate complex projects with stakeholder input",
382
+ manager: true,
383
+ human_input: true, # Enable human collaboration
384
+ require_approval_for_tools: false, # Manager can use tools freely
385
+ require_approval_for_final_answer: true # Human reviews project decisions
386
+ )
387
+ ```
388
+
389
+ ### Dynamic Team Scaling
390
+ ```ruby
391
+ # Add specialists based on project needs
392
+ if project_requires_mobile?
393
+ mobile_developer = RCrewAI::Agent.new(
394
+ name: "mobile_developer",
395
+ role: "Mobile App Developer",
396
+ goal: "Create native mobile applications",
397
+ tools: [mobile_dev_tools]
398
+ )
399
+
400
+ software_team.add_agent(mobile_developer)
401
+ end
402
+
403
+ if project_requires_ml?
404
+ ml_engineer = RCrewAI::Agent.new(
405
+ name: "ml_engineer",
406
+ role: "Machine Learning Engineer",
407
+ goal: "Implement ML models and data pipelines",
408
+ tools: [ml_tools]
409
+ )
410
+
411
+ software_team.add_agent(ml_engineer)
412
+ end
413
+ ```
414
+
415
+ ### Multi-Manager Hierarchy
416
+ ```ruby
417
+ # Large projects can have multiple manager layers
418
+ engineering_manager = RCrewAI::Agent.new(
419
+ name: "engineering_manager",
420
+ role: "Engineering Manager",
421
+ manager: true,
422
+ allow_delegation: true
423
+ )
424
+
425
+ product_manager = RCrewAI::Agent.new(
426
+ name: "product_manager",
427
+ role: "Product Manager",
428
+ manager: true,
429
+ allow_delegation: true
430
+ )
431
+
432
+ # Both managers coordinate different aspects
433
+ crew.add_agent(engineering_manager) # Technical coordination
434
+ crew.add_agent(product_manager) # Product coordination
435
+ ```
436
+
437
+ ## Performance Optimization
438
+
439
+ ### Concurrent Execution
440
+ - Independent tasks run in parallel
441
+ - Dependencies are automatically resolved
442
+ - Resource usage is optimized across agents
443
+ - Manager monitors and balances workload
444
+
445
+ ### Intelligent Task Routing
446
+ - Tasks routed to most qualified agents
447
+ - Workload balanced across team members
448
+ - Expertise matching improves quality
449
+ - Reduced coordination overhead
450
+
451
+ ## Running the Example
452
+
453
+ 1. **Setup:**
454
+ ```bash
455
+ bundle install
456
+ export OPENAI_API_KEY="your-api-key"
457
+ ```
458
+
459
+ 2. **Execute:**
460
+ ```bash
461
+ ruby hierarchical_crew_example.rb
462
+ ```
463
+
464
+ 3. **Expected Output:**
465
+ - Detailed manager coordination logs
466
+ - Task delegation decisions
467
+ - Phase-by-phase execution progress
468
+ - Individual task results
469
+ - Comprehensive project summary
470
+ - Generated project artifacts
471
+
472
+ This hierarchical pattern is perfect for:
473
+ - **Complex Software Projects**: Multi-component development
474
+ - **Enterprise Workflows**: Requiring coordination and oversight
475
+ - **Multi-Disciplinary Teams**: Different expertise areas
476
+ - **Quality-Critical Projects**: Needing management oversight
477
+ - **Large-Scale Operations**: Requiring delegation and coordination
478
+
479
+ The manager agent acts as an intelligent orchestrator, making strategic decisions about task delegation while maintaining oversight of the entire project workflow.