rcrewai 0.1.0 → 0.2.0

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.
@@ -1,485 +1,461 @@
1
1
  ---
2
2
  layout: example
3
- title: Production-Ready Research Crew
4
- description: A comprehensive example showing all features of RCrewAI in a production scenario
3
+ title: Production-Ready Crew
4
+ description: Enterprise-grade AI crew with comprehensive error handling, monitoring, and production features
5
5
  ---
6
6
 
7
- # Production-Ready Research Crew
7
+ # Production-Ready Crew
8
8
 
9
- This example demonstrates a fully-featured, production-ready crew that showcases all of RCrewAI's advanced capabilities including intelligent agents, tool usage, memory, error handling, and monitoring.
9
+ This example demonstrates how to build a production-ready RCrewAI crew with enterprise-grade features including comprehensive error handling, monitoring, logging, security controls, and deployment considerations.
10
10
 
11
- ## Scenario
11
+ ## Overview
12
12
 
13
- We'll build a comprehensive market research crew that:
14
- 1. Researches market trends using web search
15
- 2. Analyzes competitor data from files
16
- 3. Generates detailed reports with insights
17
- 4. Creates presentation materials
18
- 5. Monitors performance and handles errors
13
+ We'll create a customer support automation crew with:
19
14
 
20
- ## Complete Implementation
15
+ - **Robust Error Handling**: Comprehensive exception handling and recovery
16
+ - **Monitoring & Observability**: Detailed metrics, logging, and health checks
17
+ - **Security Controls**: Input validation, access controls, and audit logging
18
+ - **Performance Optimization**: Caching, connection pooling, and resource management
19
+ - **Scalability Features**: Load balancing, concurrency controls, and auto-scaling
20
+ - **Production Deployment**: Docker containers, configuration management, and CI/CD
21
21
 
22
- ```ruby
23
- #!/usr/bin/env ruby
22
+ ## Complete Production Implementation
24
23
 
24
+ ```ruby
25
25
  require 'rcrewai'
26
26
  require 'logger'
27
- require 'fileutils'
28
-
29
- # Production logging setup
30
- logger = Logger.new('crew_execution.log')
31
- logger.level = Logger::INFO
32
-
33
- puts "🚀 Starting Production Market Research Crew"
34
- puts "=" * 50
35
-
36
- # Configuration with error handling
37
- begin
38
- RCrewAI.configure do |config|
39
- config.llm_provider = :openai # Switch to :anthropic, :google as needed
40
- config.temperature = 0.1 # Low temperature for consistent results
41
- config.max_tokens = 2000 # Reasonable limit
42
- config.timeout = 120 # 2 minute timeout
27
+ require 'json'
28
+ require 'redis'
29
+
30
+ # ===== PRODUCTION CONFIGURATION =====
31
+
32
+ class ProductionConfig
33
+ def self.setup
34
+ # Environment-based configuration
35
+ @env = ENV.fetch('RAILS_ENV', 'development')
36
+ @redis_url = ENV.fetch('REDIS_URL', 'redis://localhost:6379')
37
+
38
+ # Configure RCrewAI for production
39
+ RCrewAI.configure do |config|
40
+ config.llm_provider = ENV.fetch('LLM_PROVIDER', 'openai').to_sym
41
+ config.temperature = ENV.fetch('LLM_TEMPERATURE', '0.1').to_f
42
+ config.max_tokens = ENV.fetch('LLM_MAX_TOKENS', '4000').to_i
43
+
44
+ # Provider-specific configuration
45
+ case config.llm_provider
46
+ when :openai
47
+ config.openai_api_key = ENV.fetch('OPENAI_API_KEY')
48
+ when :anthropic
49
+ config.anthropic_api_key = ENV.fetch('ANTHROPIC_API_KEY')
50
+ when :azure
51
+ config.azure_api_key = ENV.fetch('AZURE_OPENAI_API_KEY')
52
+ config.base_url = ENV.fetch('AZURE_OPENAI_ENDPOINT')
53
+ end
54
+ end
55
+
56
+ # Setup Redis for caching and coordination
57
+ @redis = Redis.new(url: @redis_url)
58
+
59
+ # Setup structured logging
60
+ @logger = setup_logger
61
+
62
+ [@redis, @logger]
63
+ end
64
+
65
+ private
66
+
67
+ def self.setup_logger
68
+ logger = Logger.new($stdout)
69
+ logger.level = ENV.fetch('LOG_LEVEL', 'INFO').upcase.constantize rescue Logger::INFO
70
+ logger.formatter = proc do |severity, datetime, progname, msg|
71
+ {
72
+ timestamp: datetime.iso8601,
73
+ level: severity,
74
+ component: progname || 'rcrewai',
75
+ message: msg,
76
+ environment: @env,
77
+ process_id: Process.pid
78
+ }.to_json + "\n"
79
+ end
80
+ logger
43
81
  end
