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

# Use the API from Claude Code

> Let a coding agent update instructions and knowledge on all your agents at once

Coding agents such as Claude Code work best when they can write a short script against a typed API. This page gives your agent what it needs: a key, the client, and recipes it can adapt.

> [!TIP]
>
> Prefer commands to scripts? The [totebot CLI](https://docs.totebot.ai/cli/overview.md) does all of this with one command each, signs in through your browser, and ships a Claude Code skill. See [Use the CLI with coding agents](https://docs.totebot.ai/cli/coding-agents.md).

> [!TIP]
>
> Want the agent to find what your knowledge is missing and fix it? See [Analyse your agent with Claude Code](https://docs.totebot.ai/api/analyse-with-claude-code.md).

The live OpenAPI spec is public at [`https://api.totebot.ai/v1/openapi.json`](https://api.totebot.ai/v1/openapi.json). Point your agent at it whenever it needs a field or an endpoint that is not in these recipes.

## Set up

**1. Create a team key**

In **Team settings** → **API keys**, create a key. It can only read until you turn on write access, so switch on just the write scopes the agent needs (for example `agents:write` and `knowledge:write`). Keep **All agents**, or pick the agents it may change. You can widen or narrow the key later with **Edit access**.

**2. Put the key in your environment**

```bash theme={null}
export TOTEBOT_API_KEY=tb_live_your_key_here
```

Never paste the key into a prompt or commit it.

**3. Download the client**

```bash theme={null}
curl -o totebot.ts https://api.totebot.ai/v1/sdk/totebot.ts
```

It is one TypeScript file with no dependencies. Run scripts with `npx tsx script.ts`, `bun script.ts` or `deno run -A script.ts`.

**4. Tell your agent where to look**

Add this to your project's `CLAUDE.md`:

```markdown theme={null}
## Totebot
Manage our Totebot agents with ./totebot.ts and $TOTEBOT_API_KEY.
Guide: https://docs.totebot.ai/api/claude-code
Spec: https://api.totebot.ai/v1/openapi.json
Knowledge changes go live after training: pass `train: true` to bulk calls,
or call totebot.training.start(agentId) once a batch is done.
```

You can then ask things like *"Update the shipping FAQ on every agent to say delivery takes 2-3 working days"* and the agent writes and runs a script like the ones below.

## Recipes

### List agents and their instructions

```ts theme={null}
import { Totebot } from './totebot';

const totebot = new Totebot({ apiKey: process.env.TOTEBOT_API_KEY! });

for (const agent of await totebot.agents.list()) {
  console.log(agent.id, agent.name);
  console.log(agent.systemPrompt);
}
```

### Update one FAQ on every agent

The Q\&A is matched by its exact question: agents that have it get the new answer, agents that don't get it added.

```ts theme={null}
const { succeeded, failed, results } = await totebot.bulk.upsertQa({
  question: 'How long does delivery take?',
  answer: 'Delivery takes 2-3 working days within Slovenia and Croatia.',
  train: true,
});

for (const result of results) {
  console.log(
    result.agentId,
    result.ok ? result.data.action : `failed: ${result.error.message}`,
  );
}
```

### Change a section of the instructions on every agent

Instructions apply from the next message; no training needed.

```ts theme={null}
const agents = await totebot.agents.list();

for (const agent of agents) {
  const systemPrompt = agent.systemPrompt.replace(
    /## Returns[\s\S]*?(?=\n## |$)/,
    '## Returns\nCustomers can return items within 30 days.\n',
  );
  if (systemPrompt !== agent.systemPrompt) {
    await totebot.agents.update(agent.id, { systemPrompt });
  }
}
```

To set the same full instructions on several agents at once, use `totebot.bulk.updateAgents({ agentIds, systemPrompt })`.

### Keep a text document in sync from a file

The text source is matched by its exact title, so running this again after editing the file replaces the old version.

```ts theme={null}
import { readFileSync } from 'fs';

await totebot.bulk.upsertText({
  title: 'Shipping policy',
  text: readFileSync('knowledge/shipping.md', 'utf8'),
  train: true,
});
```

Text sources hold up to 10,000 characters; split longer documents into several titled sources.

### Add only to some agents

Every bulk call takes `agentIds`. Agent IDs are in `totebot.agents.list()`.

```ts theme={null}
const agents = await totebot.agents.list();
const hr = agents.filter((agent) => agent.name.includes('HR')).map((a) => a.id);

await totebot.bulk.upsertQa({
  agentIds: hr,
  question: 'How many vacation days do I get?',
  answer: 'Full-time employees get 25 days a year.',
  train: true,
});
```

### Find and retry failed sources

```ts theme={null}
for (const agent of await totebot.agents.list()) {
  const failed = await totebot.knowledge.list(agent.id, { status: 'FAILED' });
  for (const source of failed) {
    console.log(agent.name, source.url ?? source.title, source.processingError);
  }
  if (failed.length > 0) {
    await totebot.knowledge.retryFailed(agent.id);
  }
}
```

### Remove an outdated answer everywhere

```ts theme={null}
await totebot.bulk.remove({
  match: { question: 'Do you offer free shipping over 50 EUR?' },
  train: true,
});
```

### Wait for training to finish

```ts theme={null}
await totebot.training.start(agentId);
const status = await totebot.training.waitUntilDone(agentId);
if (status.hasFailedKnowledgeSources) {
  const failed = await totebot.knowledge.list(agentId, { status: 'FAILED' });
  console.log(failed.map((source) => source.processingError));
}
```

### Create an agent from a website and set it up

```ts theme={null}
const agent = await totebot.agents.create({ websiteUrl: 'https://example.com' });

const models = await totebot.agents.models(agent.id);
const cheapest = models
  .filter((model) => model.isAvailableOnPlan)
  .sort((a, b) => a.creditMultiplier - b.creditMultiplier)[0];

await totebot.agents.update(agent.id, {
  modelId: cheapest.id,
  language: 'sl',
  allowedDomains: ['example.com'],
  isPublic: false,
});
await totebot.agents.updateChatInterface(agent.id, {
  initialMessages: ['Pozdravljeni! Kako vam lahko pomagam?'],
  suggestedMessages: ['Kje je moje naročilo?', 'Dostava'],
});
```

### Clone an agent for a new market

```ts theme={null}
const { agent: copy, trainingRequired } = await totebot.agents.duplicate(sloAgentId, {
  name: 'Example HR',
});
await totebot.agents.update(copy.id, { language: 'hr' });
if (trainingRequired) await totebot.training.start(copy.id);
```

### Add lead capture and a handover to every agent

```ts theme={null}
for (const agent of await totebot.agents.list()) {
  const actions = await totebot.actions.list(agent.id);
  if (!actions.some((action) => action.type === 'Lead')) {
    await totebot.actions.create(agent.id, {
      type: 'Lead',
      name: 'Capture leads',
      description: 'When a visitor wants a quote or a callback, collect their name and email.',
    });
  }
}
```

The key needs `plugins:write`.

### Work the help desk

```ts theme={null}
const { tickets } = await totebot.tickets.list({ view: 'UNASSIGNED' });
const { members } = await totebot.team.members();
const ana = members.find((member) => member.email === 'ana@example.com');

for (const ticket of tickets) {
  await totebot.tickets.update(ticket.id, { assigneeId: ana?.userId, priority: 'HIGH' });
  await totebot.tickets.addNote(ticket.id, 'Assigned by the weekly triage script.');
}
```

The key needs `helpdesk:read` and `helpdesk:write`.

### Check plan usage and invite a colleague

```ts theme={null}
const team = await totebot.team.get();
console.log(team.plan, team.usage.messages);

if (team.usage.members.limit === -1 || team.usage.members.used < team.usage.members.limit) {
  await totebot.team.invite('ana@example.com');
}
```

The key needs `members:write`, which lets it add people with dashboard access. The API only invites members; ownership is granted in the dashboard.

### Answer the questions your agents could not

```ts theme={null}
for (const agent of await totebot.agents.list()) {
  for (const gap of await totebot.knowledge.suggestions(agent.id)) {
    console.log(agent.name, gap.frequency, gap.normalizedQuestion);
  }
}
// After a human writes the answer:
await totebot.knowledge.resolveSuggestion(agentId, suggestionId, {
  type: 'QA',
  question: 'Do you ship to Austria?',
  answer: 'Yes, within 3-5 working days.',
});
```

### Test new instructions, apply them, and roll back if needed

```ts theme={null}
import { readFileSync } from 'node:fs';

const proposed = readFileSync('proposed.md', 'utf8');

// Run the test questions against the proposal; nothing is saved.
const started = await totebot.tests.startRun(agentId, { systemPrompt: proposed });
const run = await totebot.tests.waitForRun(agentId, started.id);
console.log(`proposal ${run.passed}/${run.total}, live agent ${run.baselinePassed}/${run.total}`);
if (run.status !== 'COMPLETED' || run.passed < (run.baselinePassed ?? run.total)) {
  throw new Error('The proposal does not pass at least as many test questions as the live agent.');
}

// One reply with the steps behind it; no conversation is created.
const preview = await totebot.chatPreview(agentId, {
  message: 'Do you deliver on Saturdays?',
  systemPrompt: proposed,
});
console.log(preview.reply);

// See what would change. Apply only after a person approved it.
console.log(await totebot.agents.previewUpdate(agentId, { systemPrompt: proposed }));
await totebot.agents.update(agentId, { systemPrompt: proposed });
const { items } = await totebot.revisions.list(agentId, { limit: 1 });
const appliedRevisionId = items[0].id; // keep this id with your change

// Later, if results got worse: restore the settings from before that change.
console.log(await totebot.revisions.previewRestore(agentId, appliedRevisionId));
await totebot.revisions.restore(agentId, appliedRevisionId);
```

Test runs need `quality:write` (and `quality:read` to read results), the preview chat `chat:write` plus `agents:write` or `quality:write`, and the update and restore `agents:write`. The full loop, with the analysis steps, is in [Optimize your agents with Claude Code](https://docs.totebot.ai/cli/optimize-agents.md).

## Without the client

Everything above is plain HTTPS. For example, with `curl`:

```bash theme={null}
curl -X POST https://api.totebot.ai/v1/bulk/knowledge/qa \
  -H "Authorization: Bearer $TOTEBOT_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"question":"How long does delivery take?","answer":"2-3 working days.","train":true}'
```

## Good to know

* **Training.** New and edited knowledge reaches the agent after training. Training a large knowledge base takes a few minutes, and an agent trained very recently may ask you to wait (`429` with `secondsRemaining`). Batch your changes and train once.
* **Edits create a new source.** Editing a text or Q\&A gives it a new `id`, so look sources up again after changing them, or match by question or title with the bulk endpoints.
* **Retries are safe.** The client sends an `Idempotency-Key` with every write and retries network errors and server errors with the same key.
* **Scopes.** Keys start read-only. If a call fails with `403`, `error.details.missingScopes` says which scope to turn on in **Edit access**.
* **Rate limits.** Over the limit you get `429` with `Retry-After`; the client waits and retries.
* **Not available.** Billing, deleting the team, API keys, granting ownership and OAuth connections stay in the dashboard. See [What the API does not do](https://docs.totebot.ai/api/public-api.md#what-the-api-does-not-do).
* **Integration content.** Synced products and other integration content show `managedByIntegration: true` and are read-only here.

See the [Public API overview](https://docs.totebot.ai/api/public-api.md) for limits and errors, and the [API reference](https://docs.totebot.ai/api-reference/overview.md) for every field.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.