> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agent-corex.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool Execution Flow Examples

> Learn how tools are executed in sequential order, in parallel batches, and with comprehensive error handling and failure recovery mechanisms

## Tool Execution Flow Examples

This page shows how to structure tool execution flows for real-world scenarios.

***

## Sequential Execution

Execute tools one after another:

```javascript theme={null}
const workflow = async () => {
  // Step 1: Retrieve tools
  const tools = await agent.retrieveTools({
    query: "Deploy Node.js app, test it, and notify team"
  });

  // Step 2: Build application
  console.log('📦 Building...');
  const buildResult = await agent.executeTool({
    toolName: 'docker-build',
    params: {
      dockerfile: './Dockerfile',
      tag: 'myapp:latest'
    }
  });

  // Step 3: Run tests
  console.log('🧪 Testing...');
  const testResult = await agent.executeTool({
    toolName: 'run-test-suite',
    params: {
      image: buildResult.imageUri,
      coverage: true
    }
  });

  if (testResult.failed > 0) {
    throw new Error(`Tests failed: ${testResult.failed}`);
  }

  // Step 4: Deploy
  console.log('🚀 Deploying...');
  const deployResult = await agent.executeTool({
    toolName: 'deploy-aws-ecs',
    params: {
      image: buildResult.imageUri,
      environment: 'production'
    }
  });

  // Step 5: Notify
  console.log('📢 Notifying...');
  await agent.executeTool({
    toolName: 'send-slack-message',
    params: {
      channel: '#deployments',
      message: `✅ Deployed successfully!`
    }
  });

  console.log('✨ Done!');
};

await workflow();
```

***

## Parallel Execution

Execute multiple tools simultaneously:

```javascript theme={null}
const parallelWorkflow = async () => {
  const tools = await agent.retrieveTools({
    query: "Get logs, check metrics, update dashboard"
  });

  // Execute all in parallel
  const [logs, metrics, dashboard] = await Promise.all([
    agent.executeTool({
      toolName: 'query-logs',
      params: {
        service: 'api',
        timeRange: '-1h'
      }
    }),
    agent.executeTool({
      toolName: 'query-metrics',
      params: {
        service: 'api',
        metrics: ['cpu', 'memory', 'latency']
      }
    }),
    agent.executeTool({
      toolName: 'update-dashboard',
      params: {
        dashboardId: 'prod-metrics'
      }
    })
  ]);

  console.log('✅ All tasks completed:');
  console.log(`  Logs: ${logs.entries.length} entries`);
  console.log(`  Metrics: CPU ${metrics.cpu}%`);
  console.log(`  Dashboard: Updated`);
};

await parallelWorkflow();
```

***

## Conditional Execution

Execute based on results:

```javascript theme={null}
const conditionalWorkflow = async () => {
  // Get deployment tools
  const deployTools = await agent.retrieveTools({
    query: "Deploy and monitor"
  });

  // Check current status
  const status = await agent.executeTool({
    toolName: 'check-service-health',
    params: { service: 'api' }
  });

  if (status.healthy) {
    console.log('✅ Service already healthy');
    return;
  }

  console.log('⚠️ Service unhealthy, deploying fix...');

  // Deploy fix
  const deployResult = await agent.executeTool({
    toolName: 'deploy-latest-version',
    params: {
      service: 'api',
      environment: 'production'
    }
  });

  // Verify health after deploy
  const newStatus = await agent.executeTool({
    toolName: 'check-service-health',
    params: { service: 'api' }
  });

  if (newStatus.healthy) {
    console.log('✅ Service recovered!');
  } else {
    console.log('❌ Service still unhealthy, escalating...');
    
    // Escalate to human
    await agent.executeTool({
      toolName: 'create-incident-ticket',
      params: {
        project: 'OPS',
        title: 'Automated recovery failed'
      }
    });
  }
};

await conditionalWorkflow();
```

***

## Error Handling & Retry

Handle failures gracefully:

```javascript theme={null}
const retryableWorkflow = async () => {
  const executeWithRetry = async (
    toolName,
    params,
    maxRetries = 3
  ) => {
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        console.log(`Attempt ${attempt}/${maxRetries}...`);
        return await agent.executeTool({
          toolName,
          params,
          timeout: 30000
        });
      } catch (error) {
        console.error(`Attempt ${attempt} failed: ${error.message}`);

        if (attempt === maxRetries) {
          throw error;
        }

        // Exponential backoff
        const delay = Math.pow(2, attempt - 1) * 1000;
        console.log(`Waiting ${delay}ms before retry...`);
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  };

  try {
    const result = await executeWithRetry(
      'deploy-aws-lambda',
      {
        function: 'my-function',
        code: 'build/function.zip'
      }
    );
    console.log('✅ Deployment succeeded');
  } catch (error) {
    console.error('❌ Deployment failed after retries');
  }
};

await retryableWorkflow();
```