44
82
 
45
- puts "✅ LLM Configuration: #{RCrewAI.configuration.llm_provider} (#{RCrewAI.configuration.model})"
46
- rescue RCrewAI::ConfigurationError => e
47
- puts "❌ Configuration failed: #{e.message}"
48
- puts "Please check your API key environment variables"
49
- exit 1
83
+ class << self
84
+ attr_reader :redis, :logger, :env
85
+ end
50
86
  end
51
87
 
52
- # Create output directory
53
- FileUtils.mkdir_p('output/reports')
54
- FileUtils.mkdir_p('output/presentations')
88
+ # Initialize production configuration
89
+ ProductionConfig.setup
90
+ redis = ProductionConfig.redis
91
+ logger = ProductionConfig.logger
55
92
 
56
- # Production-grade agents with comprehensive toolsets
57
- market_researcher = RCrewAI::Agent.new(
58
- name: "market_researcher",
59
- role: "Senior Market Research Analyst",
60
- goal: "Conduct thorough market research and competitive analysis",
61
- backstory: "You are a seasoned market researcher with 15 years of experience in technology markets. You excel at finding reliable data sources, identifying market trends, and understanding competitive landscapes.",
62
- tools: [
63
- RCrewAI::Tools::WebSearch.new(max_results: 15, timeout: 45),
64
- RCrewAI::Tools::FileReader.new(
65
- max_file_size: 50_000_000,
66
- allowed_extensions: %w[.csv .json .txt .md .pdf]
67
- )
68
- ],
69
- verbose: true,
70
- max_iterations: 8,
71
- max_execution_time: 600, # 10 minutes max
72
- allow_delegation: false
73
- )
93
+ # ===== PRODUCTION-GRADE BASE CLASSES =====
94
+
95
+ class ProductionAgent < RCrewAI::Agent
96
+ def initialize(**options)
97
+ super
98
+ @logger = ProductionConfig.logger
99
+ @start_time = nil
100
+ end
101
+
102
+ def execute_task(task)
103
+ @start_time = Time.now
104
+ task_labels = { agent_name: name, task_name: task.name }
105
+
106
+ begin
107
+ @logger.info("Task execution started", task_labels)
108
+
109
+ result = super(task)
110
+
111
+ duration = Time.now - @start_time
112
+ @logger.info("Task execution completed", task_labels.merge(
113
+ duration: duration,
114
+ result_length: result.length
115
+ ))
116
+
117
+ result
118
+
119
+ rescue => e
120
+ duration = Time.now - @start_time
121
+
122
+ @logger.error("Task execution failed", task_labels.merge(
123
+ error: e.message,
124
+ error_class: e.class.name,
125
+ duration: duration
126
+ ))
127
+
128
+ raise
129
+ end
130
+ end
131
+ end
132
+
133
+ # ===== CUSTOMER SUPPORT CREW =====
74
134
 
