Skip to main content

Tool Execution Flow Examples

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

Sequential Execution

Execute tools one after another:
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:
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:
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:
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:
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

PatternUse CaseExample
SequentialSteps must run in orderBuild β†’ Test β†’ Deploy
ParallelIndependent tasksGet logs, metrics, status
ConditionalRun based on stateIf unhealthy, deploy fix
RetryHandle transient failuresAPI timeouts
OrchestratedComplex multi-stepIssue 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

Sample Queries

Real query examples.

Real-World Workflows

Complete end-to-end workflows.

Error Handling

Error codes and handling.

API Reference

Execute tool details.

Master these patterns and you’ll build robust, reliable automation! πŸš€