***

## Multi-Tool Orchestration

Complex workflow with multiple tools:

```javascript theme={null}
const orchestratedWorkflow = async () => {
  const tools = await agent.retrieveTools({
    query: "Create GitHub issue, add to Jira, assign to team, notify Slack"
  });

  const issue = {
    title: 'Critical bug in production',
    description: 'Users reporting errors in payment flow',
    severity: 'critical'
  };

  try {
    // Create GitHub issue
    console.log('📝 Creating GitHub issue...');
    const ghIssue = await agent.executeTool({
      toolName: 'create-github-issue',
      params: {
        repository: 'company/api',
        title: issue.title,
        body: issue.description,
        labels: ['bug', 'critical', 'production']
      }
    });

    // Create Jira ticket
    console.log('📋 Creating Jira ticket...');
    const jiraTicket = await agent.executeTool({
      toolName: 'create-jira-issue',
      params: {
        project: 'PLATFORM',
        title: issue.title,
        description: issue.description,
        priority: 'Highest'
      }
    });

    // Link GitHub to Jira
    console.log('🔗 Linking issues...');
    await agent.executeTool({
      toolName: 'link-github-to-jira',
      params: {
        githubUrl: ghIssue.url,
        jiraKey: jiraTicket.key
      }
    });

    // Assign to backend team
    console.log('👥 Assigning to team...');
    const teamMembers = await agent.executeTool({
      toolName: 'get-oncall-engineer',
      params: {
        team: 'backend'
      }
    });

    await agent.executeTool({
      toolName: 'assign-jira-issue',
      params: {
        issueKey: jiraTicket.key,
        assignee: teamMembers.engineer.email
      }
    });

    // Notify on Slack
    console.log('🔔 Notifying team...');
    await agent.executeTool({
      toolName: 'send-slack-message',
      params: {
        channel: '#incidents',
        message: `🚨 CRITICAL ISSUE\n${issue.title}\nGH: ${ghIssue.url}\nJira: ${jiraTicket.url}\nAssigned: @${teamMembers.engineer.slack}`,
        mentionUsers: [teamMembers.engineer.slack]
      }
    });

    console.log('✅ All tools executed successfully');
    return {
      github: ghIssue,
      jira: jiraTicket,
      assignee: teamMembers.engineer
    };

  } catch (error) {
    console.error('❌ Workflow failed:', error.message);
    
    // Cleanup or escalate
    await agent.executeTool({
      toolName: 'send-slack-message',
      params: {
        channel: '#engineering',
        message: `⚠️ Workflow automation failed: ${error.message}`
      }
    });
    
    throw error;
  }
};

await orchestratedWorkflow();
```

***

## Workflow Patterns

| Pattern          | Use Case                  | Example                   |
| ---------------- | ------------------------- | ------------------------- |
| **Sequential**   | Steps must run in order   | Build → Test → Deploy     |
| **Parallel**     | Independent tasks         | Get logs, metrics, status |
| **Conditional**  | Run based on state        | If unhealthy, deploy fix  |
| **Retry**        | Handle transient failures | API timeouts              |
| **Orchestrated** | Complex multi-step        | Issue tracking workflow   |

***

## Best Practices

✅ **DO:**

* Handle each tool error individually
* Implement exponential backoff for retries
* Log meaningful messages at each step
* Use parallel execution when safe
* Notify on failures and successes

❌ **DON'T:**

* Chain 10+ tools synchronously
* Ignore error messages
* Retry immediately without waiting
* Assume tools always succeed
* Leave workflows without logging

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Sample Queries" href="/examples/sample-queries">
    Real query examples.
  </Card>

  <Card title="Real-World Workflows" href="/examples/real-world-workflows">
    Complete end-to-end workflows.
  </Card>

  <Card title="Error Handling" href="/api-reference/overview">
    Error codes and handling.
  </Card>

  <Card title="API Reference" href="/api-reference/execute-tool">
    Execute tool details.
  </Card>
</CardGroup>

***

Master these patterns and you'll build robust, reliable automation! 🚀
