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.
data/docs/api/task.md ADDED
@@ -0,0 +1,494 @@
1
+ ---
2
+ layout: api
3
+ title: RCrewAI::Task
4
+ description: API documentation for the Task class
5
+ ---
6
+
7
+ # RCrewAI::Task
8
+
9
+ The Task class represents individual units of work that agents execute. Tasks define what needs to be done, expected outputs, dependencies, and execution parameters.
10
+
11
+ ## Constructor
12
+
13
+ ### `new(name:, description:, **options)`
14
+
15
+ Creates a new task instance.
16
+
17
+ **Required Parameters:**
18
+ - `name` (String) - Unique identifier for the task
19
+ - `description` (String) - Detailed description of what the task should accomplish
20
+
21
+ **Optional Parameters:**
22
+ - `agent` (RCrewAI::Agent) - Agent assigned to execute this task
23
+ - `expected_output` (String) - Description of expected result format/content
24
+ - `context` (Array) - Array of tasks this task depends on
25
+ - `tools` (Array) - Specific tools available for this task (in addition to agent tools)
26
+ - `callback` (Proc) - Callback function called after task completion
27
+ - `max_retries` (Integer) - Maximum retry attempts on failure (default: 3)
28
+ - `retry_delay` (Integer) - Delay between retries in seconds (default: 5)
29
+ - `timeout` (Integer) - Task execution timeout in seconds (default: 300)
30
+ - `human_input` (Boolean) - Enable human interaction for this task (default: false)
31
+ - `require_confirmation` (Boolean) - Require human confirmation before starting
32
+ - `allow_guidance` (Boolean) - Allow human guidance during execution
33
+ - `human_review_points` (Array) - Points where human review is requested ([:completion, :error])
34
+ - `async` (Boolean) - Whether task can be executed asynchronously (default: false)
35
+
36
+ **Returns:** `RCrewAI::Task` instance
37
+
38
+ **Example:**
39
+ ```ruby
40
+ task = RCrewAI::Task.new(
41
+ name: "market_research",
42
+ description: "Research competitor landscape and pricing strategies for our new AI product",
43
+ agent: research_agent,
44
+ expected_output: "Comprehensive market analysis report with competitor pricing matrix and strategic recommendations",
45
+ context: [data_collection_task], # Depends on data collection
46
+ tools: [RCrewAI::Tools::WebSearch.new(max_results: 15)], # Task-specific tools
47
+ max_retries: 2,
48
+ timeout: 600,
49
+ human_input: true,
50
+ require_confirmation: true,
51
+ callback: ->(task, result) {
52
+ puts "Market research completed: #{result.length} characters"
53
+ NotificationService.notify("Research completed for #{task.name}")
54
+ }
55
+ )
56
+ ```
57
+
58
+ ## Instance Methods
59
+
60
+ ### `#execute`
61
+
62
+ Executes the task with the assigned agent.
63
+
64
+ **Returns:** String containing the task result
65
+
66
+ **Raises:**
67
+ - `RCrewAI::TaskExecutionError` - If task execution fails
68
+ - `RCrewAI::TaskDependencyError` - If dependencies are not met
69
+
70
+ **Example:**
71
+ ```ruby
72
+ begin
73
+ result = task.execute
74
+ puts "Task completed successfully: #{result[0..100]}..."
75
+ rescue RCrewAI::TaskExecutionError => e
76
+ puts "Task failed: #{e.message}"
77
+ puts "Retry count: #{task.retry_count}"
78
+ rescue RCrewAI::TaskDependencyError => e
79
+ puts "Dependencies not met: #{e.message}"
80
+ end
81
+ ```
82
+
83
+ ### `#add_context_task(task)`
84
+
85
+ Adds a dependency task to this task's context.
86
+
87
+ **Parameters:**
88
+ - `task` (RCrewAI::Task) - Task to add as dependency
89
+
90
+ **Returns:** `self`
91
+
92
+ **Example:**
93
+ ```ruby
94
+ research_task = RCrewAI::Task.new(name: "research", description: "Research topic")
95
+ analysis_task = RCrewAI::Task.new(name: "analysis", description: "Analyze research")
96
+
97
+ analysis_task.add_context_task(research_task)
98
+ # Now analysis_task will wait for research_task to complete
99
+ ```
100
+
101
+ ### `#add_tool(tool)`
102
+
103
+ Adds a tool specific to this task.
104
+
105
+ **Parameters:**
106
+ - `tool` (RCrewAI::Tools::Base) - Tool instance to add
107
+
108
+ **Returns:** `self`
109
+
110
+ **Example:**
111
+ ```ruby
112
+ custom_api_tool = MyCustomAPITool.new(api_key: ENV['API_KEY'])
113
+ task.add_tool(custom_api_tool)
114
+ ```
115
+
116
+ ### `#dependencies_met?`
117
+
118
+ Checks if all dependency tasks are completed.
119
+
120
+ **Returns:** Boolean
121
+
122
+ **Example:**
123
+ ```ruby
124
+ if task.dependencies_met?
125
+ result = task.execute
126
+ else
127
+ puts "Waiting for dependencies: #{task.pending_dependencies.map(&:name)}"
128
+ end
129
+ ```
130
+
131
+ ### `#context_data`
132
+
133
+ Returns formatted context data from dependency tasks.
134
+
135
+ **Returns:** String containing context from completed dependency tasks
136
+
137
+ **Example:**
138
+ ```ruby
139
+ puts task.context_data
140
+ # Output includes results from all completed context tasks
141
+ ```
142
+
143
+ ### `#enable_human_input(**options)`
144
+
145
+ Enables human interaction for this task.
146
+
147
+ **Parameters:**
148
+ - `require_confirmation` (Boolean) - Require confirmation before starting
149
+ - `allow_guidance` (Boolean) - Allow guidance during execution
150
+ - `human_review_points` (Array) - Review points ([:completion, :error, :midpoint])
151
+
152
+ **Returns:** `self`
153
+
154
+ **Example:**
155
+ ```ruby
156
+ task.enable_human_input(
157
+ require_confirmation: true,
158
+ allow_guidance: true,
159
+ human_review_points: [:completion, :error]
160
+ )
161
+ ```
162
+
163
+ ### `#disable_human_input`
164
+
165
+ Disables human interaction for this task.
166
+
167
+ **Returns:** `self`
168
+
169
+ ## Attributes
170
+
171
+ ### `name` (readonly)
172
+ The task's unique name.
173
+
174
+ **Type:** String
175
+
176
+ ### `description` (readonly)
177
+ Detailed description of the task.
178
+
179
+ **Type:** String
180
+
181
+ ### `expected_output` (readonly)
182
+ Description of expected output format/content.
183
+
184
+ **Type:** String
185
+
186
+ ### `agent`
187
+ The agent assigned to execute this task.
188
+
189
+ **Type:** RCrewAI::Agent
190
+
191
+ ### `context`
192
+ Array of dependency tasks.
193
+
194
+ **Type:** Array<RCrewAI::Task>
195
+
196
+ ### `tools`
197
+ Task-specific tools (in addition to agent tools).
198
+
199
+ **Type:** Array
200
+
201
+ ### `status`
202
+ Current execution status.
203
+
204
+ **Type:** Symbol (`:pending`, `:running`, `:completed`, `:failed`)
205
+
206
+ ### `result`
207
+ The task execution result.
208
+
209
+ **Type:** String
210
+
211
+ ### `start_time`
212
+ When task execution started.
213
+
214
+ **Type:** Time
215
+
216
+ ### `end_time`
217
+ When task execution completed.
218
+
219
+ **Type:** Time
220
+
221
+ ### `execution_time`
222
+ Total execution time in seconds.
223
+
224
+ **Type:** Float
225
+
226
+ ### `retry_count`
227
+ Number of retry attempts made.
228
+
229
+ **Type:** Integer
230
+
231
+ ### `error_message`
232
+ Error message if task failed.
233
+
234
+ **Type:** String
235
+
236
+ ### `human_input`
237
+ Whether human input is enabled.
238
+
239
+ **Type:** Boolean
240
+
241
+ ### `async`
242
+ Whether task supports async execution.
243
+
244
+ **Type:** Boolean
245
+
246
+ ## Task States and Lifecycle
247
+
248
+ Tasks progress through several states:
249
+
250
+ 1. **`:pending`** - Initial state, waiting to be executed
251
+ 2. **`:running`** - Currently being executed by an agent
252
+ 3. **`:completed`** - Successfully completed with result
253
+ 4. **`:failed`** - Failed after all retry attempts
254
+
255
+ ```ruby
256
+ # Check task status
257
+ case task.status
258
+ when :pending
259
+ puts "Task is waiting to be executed"
260
+ when :running
261
+ puts "Task is currently being executed"
262
+ when :completed
263
+ puts "Task completed successfully"
264
+ puts "Result: #{task.result}"
265
+ puts "Execution time: #{task.execution_time}s"
266
+ when :failed
267
+ puts "Task failed: #{task.error_message}"
268
+ puts "Retry attempts: #{task.retry_count}"
269
+ end
270
+ ```
271
+
272
+ ## Task Dependencies
273
+
274
+ Tasks can depend on other tasks, creating execution order:
275
+
276
+ ```ruby
277
+ # Create task chain
278
+ data_collection = RCrewAI::Task.new(
279
+ name: "collect_data",
280
+ description: "Collect raw data from various sources",
281
+ agent: data_collector
282
+ )
283
+
284
+ data_processing = RCrewAI::Task.new(
285
+ name: "process_data",
286
+ description: "Clean and process collected data",
287
+ agent: data_processor,
288
+ context: [data_collection] # Depends on data collection
289
+ )
290
+
291
+ analysis = RCrewAI::Task.new(
292
+ name: "analyze_data",
293
+ description: "Analyze processed data for insights",
294
+ agent: data_analyst,
295
+ context: [data_processing] # Depends on data processing
296
+ )
297
+
298
+ report_generation = RCrewAI::Task.new(
299
+ name: "generate_report",
300
+ description: "Generate final report with visualizations",
301
+ agent: report_generator,
302
+ context: [analysis] # Depends on analysis
303
+ )
304
+
305
+ # Tasks will execute in dependency order:
306
+ # data_collection → data_processing → analysis → report_generation
307
+ ```
308
+
309
+ ## Task-Specific Tools
310
+
311
+ Tasks can have their own tools in addition to agent tools:
312
+
313
+ ```ruby
314
+ # Task with specialized tools
315
+ api_integration_task = RCrewAI::Task.new(
316
+ name: "integrate_api",
317
+ description: "Integrate with external API and process data",
318
+ agent: integration_agent,
319
+ tools: [
320
+ CustomAPIClient.new(base_url: ENV['API_URL'], api_key: ENV['API_KEY']),
321
+ DataValidator.new(schema_path: './schemas/api_response.json'),
322
+ RCrewAI::Tools::FileWriter.new(allowed_extensions: ['.json', '.csv'])
323
+ ]
324
+ )
325
+
326
+ # Agent will have access to both its own tools and task-specific tools
327
+ ```
328
+
329
+ ## Human-in-the-Loop Tasks
330
+
331
+ Tasks can integrate human oversight at various points:
332
+
333
+ ```ruby
334
+ critical_task = RCrewAI::Task.new(
335
+ name: "deploy_model",
336
+ description: "Deploy ML model to production environment",
337
+ agent: deployment_agent,
338
+ human_input: true,
339
+ require_confirmation: true, # Human must approve before starting
340
+ allow_guidance: true, # Human can provide guidance during execution
341
+ human_review_points: [:completion], # Human reviews final result
342
+ callback: ->(task, result) {
343
+ if result.include?("DEPLOYED SUCCESSFULLY")
344
+ SlackNotifier.notify("🚀 Model deployed successfully!")
345
+ end
346
+ }
347
+ )
348
+
349
+ # Execution flow with human interaction:
350
+ # 1. Human confirms task start
351
+ # 2. Agent begins deployment process
352
+ # 3. Human provides guidance if needed
353
+ # 4. Human reviews deployment result
354
+ # 5. Callback notifies team of success
355
+ ```
356
+
357
+ ## Async Task Execution
358
+
359
+ Tasks can be marked for asynchronous execution:
360
+
361
+ ```ruby
362
+ # Tasks that can run in parallel
363
+ parallel_tasks = [
364
+ RCrewAI::Task.new(
365
+ name: "market_research",
366
+ description: "Research market trends",
367
+ agent: researcher,
368
+ async: true # Can run concurrently
369
+ ),
370
+
371
+ RCrewAI::Task.new(
372
+ name: "competitor_analysis",
373
+ description: "Analyze competitor strategies",
374
+ agent: analyst,
375
+ async: true # Can run concurrently
376
+ ),
377
+
378
+ RCrewAI::Task.new(
379
+ name: "technical_review",
380
+ description: "Review technical specifications",
381
+ agent: tech_reviewer,
382
+ async: true # Can run concurrently
383
+ )
384
+ ]
385
+
386
+ # These tasks can execute simultaneously
387
+ crew.add_task(parallel_tasks)
388
+ results = crew.execute(async: true, max_concurrency: 3)
389
+ ```
390
+
391
+ ## Task Callbacks and Events
392
+
393
+ Tasks can execute callbacks at various lifecycle events:
394
+
395
+ ```ruby
396
+ task = RCrewAI::Task.new(
397
+ name: "data_analysis",
398
+ description: "Analyze customer data for insights",
399
+ agent: analyst,
400
+
401
+ # Callbacks for different events
402
+ on_start: ->(task) {
403
+ puts "Starting analysis: #{task.name}"
404
+ MetricsTracker.task_started(task.name)
405
+ },
406
+
407
+ on_progress: ->(task, progress) {
408
+ puts "Progress: #{progress}% complete"
409
+ ProgressBar.update(task.name, progress)
410
+ },
411
+
412
+ on_completion: ->(task, result) {
413
+ puts "Analysis completed: #{result.length} chars"
414
+ ResultStore.save(task.name, result)
415
+ EmailNotifier.send_completion_notice(task.name)
416
+ },
417
+
418
+ on_error: ->(task, error) {
419
+ puts "Task failed: #{error.message}"
420
+ ErrorTracker.log_error(task.name, error)
421
+ AlertSystem.notify_failure(task.name)
422
+ }
423
+ )
424
+ ```
425
+
426
+ ## Retry Logic and Error Handling
427
+
428
+ Tasks have built-in retry capabilities:
429
+
430
+ ```ruby
431
+ resilient_task = RCrewAI::Task.new(
432
+ name: "api_data_sync",
433
+ description: "Sync data with external API",
434
+ agent: sync_agent,
435
+ max_retries: 5, # Try up to 5 times
436
+ retry_delay: 10, # Wait 10 seconds between retries
437
+ timeout: 120, # Timeout after 2 minutes
438
+
439
+ # Custom retry logic
440
+ retry_if: ->(error) {
441
+ # Retry on network errors, but not on authentication errors
442
+ error.is_a?(Net::TimeoutError) || error.is_a?(Net::ReadTimeout)
443
+ }
444
+ )
445
+
446
+ # Task will automatically retry on transient failures
447
+ result = resilient_task.execute
448
+ ```
449
+
450
+ ## Task Monitoring and Metrics
451
+
452
+ ```ruby
453
+ # Task execution with monitoring
454
+ task = RCrewAI::Task.new(
455
+ name: "report_generation",
456
+ description: "Generate monthly performance report",
457
+ agent: report_agent,
458
+
459
+ # Built-in metrics
460
+ track_metrics: true,
461
+
462
+ # Custom monitoring
463
+ callback: ->(task, result) {
464
+ # Record performance metrics
465
+ TaskMetrics.record(
466
+ task_name: task.name,
467
+ execution_time: task.execution_time,
468
+ result_size: result.length,
469
+ agent_name: task.agent.name,
470
+ success: task.status == :completed
471
+ )
472
+ }
473
+ )
474
+
475
+ # After execution
476
+ puts "Task metrics:"
477
+ puts "- Execution time: #{task.execution_time}s"
478
+ puts "- Retry attempts: #{task.retry_count}"
479
+ puts "- Result size: #{task.result.length} characters"
480
+ puts "- Agent used: #{task.agent.name}"
481
+ ```
482
+
483
+ ## Best Practices
484
+
485
+ 1. **Clear Descriptions**: Write detailed, specific task descriptions
486
+ 2. **Expected Outputs**: Define what the result should look like
487
+ 3. **Proper Dependencies**: Use context to establish task execution order
488
+ 4. **Appropriate Tools**: Provide task-specific tools when needed
489
+ 5. **Human Oversight**: Enable human input for critical tasks
490
+ 6. **Error Handling**: Set appropriate retry limits and timeouts
491
+ 7. **Async Where Possible**: Mark independent tasks as async for performance
492
+ 8. **Monitoring**: Use callbacks to track task performance and results
493
+ 9. **Resource Limits**: Set reasonable timeouts to prevent hanging
494
+ 10. **Result Validation**: Validate task outputs match expected format