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

# Execute API

> Stateless agent execution — run one-shot tasks, background jobs, and scheduled automation.

## POST /v1/bots/:id/execute

The Execute API runs a bot with a single prompt and returns a response. Unlike the Chat API, Execute is **stateless** — no session ID, no conversation history loaded. Each call is independent.

Use Execute for:

* Scheduled automation (daily reports, cron jobs)
* Background processing (classify this email, summarize this document)
* One-shot tasks that don't need memory

## Request

```bash theme={null}
curl -X POST https://api.bothive.cloud/v1/bots/{bot_id}/execute \
  -H "Authorization: Bearer bh_sk_xxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Summarize these support tickets and identify the top 3 issues: [...]",
    "context": {
      "time_range": "last_7_days",
      "team": "billing"
    }
  }'
```

### Headers

| Header          | Required | Description        |
| --------------- | -------- | ------------------ |
| `Authorization` |          | `Bearer bh_sk_...` |
| `Content-Type`  |          | `application/json` |

### Request body

| Field        | Type     | Required | Description                                           |
| ------------ | -------- | -------- | ----------------------------------------------------- |
| `prompt`     | `string` |          | The task prompt or instruction                        |
| `context`    | `object` | Optional | Additional key-value context injected into the prompt |
| `model`      | `string` | Optional | Override the bot's default model for this run         |
| `max_tokens` | `number` | Optional | Cap the response length                               |

## Response

```json theme={null}
{
  "result": "Top 3 billing issues this week:\n1. Failed card charges (47 tickets)\n2. Plan upgrade confusion (23 tickets)\n3. Invoice discrepancies (18 tickets)",
  "run_id": "run_abc456",
  "latency_ms": 1204,
  "tokens_used": 892,
  "tools_called": ["billing.getTickets", "ai.summarize"],
  "status": "success"
}
```

### Response fields

| Field          | Type       | Description                                 |
| -------------- | ---------- | ------------------------------------------- |
| `result`       | `string`   | The agent's output for this execution       |
| `run_id`       | `string`   | Unique run ID — use to fetch the full trace |
| `latency_ms`   | `number`   | Total execution time in milliseconds        |
| `tokens_used`  | `number`   | Total tokens consumed                       |
| `tools_called` | `string[]` | Capability names invoked during this run    |
| `status`       | `string`   | `success`, `error`, or `timeout`            |

## TypeScript example

```typescript theme={null}
import { BothiveClient } from '@bothive/sdk';

const client = new BothiveClient({ apiKey: process.env.BOTHIVE_API_KEY });

// One-shot execution
const result = await client.bots.execute('bot_abc123', {
  prompt: 'Classify this support email as: billing / technical / general',
  context: {
    email: emailBody,
    sender: fromAddress,
  },
});

console.log(result.result); // "billing"
console.log(result.run_id); // For trace lookup
```

## Scheduled execution example

Run a bot on a schedule from your backend:

```typescript theme={null}
// Using node-cron or Vercel Cron
import cron from 'node-cron';

cron.schedule('0 9 * * *', async () => {
  const report = await fetch(
    `https://api.bothive.cloud/v1/bots/${REPORT_BOT_ID}/execute`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.BOTHIVE_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt: 'Generate today\'s business metrics report',
        context: { date: new Date().toISOString() },
      }),
    }
  );

  const { result, run_id } = await report.json();

  // Post to Slack
  await postToSlack('#metrics', result);

  console.log(`Report generated. Trace: ${run_id}`);
});
```

<Tip>
  If your bot has a `schedule` block in HiveLang, Bothive handles the cron automatically — you don't need to set up your own cron job. Use the Execute API only when you need to trigger a run from your own backend on-demand.
</Tip>

## Execute vs Chat — when to use each

| Use case                             | Chat API | Execute API |
| ------------------------------------ | -------- | ----------- |
| Product copilot / embedded assistant |          |             |
| Session-aware customer support       |          |             |
| One-shot classification task         |          |             |
| Daily scheduled report               |          |             |
| Background email processing          |          |             |
| Webhook-triggered automation         |          |             |
| Long-running conversation            |          |             |

## Fetching the trace

After any Execute call, use the `run_id` to fetch the full trace:

```bash theme={null}
curl https://api.bothive.cloud/v1/runs/{run_id} \
  -H "Authorization: Bearer bh_sk_xxxxxxxxx"
```

## Next reads

<CardGroup cols={3}>
  <Card title="Chat API" icon="comments" href="./chat" className="glass-effect" />

  <Card title="Deploy API" icon="rocket" href="./deploy" className="glass-effect" />

  <Card title="Observability" icon="chart-line" href="../concepts/observability" className="glass-effect" />
</CardGroup>
