RCrewAI::Task
API documentation for the Task class
RCrewAI::Task
The Task class represents individual units of work that agents execute. Tasks define what needs to be done, expected outputs, dependencies, and execution parameters.
Constructor
new(name:, description:, **options)
Creates a new task instance.
Required Parameters:
name(String) - Unique identifier for the taskdescription(String) - Detailed description of what the task should accomplish
Optional Parameters:
agent(RCrewAI::Agent) - Agent assigned to execute this taskexpected_output(String) - Description of expected result format/contentcontext(Array) - Array of tasks this task depends ontools(Array) - Specific tools available for this task (in addition to agent tools)callback(Proc) - Callback function called after task completionmax_retries(Integer) - Maximum retry attempts on failure (default: 3)retry_delay(Integer) - Delay between retries in seconds (default: 5)timeout(Integer) - Task execution timeout in seconds (default: 300)human_input(Boolean) - Enable human interaction for this task (default: false)require_confirmation(Boolean) - Require human confirmation before startingallow_guidance(Boolean) - Allow human guidance during executionhuman_review_points(Array) - Points where human review is requested ([:completion, :error])async(Boolean) - Whether task can be executed asynchronously (default: false)output_schema(Hash) - A JSON-schema subset the output is validated/coerced against; parsed result on#structured_output(raw string on#raw_result). Non-conforming output re-runs the agent with the error fed backguardrail(callable) -->(output) { [ok, value_or_error] }to validate/transform output before it flows downstreamguardrail_max_retries(Integer) - Guardrail retries with the reason fed back (default: 3)output_file(String) - Path to write the result to after completioncreate_directory(Boolean) - Create the output file’s parent dirs (default: true)markdown(Boolean) - Prepend a heading when the output isn’t already markdown (default: false)attachments(Array) - Multimodal image inputs, e.g.[{ type: :image, path: 'x.png' }]or{ type: :image, url: '...' }(OpenAI/Azure). See Advanced Agent Options
Returns: RCrewAI::Task instance
Example:
task = RCrewAI::Task.new(
name: "market_research",
description: "Research competitor landscape and pricing strategies for our new AI product",
agent: research_agent,
expected_output: "Comprehensive market analysis report with competitor pricing matrix and strategic recommendations",
context: [data_collection_task], # Depends on data collection
tools: [RCrewAI::Tools::WebSearch.new(max_results: 15)], # Task-specific tools
max_retries: 2,
timeout: 600,
human_input: true,
require_confirmation: true,
callback: ->(task, result) {
puts "Market research completed: #{result.length} characters"
NotificationService.notify("Research completed for #{task.name}")
}
)
Instance Methods
#execute
Executes the task with the assigned agent.
Returns: String containing the task result
Raises:
RCrewAI::TaskExecutionError- If task execution failsRCrewAI::TaskDependencyError- If dependencies are not met
Example:
begin
result = task.execute
puts "Task completed successfully: #{result[0..100]}..."
rescue RCrewAI::TaskExecutionError => e
puts "Task failed: #{e.message}"
rescue RCrewAI::TaskDependencyError => e
puts "Dependencies not met: #{e.message}"
end
#add_context_task(task)
Adds a dependency task to this task’s context.
Parameters:
task(RCrewAI::Task) - Task to add as dependency
Returns: self
Example:
research_task = RCrewAI::Task.new(name: "research", description: "Research topic")
analysis_task = RCrewAI::Task.new(name: "analysis", description: "Analyze research")
analysis_task.add_context_task(research_task)
# Now analysis_task will wait for research_task to complete
#add_tool(tool)
Adds a tool specific to this task.
Parameters:
tool(RCrewAI::Tools::Base) - Tool instance to add
Returns: self
Example:
custom_api_tool = MyCustomAPITool.new(api_key: ENV['API_KEY'])
task.add_tool(custom_api_tool)
#dependencies_met?
Checks if all dependency tasks are completed.
Returns: Boolean
Example:
if task.dependencies_met?
result = task.execute
else
puts "Waiting for dependencies: #{task.context.reject(&:completed?).map(&:name)}"
end
#context_data
Returns formatted context data from dependency tasks.
Returns: String containing context from completed dependency tasks
Example:
puts task.context_data
# Output includes results from all completed context tasks
#enable_human_input(**options)
Enables human interaction for this task.
Parameters:
require_confirmation(Boolean) - Require confirmation before startingallow_guidance(Boolean) - Allow guidance during executionhuman_review_points(Array) - Review points ([:completion, :error, :midpoint])
Returns: self
Example:
task.enable_human_input(
require_confirmation: true,
allow_guidance: true,
human_review_points: [:completion, :error]
)
#disable_human_input
Disables human interaction for this task.
Returns: self
Attributes
name (readonly)
The task’s unique name.
Type: String
description (readonly)
Detailed description of the task.
Type: String
expected_output (readonly)
Description of expected output format/content.
Type: String
agent
The agent assigned to execute this task.
Type: RCrewAI::Agent
context
Array of dependency tasks.
Type: Array<RCrewAI::Task>
tools
Task-specific tools (in addition to agent tools).
Type: Array
status
Current execution status.
Type: Symbol (:pending, :running, :completed, :failed)
result
The task execution result.
Type: String
start_time
When task execution started.
Type: Time
end_time
When task execution completed.
Type: Time
execution_time
Total execution time in seconds.
Type: Float
async
Whether task supports async execution.
Type: Boolean
Task States and Lifecycle
Tasks progress through several states:
:pending- Initial state, waiting to be executed:running- Currently being executed by an agent:completed- Successfully completed with result:failed- Failed after all retry attempts
# Check task status
case task.status
when :pending
puts "Task is waiting to be executed"
when :running
puts "Task is currently being executed"
when :completed
puts "Task completed successfully"
puts "Result: #{task.result}"
puts "Execution time: #{task.execution_time}s"
when :failed
puts "Task failed: #{task.result}"
end
Task Dependencies
Tasks can depend on other tasks, creating execution order:
# Create task chain
data_collection = RCrewAI::Task.new(
name: "collect_data",
description: "Collect raw data from various sources",
agent: data_collector
)
data_processing = RCrewAI::Task.new(
name: "process_data",
description: "Clean and process collected data",
agent: data_processor,
context: [data_collection] # Depends on data collection
)
analysis = RCrewAI::Task.new(
name: "analyze_data",
description: "Analyze processed data for insights",
agent: data_analyst,
context: [data_processing] # Depends on data processing
)
report_generation = RCrewAI::Task.new(
name: "generate_report",
description: "Generate final report with visualizations",
agent: report_generator,
context: [analysis] # Depends on analysis
)
# Tasks will execute in dependency order:
# data_collection → data_processing → analysis → report_generation
Task-Specific Tools
Tasks can have their own tools in addition to agent tools:
# Task with specialized tools
api_integration_task = RCrewAI::Task.new(
name: "integrate_api",
description: "Integrate with external API and process data",
agent: integration_agent,
tools: [
CustomAPIClient.new(base_url: ENV['API_URL'], api_key: ENV['API_KEY']),
DataValidator.new(schema_path: './schemas/api_response.json'),
RCrewAI::Tools::FileWriter.new(allowed_extensions: ['.json', '.csv'])
]
)
# Agent will have access to both its own tools and task-specific tools
Human-in-the-Loop Tasks
Tasks can integrate human oversight at various points:
critical_task = RCrewAI::Task.new(
name: "deploy_model",
description: "Deploy ML model to production environment",
agent: deployment_agent,
human_input: true,
require_confirmation: true, # Human must approve before starting
allow_guidance: true, # Human can provide guidance during execution
human_review_points: [:completion], # Human reviews final result
callback: ->(task, result) {
if result.include?("DEPLOYED SUCCESSFULLY")
SlackNotifier.notify("🚀 Model deployed successfully!")
end
}
)
# Execution flow with human interaction:
# 1. Human confirms task start
# 2. Agent begins deployment process
# 3. Human provides guidance if needed
# 4. Human reviews deployment result
# 5. Callback notifies team of success
Async Task Execution
Tasks can be marked for asynchronous execution:
# Tasks that can run in parallel
parallel_tasks = [
RCrewAI::Task.new(
name: "market_research",
description: "Research market trends",
agent: researcher,
async: true # Can run concurrently
),
RCrewAI::Task.new(
name: "competitor_analysis",
description: "Analyze competitor strategies",
agent: analyst,
async: true # Can run concurrently
),
RCrewAI::Task.new(
name: "technical_review",
description: "Review technical specifications",
agent: tech_reviewer,
async: true # Can run concurrently
)
]
# These tasks can execute simultaneously
crew.add_task(parallel_tasks)
results = crew.execute(async: true, max_concurrency: 3)
Task Callbacks
callback: runs once when the task completes. Use crew.execute events for finer-grained progress.
task = RCrewAI::Task.new(
name: "data_analysis",
description: "Analyze customer data for insights",
agent: analyst,
callback: ->(task, result) {
ResultStore.save(task.name, result)
puts "Finished in #{task.execution_time}s"
}
)
Retries
max_retries: sets how many times a failed task is retried (default: 2). Retries back off exponentially. There’s no per-task timeout or retry condition.
resilient_task = RCrewAI::Task.new(
name: "api_data_sync",
description: "Sync data with external API",
agent: sync_agent,
max_retries: 5
)
Best Practices
- Clear Descriptions: Write detailed, specific task descriptions
- Expected Outputs: Define what the result should look like
- Proper Dependencies: Use context to establish task execution order
- Appropriate Tools: Provide task-specific tools when needed
- Human Oversight: Enable human input for critical tasks
- Error Handling: Set appropriate retry limits
- Async Where Possible: Mark independent tasks as async for performance
- Monitoring: Use callbacks to track task performance and results
- Result Validation: Validate task outputs match expected format