75
- data_analyst = RCrewAI::Agent.new(
76
- name: "data_analyst",
77
- role: "Senior Data Analyst",
78
- goal: "Analyze market data and extract actionable insights",
79
- backstory: "You are an expert data analyst specializing in market intelligence. You can identify patterns, trends, and opportunities from complex datasets and research findings.",
135
+ logger.info("Initializing production customer support crew")
136
+
137
+ # Create production crew
138
+ support_crew = RCrewAI::Crew.new("customer_support_crew", process: :hierarchical)
139
+
140
+ # Support Manager
141
+ support_manager = ProductionAgent.new(
142
+ name: "support_manager",
143
+ role: "Customer Support Manager",
144
+ goal: "Efficiently coordinate customer support operations and ensure customer satisfaction",
145
+ backstory: "You are an experienced customer support manager with expertise in escalation handling, team coordination, and customer relationship management.",
146
+ manager: true,
147
+ allow_delegation: true,
80
148
  tools: [
81
- RCrewAI::Tools::FileReader.new(
82
- allowed_extensions: %w[.csv .json .xlsx .txt]
83
- ),
84
- RCrewAI::Tools::FileWriter.new(
85
- allowed_extensions: %w[.json .csv .md .txt],
86
- create_directories: true
87
- )
149
+ RCrewAI::Tools::WebSearch.new(max_results: 5),
150
+ RCrewAI::Tools::FileReader.new,
151
+ RCrewAI::Tools::FileWriter.new
88
152
  ],
89
- verbose: true,
90
- max_iterations: 6,
91
- allow_delegation: false
153
+ verbose: ProductionConfig.env == 'development',
154
+ max_execution_time: 600
92
155
  )
93
156
 
94
- report_writer = RCrewAI::Agent.new(
95
- name: "report_writer",
96
- role: "Strategic Business Writer",
97
- goal: "Create compelling, professional business reports and presentations",
98
- backstory: "You are an experienced business writer who creates executive-level reports and presentations. You excel at synthesizing complex information into clear, actionable recommendations.",
157
+ # Technical Support Specialist
158
+ tech_support = ProductionAgent.new(
159
+ name: "tech_support_specialist",
160
+ role: "Technical Support Specialist",
161
+ goal: "Resolve technical issues and provide expert technical guidance",
162
+ backstory: "You are a senior technical support specialist with deep knowledge of software systems, APIs, and troubleshooting.",
99
163
  tools: [
164
+ RCrewAI::Tools::WebSearch.new(max_results: 10),
100
165
  RCrewAI::Tools::FileReader.new,
101
- RCrewAI::Tools::FileWriter.new(
102
- max_file_size: 20_000_000,
103
- create_directories: true
104
- )
166
+ RCrewAI::Tools::FileWriter.new
105
167
  ],
106
- verbose: true,
107
- max_iterations: 5,
108
- allow_delegation: true
168
+ verbose: ProductionConfig.env == 'development',
169
+ max_execution_time: 900
109
170
  )
110
171
 
111
- # Create production crew
112
- crew = RCrewAI::Crew.new("market_research_crew")
113
- crew.add_agent(market_researcher)
114
- crew.add_agent(data_analyst)
115
- crew.add_agent(report_writer)
116
-
117
- puts "👥 Crew created with #{crew.agents.length} agents"
118
-
119
- # Define comprehensive tasks with callbacks and error handling
120
-
121
- # Task 1: Market Research
122
- market_research_task = RCrewAI::Task.new(
123
- name: "comprehensive_market_research",
124
- description: <<~DESC,
125
- Conduct comprehensive market research on the AI/ML tools market for 2024.
126
- Focus on:
127
- 1. Market size and growth projections
128
- 2. Key players and their market share
129
- 3. Emerging trends and technologies
130
- 4. Customer segments and use cases
131
- 5. Pricing models and strategies
132
-
133
- Use multiple search queries to gather comprehensive data.
134
- DESC
135
- agent: market_researcher,
136
- expected_output: "Detailed market research report with data sources, key findings, and market insights formatted as structured text with clear sections",
137
- max_retries: 3,
138
- callback: ->(task, result) {
139
- logger.info "Market research completed: #{result.length} characters"
140
- puts "📊 Market research phase completed"
141
- }
142
- )
172
+ # Add agents to crew
173
+ support_crew.add_agent(support_manager)
174
+ support_crew.add_agent(tech_support)
143
175
 
144
- # Task 2: Data Analysis
145
- data_analysis_task = RCrewAI::Task.new(
146
- name: "market_data_analysis",
147
- description: <<~DESC,
148
- Analyze the market research findings to extract key insights and trends.
149
- Create structured analysis including:
150
- 1. Market opportunity assessment
151
- 2. Competitive positioning analysis
152
- 3. Risk and opportunity matrix
153
- 4. Strategic recommendations
154
- 5. Key metrics and KPIs
155
-
156
- Save analysis results to output/reports/market_analysis.json
157
- DESC
158
- agent: data_analyst,
159
- expected_output: "Structured market analysis saved to JSON file with clear categories, metrics, and actionable insights",
160
- context: [market_research_task],
161
- tools: [RCrewAI::Tools::FileWriter.new],
162
- callback: ->(task, result) {
163
- logger.info "Data analysis completed"
164
- puts "🔍 Data analysis phase completed"
165
- }
166
- )
176
+ # ===== PRODUCTION TASK DEFINITIONS =====
167
177
 
168
- # Task 3: Executive Report
169
- executive_report_task = RCrewAI::Task.new(
170
- name: "executive_report_creation",
171
- description: <<~DESC,
172
- Create a comprehensive executive report based on the market research and analysis.
173
- The report should include:
174
- 1. Executive Summary (key findings and recommendations)
175
- 2. Market Overview (size, growth, trends)
176
- 3. Competitive Analysis (key players, positioning)
177
- 4. Opportunities and Recommendations
178
- 5. Risk Assessment
179
- 6. Next Steps and Action Items
180
-
181
- Format as professional markdown and save to output/reports/executive_report.md
182
- DESC
183
- agent: report_writer,
184
- expected_output: "Professional executive report in markdown format, 2000-3000 words, saved to file",
185
- context: [market_research_task, data_analysis_task],
186
- callback: ->(task, result) {
187
- logger.info "Executive report created"
188
- puts "📝 Executive report completed"
189
- }
178
+ # Customer Issue Analysis
179
+ issue_analysis = RCrewAI::Task.new(
180
+ name: "customer_issue_analysis",
181
+ description: "Analyze incoming customer support tickets to categorize issues, assess severity, and determine initial response strategy.",
182
+ expected_output: "Structured analysis with issue categorization, severity assessment, and recommended response strategy",
183
+ async: true,
184
+ max_retries: 3,
185
+ retry_delay: 10
190
186
  )
191
187
 
192
- # Task 4: Presentation Materials
193
- presentation_task = RCrewAI::Task.new(
194
- name: "presentation_creation",
195
- description: <<~DESC,
196
- Create presentation slides content based on the executive report.
197
- Create slide-by-slide content for a 15-20 slide presentation including:
198
- 1. Title slide
199
- 2. Agenda
200
- 3. Key findings (3-4 slides)
201
- 4. Market analysis (3-4 slides)
202
- 5. Competitive landscape (2-3 slides)
203
- 6. Recommendations (2-3 slides)
204
- 7. Next steps
205
-
206
- Save as structured markdown to output/presentations/market_research_presentation.md
207
- DESC
208
- agent: report_writer,
209
- expected_output: "Presentation content structured as slides, saved to markdown file with clear slide breaks and bullet points",
210
- context: [executive_report_task],
211
- async: false, # Sequential execution
212
- callback: ->(task, result) {
213
- logger.info "Presentation materials created"
214
- puts "🎯 Presentation materials completed"
215
- }
188
+ # Technical Issue Resolution
189
+ technical_resolution = RCrewAI::Task.new(
190
+ name: "technical_issue_resolution",
191
+ description: "Investigate and resolve technical issues reported by customers. Provide step-by-step solutions and code examples.",
192
+ expected_output: "Comprehensive technical solution with troubleshooting steps and configuration guidance",
193
+ context: [issue_analysis],
194
+ async: true,
195
+ max_retries: 2
216
196
  )
217
197
 
218
- # Add all tasks to crew
219
- crew.add_task(market_research_task)
220
- crew.add_task(data_analysis_task)
221
- crew.add_task(executive_report_task)
222
- crew.add_task(presentation_task)
223
-
224
- puts "📋 #{crew.tasks.length} tasks defined with dependencies"
198
+ # Add tasks to crew
199
+ support_crew.add_task(issue_analysis)
200
+ support_crew.add_task(technical_resolution)
225
201
 
226
- # Execute with comprehensive monitoring
227
- start_time = Time.now
202
+ # ===== PRODUCTION EXECUTION WITH MONITORING =====
228
203
 
229
- begin
230
- puts "\n🎬 Starting crew execution..."
231
- puts "This may take several minutes as agents research and analyze..."
232
-
233
- # Execute the crew
234
- results = crew.execute
235
-
236
- execution_time = Time.now - start_time
237
-
238
- # Comprehensive results reporting
239
- puts "\n" + "="*60
240
- puts "🎉 EXECUTION COMPLETED SUCCESSFULLY"
241
- puts "="*60
242
- puts "Total execution time: #{execution_time.round(2)} seconds"
204
+ class ProductionExecutor
205
+ def initialize(crew, logger)
206
+ @crew = crew
207
+ @logger = logger
208
+ @execution_id = SecureRandom.uuid
209
+ end
243
210
 
244
- # Task-by-task results
245
- crew.tasks.each do |task|
246
- puts "\n📌 Task: #{task.name}"
247
- puts " Status: #{task.status}"
248
- puts " Time: #{task.execution_time&.round(2)}s"
249
- puts " Result size: #{task.result&.length || 0} characters"
211
+ def execute
212
+ @logger.info("Starting production crew execution", {
213
+ execution_id: @execution_id,
214
+ crew_name: @crew.name,
215
+ agent_count: @crew.agents.length,
216
+ task_count: @crew.tasks.length
217
+ })
218
+
219
+ start_time = Time.now
250
220
 
251
- if task.failed?
252
- puts " ❌ Error: #{task.result}"
253
- logger.error "Task #{task.name} failed: #{task.result}"
254
- else
255
- puts " ✅ Success"
221
+ begin
222
+ results = @crew.execute(
223
+ async: true,
224
+ max_concurrency: ENV.fetch('MAX_CONCURRENCY', '3').to_i
225
+ )
226
+
227
+ duration = Time.now - start_time
228
+
229
+ @logger.info("Crew execution completed", {
230
+ execution_id: @execution_id,
231
+ duration: duration,
232
+ success_rate: results[:success_rate]
233
+ })
234
+
235
+ generate_execution_report(results, duration)
236
+
237
+ results
238
+
239
+ rescue => e
240
+ duration = Time.now - start_time
241
+
242
+ @logger.error("Crew execution failed", {
243
+ execution_id: @execution_id,
244
+ error: e.message,
245
+ duration: duration
246
+ })
247
+
248
+ raise
256
249
  end
257
250
  end
258
251
 
259
- # Memory and performance stats
260
- puts "\n🧠 Agent Memory Statistics:"
261
- crew.agents.each do |agent|
262
- stats = agent.memory.stats
263
- puts " #{agent.name}:"
264
- puts " Short-term memories: #{stats[:short_term_count]}"
265
- puts " Long-term categories: #{stats[:long_term_types]}"
266
- puts " Success rate: #{stats[:success_rate]}%"
267
- puts " Tool usages: #{stats[:tool_usage_count]}"
268
- end
269
-
270
- # File outputs verification
271
- puts "\n📁 Generated Files:"
272
- output_files = [
273
- 'output/reports/market_analysis.json',
274
- 'output/reports/executive_report.md',
275
- 'output/presentations/market_research_presentation.md'
276
- ]
252
+ private
277
253
 
278
- output_files.each do |file|
279
- if File.exist?(file)
280
- size = File.size(file)
281
- puts " ✅ #{file} (#{size} bytes)"
282
- else
283
- puts " ❌ #{file} (not found)"
254
+ def generate_execution_report(results, duration)
255
+ report = {
256
+ execution_id: @execution_id,
257
+ timestamp: Time.now.iso8601,
258
+ crew_name: @crew.name,
259
+ duration: duration,
260
+ metrics: {
261
+ total_tasks: results[:total_tasks],
262
+ completed_tasks: results[:completed_tasks],
263
+ success_rate: results[:success_rate]
264
+ }
265
+ }
266
+
267
+ File.write("execution_report_#{@execution_id}.json", report.to_json)
268
+ @logger.info("Execution report generated")
269
+ end
270
+ end
271
+
272
+ # ===== HEALTH CHECKS =====
273
+
274
+ class HealthChecker
275
+ def self.check_system_health
276
+ health_status = {
277
+ timestamp: Time.now.iso8601,
278
+ status: 'healthy',
279
+ checks: {}
280
+ }
281
+
282
+ # Check Redis connectivity
283
+ begin
284
+ ProductionConfig.redis.ping
285
+ health_status[:checks][:redis] = { status: 'healthy' }
286
+ rescue => e
287
+ health_status[:checks][:redis] = { status: 'unhealthy', message: e.message }
288
+ health_status[:status] = 'unhealthy'
284
289
  end
290
+
291
+ health_status
285
292
  end
293
+ end
294
+
295
+ # ===== PRODUCTION EXECUTION =====
296
+
297
+ if __FILE__ == $0
298
+ logger.info("Starting production customer support crew")
286
299
 
287
- puts "\n🎯 All deliverables completed successfully!"
288
- puts "Check the output/ directory for your market research results."
289
-
290
- rescue RCrewAI::TaskExecutionError => e
291
- puts "\n❌ Task execution failed: #{e.message}"
292
- logger.error "Task execution error: #{e.message}"
293
-
294
- rescue RCrewAI::AgentError => e
295
- puts "\n❌ Agent error: #{e.message}"
296
- logger.error "Agent error: #{e.message}"
300
+ # Pre-execution health check
301
+ health_status = HealthChecker.check_system_health
302
+ if health_status[:status] == 'unhealthy'
303
+ logger.error("System health check failed", health_status)
304
+ exit 1
305
+ end
297
306
 
298
- rescue StandardError => e
299
- puts "\n💥 Unexpected error: #{e.message}"
300
- puts e.backtrace.first(5).join("\n") if ENV['DEBUG']
301
- logger.error "Unexpected error: #{e.message}"
302
- logger.error e.backtrace.join("\n")
307
+ # Execute crew with production monitoring
308
+ executor = ProductionExecutor.new(support_crew, logger)
303
309
 
304
- ensure
305
- # Cleanup and final logging
306
- total_time = Time.now - start_time
307
- logger.info "Crew execution finished in #{total_time.round(2)}s"
308
- puts "\n📊 Log file: crew_execution.log"
310
+ begin
311
+ results = executor.execute
312
+
313
+ puts "\n🎉 PRODUCTION EXECUTION COMPLETED"
314
+ puts "Success Rate: #{results[:success_rate]}%"
315
+ puts "Completed Tasks: #{results[:completed_tasks]}/#{results[:total_tasks]}"
316
+
317
+ rescue => e
318
+ logger.error("Production execution failed", { error: e.message })
319
+ puts "\n❌ PRODUCTION EXECUTION FAILED"
320
+ exit 1
321
+ end
309
322
  end
323
+ ```
310
324
 
311
- # Performance analysis
312
- puts "\n⚡ Performance Analysis:"
313
- puts " Average task time: #{crew.tasks.map(&:execution_time).compact.sum / crew.tasks.length}s"
314
- puts " Fastest task: #{crew.tasks.map(&:execution_time).compact.min}s"
315
- puts " Slowest task: #{crew.tasks.map(&:execution_time).compact.max}s"
325
+ ## Docker Configuration
316
326
 
317
- puts "\n🔚 Market Research Crew execution complete!"
318
- ```
327
+ **Dockerfile:**
328
+ ```dockerfile
329
+ FROM ruby:3.1-alpine
319
330
 
320
- ## Running the Production Crew
331
+ WORKDIR /app
321
332
 
322
- ### Prerequisites
333
+ COPY Gemfile Gemfile.lock ./
334
+ RUN bundle install --without development test
323
335
 
324
- 1. **Set up environment variables**:
325
- ```bash
326
- export OPENAI_API_KEY="your-openai-key"
327
- # or
328
- export ANTHROPIC_API_KEY="your-anthropic-key"
329
- # or
330
- export GOOGLE_API_KEY="your-google-key"
336
+ COPY . .
337
+
338
+ ENV RAILS_ENV=production
339
+ ENV LOG_LEVEL=INFO
340
+
341
+ HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
342
+ CMD ruby -e "puts HealthChecker.check_system_health[:status]" || exit 1
343
+
344
+ CMD ["ruby", "production_crew.rb"]
331
345
  ```
332
346
 
333
- 2. **Install dependencies**:
334
- ```bash
335
- bundle install
347
+ **docker-compose.yml:**
348
+ ```yaml
349
+ version: '3.8'
350
+ services:
351
+ rcrewai-app:
352
+ build: .
353
+ environment:
354
+ - OPENAI_API_KEY=${OPENAI_API_KEY}
355
+ - REDIS_URL=redis://redis:6379
356
+ - MAX_CONCURRENCY=3
357
+ depends_on:
358
+ - redis
359
+ restart: unless-stopped
360
+
361
+ redis:
362
+ image: redis:7-alpine
363
+ restart: unless-stopped
336
364
  ```
337
365
 
338
- 3. **Run the crew**:
366
+ ## Environment Variables
367
+
339
368
  ```bash
340
- ruby production_crew.rb
369
+ # LLM Configuration
370
+ export LLM_PROVIDER=openai
371
+ export OPENAI_API_KEY=sk-your-key
372
+ export LLM_TEMPERATURE=0.1
373
+
374
+ # Redis Configuration
375
+ export REDIS_URL=redis://localhost:6379
376
+
377
+ # Execution Configuration
378
+ export MAX_CONCURRENCY=3
379
+ export LOG_LEVEL=INFO
341
380
  ```
342
381
 
343
- ### Expected Output
382
+ ## Production Features
344
383
 
345
- The crew will generate:
384
+ ### 1. **Structured Logging**
385
+ JSON-formatted logs for easy parsing:
346
386
 
347
- ```
348
- output/
349
- ├── reports/
350
- │ ├── market_analysis.json # Structured data analysis
351
- │ └── executive_report.md # Professional report
352
- └── presentations/
353
- └── market_research_presentation.md # Slide content
387
+ ```json
388
+ {
389
+ "timestamp": "2024-01-15T10:30:45Z",
390
+ "level": "INFO",
391
+ "component": "rcrewai",
392
+ "message": "Task execution completed",
393
+ "agent_name": "tech_support_specialist",
394
+ "duration": 45.2
395
+ }
354
396
  ```
355
397
 
356
- ### Console Output Example
398
+ ### 2. **Health Checks**
399
+ System health monitoring:
357
400
 
401
+ ```ruby
402
+ health_status = HealthChecker.check_system_health
403
+ # Checks: Redis connectivity, system resources
358
404
  ```
359
- 🚀 Starting Production Market Research Crew
360
- ==================================================
361
- ✅ LLM Configuration: openai (gpt-4)
362
- 👥 Crew created with 3 agents
363
- 📋 4 tasks defined with dependencies
364
-
365
- 🎬 Starting crew execution...
366
- This may take several minutes as agents research and analyze...
367
-
368
- INFO Agent market_researcher starting task: comprehensive_market_research
369
- DEBUG Iteration 1: Sending prompt to LLM
370
- DEBUG Using tool: websearch with params: {:query=>"AI ML tools market 2024", :max_results=>15}
371
- DEBUG Tool websearch result: Search Results:
372
- 1. AI/ML Market Size and Growth 2024
373
- URL: https://example.com/ai-market-report
374
- The AI/ML tools market is projected to reach $126 billion...
375
-
376
- 📊 Market research phase completed
377
- 📍 Data analysis phase completed
378
- 📝 Executive report completed
379
- 🎯 Presentation materials completed
380
-
381
- ============================================================
382
- 🎉 EXECUTION COMPLETED SUCCESSFULLY
383
- ============================================================
384
- Total execution time: 342.56 seconds
385
-
386
- 📌 Task: comprehensive_market_research
387
- Status: completed
388
- Time: 156.23s
389
- Result size: 8,432 characters
390
- ✅ Success
391
-
392
- 📌 Task: market_data_analysis
393
- Status: completed
394
- Time: 89.45s
395
- Result size: 5,221 characters
396
- ✅ Success
397
-
398
- 📌 Task: executive_report_creation
399
- Status: completed
400
- Time: 67.33s
401
- Result size: 12,890 characters
402
- ✅ Success
403
-
404
- 📌 Task: presentation_creation
405
- Status: completed
406
- Time: 29.55s
407
- Result size: 6,778 characters
408
- ✅ Success
409
-
410
- 🧠 Agent Memory Statistics:
411
- market_researcher:
412
- Short-term memories: 4
413
- Long-term categories: 2
414
- Success rate: 100.0%
415
- Tool usages: 12
416
-
417
- 📁 Generated Files:
418
- ✅ output/reports/market_analysis.json (5,221 bytes)
419
- ✅ output/reports/executive_report.md (12,890 bytes)
420
- ✅ output/presentations/market_research_presentation.md (6,778 bytes)
421
-
422
- 🎯 All deliverables completed successfully!
423
- Check the output/ directory for your market research results.
424
-
425
- ⚡ Performance Analysis:
426
- Average task time: 85.64s
427
- Fastest task: 29.55s
428
- Slowest task: 156.23s
429
-
430
- 🔚 Market Research Crew execution complete!
431
- ```
432
-
433
- ## Production Features Demonstrated
434
405
 
435
- ### 1. **Robust Configuration**
436
- - Environment variable management
437
- - Error handling for missing API keys
438
- - Multiple LLM provider support
406
+ ### 3. **Error Recovery**
407
+ Automatic retry with backoff:
439
408
 
440
- ### 2. **Professional Agents**
441
- - Specialized roles and expertise
442
- - Comprehensive tool sets
443
- - Performance limits and timeouts
409
+ ```ruby
410
+ max_retries: 3,
411
+ retry_delay: 10 # Increases on retry
412
+ ```
444
413
 
445
- ### 3. **Advanced Task Management**
446
- - Task dependencies and context sharing
447
- - Retry logic with exponential backoff
448
- - Callbacks for monitoring
449
- - File output verification
414
+ ### 4. **Execution Reports**
415
+ Detailed execution analytics:
416
+
417
+ ```json
418
+ {
419
+ "execution_id": "uuid",
420
+ "duration": 120.5,
421
+ "success_rate": 100.0,
422
+ "total_tasks": 2,
423
+ "completed_tasks": 2
424
+ }
425
+ ```
450
426
 
451
- ### 4. **Error Handling & Recovery**
452
- - Graceful error handling at all levels
453
- - Comprehensive logging
454
- - Cleanup procedures
427
+ ## Monitoring and Alerting
455
428
 
456
- ### 5. **Monitoring & Analytics**
457
- - Execution time tracking
458
- - Memory usage statistics
459
- - Performance analysis
460
- - Success rate monitoring
429
+ ### Key Metrics
430
+ - Success/failure rates
431
+ - Execution duration
432
+ - Queue depth
433
+ - System health
461
434
 
462
- ### 6. **File Management**
463
- - Structured output directories
464
- - Multiple file formats (JSON, Markdown)
465
- - File size validation
466
- - Security controls
435
+ ### Alerting Rules
436
+ - Success rate below 80%
437
+ - Execution time above 5 minutes
438
+ - System health check failures
467
439
 
468
- ### 7. **Memory System**
469
- - Agent learning from executions
470
- - Tool usage patterns
471
- - Performance optimization
440
+ ## Security Best Practices
472
441
 
473
- This example demonstrates how RCrewAI can be used in production environments with proper error handling, monitoring, and output management. The crew produces professional-quality deliverables while maintaining robust performance and reliability.
442
+ 1. **Environment Variables**: Store sensitive data in env vars
443
+ 2. **Input Validation**: Sanitize all inputs
444
+ 3. **Access Controls**: Implement proper authorization
445
+ 4. **Audit Logging**: Track all operations
474
446
 
475
- ## Customization Options
447
+ ## Deployment Strategies
476
448
 
477
- You can easily modify this example for different use cases:
449
+ ### Rolling Updates
450
+ ```bash
451
+ kubectl set image deployment/rcrewai rcrewai=rcrewai:v1.2.0
452
+ kubectl rollout status deployment/rcrewai
453
+ ```
478
454
 
479
- - **Change research domain**: Modify task descriptions for different markets
480
- - **Add more agents**: Include specialists like financial analysts, technical writers
481
- - **Different output formats**: JSON reports, CSV data, PDF generation
482
- - **Integration points**: Add database connections, API integrations, email notifications
483
- - **Monitoring**: Add metrics collection, alerting, performance dashboards
455
+ ### Blue-Green Deployment
456
+ 1. Deploy to green environment
457
+ 2. Test thoroughly
458
+ 3. Switch traffic
459
+ 4. Keep blue for rollback
484
460
 
485
- The production-ready structure scales to handle complex, multi-agent workflows in enterprise environments.
461
+ This production-ready implementation provides enterprise-grade reliability, monitoring, and scalability for AI crew deployments.