What is Declare Task Failed?

Declare Task Failed is a specialized tool that allows your agent to immediately terminate workflow execution when specific failure conditions are met. This prevents the agent from continuing to attempt a task that cannot be completed, saving time and resources.
In your prompts, always refer to this tool as declare_task_failed (lowercase, with underscores).

Why This Tool Exists

Not all workflow failures are the same. Some errors are recoverable, while others indicate fundamental issues that make task completion impossible:
  • Authentication Failures: Locked accounts or invalid credentials
  • Missing Prerequisites: Required data or systems unavailable
  • Business Rule Violations: Conditions that invalidate the entire process
  • Technical Limitations: System errors that cannot be resolved
  • User-Defined Conditions: Specific scenarios you define as failures
Without declare_task_failed, the agent might spend excessive time trying to work around insurmountable obstacles.

How It Works

  1. The agent encounters a condition you’ve defined as a failure
  2. It calls declare_task_failed with a description of the failure
  3. Workflow execution immediately terminates
  4. The run is marked as failed
  5. No trajectory is saved (the run is not cached)
  6. The failure reason is recorded for debugging
Important: Once declare_task_failed is called, the workflow stops immediately. This tool is never cached because failed runs don’t create trajectories.

When to Use Declare Task Failed

1. Authentication Errors

"If you see 'Account Locked' or 'Invalid Credentials' after attempting login, 
use declare_task_failed to terminate the workflow. Do not attempt 
password recovery or multiple login attempts."

2. Missing Critical Data

"Search for patient ID {patient_id}. If no results are found after searching, 
use declare_task_failed indicating 'Patient ID {patient_id} not found in system'. 
Do not proceed with empty data."

3. System Unavailability

"If the application shows 'System Maintenance in Progress' or fails to load 
after 30 seconds, use declare_task_failed stating 'Target system unavailable'."

4. Business Rule Violations

"Check the account balance before processing. If balance is less than {required_amount}, 
use declare_task_failed with message 'Insufficient funds: balance below required amount'."

How to Prompt for Task Failure

Best Practices

  1. Be Specific: Clearly define what constitutes a failure
  2. Provide Context: Explain why this is a failure condition
  3. Include Messages: Specify what message to include when failing
  4. Set Boundaries: Define how many attempts before failing
  5. Consider Timing: Specify timeouts for time-sensitive operations

Prompt Template

"If [specific condition occurs], use declare_task_failed with message 
'[descriptive failure reason]'. Do not [what not to do]."

Real-World Examples

Healthcare: Patient Safety

"When searching for the patient's medication list, if you see any alert about 
'Drug Interaction Warning - Contraindicated', immediately use declare_task_failed 
with message 'Critical drug interaction detected - manual review required'. 
Do not proceed with the prescription."

Finance: Compliance Checks

"Before initiating the transfer, verify the recipient is not on the sanctions list. 
If the screen shows 'Compliance Alert - Restricted Entity', use declare_task_failed 
stating 'Transfer blocked - recipient on sanctions list'. Do not attempt workarounds."

E-commerce: Inventory Management

"Check inventory for all items in order {order_id}. If any item shows 
'Out of Stock' or 'Discontinued', use declare_task_failed with message 
'Order cannot be fulfilled - {item_name} unavailable'. Do not process partial orders."

IT Operations: Deployment Safety

"Before deploying, check the pre-deployment tests. If status shows 'FAILED' 
for any critical test, use declare_task_failed with 'Deployment aborted - 
critical test failures detected'. Do not override or skip failed tests."

Common Failure Patterns

Multiple Attempt Failures

"Attempt to connect to the database. If connection fails, retry up to 3 times 
with 10-second intervals. If still failing after 3 attempts, use declare_task_failed 
with 'Database connection failed after 3 attempts'."

Timeout Conditions

"Click 'Generate Report' and wait for completion. If the progress bar doesn't 
finish within 5 minutes, use declare_task_failed stating 'Report generation 
timeout - exceeded 5 minute limit'."

Validation Failures

"After filling the form, click Submit. If validation errors appear for required 
fields that cannot be populated from the provided data {input_data}, 
use declare_task_failed listing the missing required fields."

Permission Denials

"Navigate to the admin panel. If you see 'Access Denied' or 'Insufficient Privileges', 
use declare_task_failed with 'User lacks required admin permissions'. 
Do not attempt to access via other routes."

Failure vs. Recovery Strategies

When to Fail vs. Retry

"If login fails with 'Account Locked', use declare_task_failed"
"If the file is corrupted (shows 'Cannot read file'), use declare_task_failed"
"If payment is declined with 'Card Reported Stolen', use declare_task_failed"

Cascading Failures

"The workflow requires sequential approvals from 3 departments. If any department 
shows 'Request Denied' or 'Not Authorized', use declare_task_failed immediately 
with 'Approval chain broken at {department_name}'. Don't continue to other departments."

Integration with Other Tools

With Focused Action

"Use focused_action to check if an error message appears after submission. 
If the error contains 'Fatal', 'Critical', or 'Unrecoverable', 
use declare_task_failed with the full error message."

With Terminal Commands

"Use execute_terminal_command to run 'Test-Path C:\RequiredFiles\config.xml'. 
If it returns False, use declare_task_failed with 'Required configuration file missing'."

Conditional Workflow Paths

"Check the order status. If status is 'Cancelled' or 'Refunded', 
use declare_task_failed with 'Order {order_id} already {status} - no action needed'. 
Only proceed if status is 'Pending' or 'Processing'."

Advanced Usage

Complex Failure Conditions

"Monitor the batch processing progress. Use declare_task_failed if:
1. More than 10% of items fail processing
2. Any critical error (severity = 'CRITICAL') appears in logs
3. Processing time exceeds 30 minutes
4. System memory usage exceeds 90%
Include specific failure reason in the message."

Partial Success Handling

"Process all invoices in the list. Keep track of successes and failures. 
If more than 50% fail, use declare_task_failed with 
'Batch processing failed - {failed_count} of {total_count} invoices failed'. 
Otherwise, complete successfully even with some failures."

Pre-flight Checks

"Before starting the main workflow:
1. Verify all required applications are running
2. Check available disk space > 10GB
3. Confirm network connectivity to required services
If any check fails, use declare_task_failed with specific check that failed. 
This prevents wasting time on doomed workflows."

Best Practices Summary

  1. Define clear, specific failure conditions
  2. Fail fast when recovery is impossible
  3. Include descriptive failure messages
  4. Don’t use for recoverable errors
  5. Consider the business impact of failing vs. continuing
  6. Set reasonable retry limits before failing
  7. Document why each failure condition exists
  8. Test failure scenarios to ensure proper handling

Common Mistakes to Avoid

Don’t use declare_task_failed for:
  • Temporary UI delays (use wait/retry instead)
  • Minor data variations (use focused_action to adapt)
  • Recoverable errors (implement retry logic)
  • Success scenarios (even if no action needed)

❌ Incorrect Usage

"If the page takes more than 2 seconds to load, use declare_task_failed"  // Too aggressive
"If anything goes wrong, use declare_task_failed"                         // Too vague
"After completing successfully, use declare_task_failed"                   // Wrong tool

✅ Correct Usage

"If login fails with 'Account Suspended', use declare_task_failed"
"If required file is missing after checking 3 locations, use declare_task_failed"
"If the API returns 403 Forbidden, use declare_task_failed with 'API access denied'"