> This is a page from the ElevenLabs documentation. For an index of the documentation, fetch https://elevenlabs.io/docs/llms.txt.

# Agents as code

## Overview

An agent is assembled from several parts. Its config is a large nested object, its webhook and client tools are created separately and attached by ID, and its workflow refers to those same tool IDs. Doing this by hand means creating each tool, copying the returned IDs into the agent's config and its workflow's nodes, then creating or updating the agent. A missing ID only shows up once the agent runs, and running the same script twice creates duplicate tools.

The `Agent` builder in the Python and JavaScript SDKs describes the whole agent in one definition: its settings, the [tools](/docs/eleven-agents/customization/agents-as-code/tools) it uses and its [workflow](/docs/eleven-agents/customization/agents-as-code/workflows). `agents.push()` then creates or updates every tool and the agent, filling in the tool IDs for you.

Use it to:

* Define an agent in code and review changes to it like any other code change.
* Validate agents in CI without an API key.
* Re-run a deploy script safely: tools that haven't changed aren't touched, and nothing is duplicated.
* Keep agents in a repository in the same layout as the [CLI](/docs/eleven-agents/operate/cli), and work on them with either.

> **Note**
>
> The builder runs in the SDK. `push()` and `pull()` call the existing agents and tools endpoints,
> and anything they create can be opened and edited in the dashboard.

## Requirements

* Python: the `elevenlabs` package. The builder is imported from `elevenlabs.agent_builder`, tools from `elevenlabs.agent_tools` and workflows from `elevenlabs.agent_workflows`.
* JavaScript: the `@elevenlabs/elevenlabs-js` package. Everything is exported from the package root.

## Define and push an agent

`Agent(name, options)` takes the agent's name and its settings. This agent has a webhook tool that its workflow uses, and the built-in end-call tool:

```python
from elevenlabs import ElevenLabs
from elevenlabs.agent_builder import Agent
from elevenlabs.agent_tools import Schema, SystemTool, Tool
from elevenlabs.agent_workflows import Workflow

elevenlabs = ElevenLabs()

get_order = (
    Tool.webhook("get_order", "Look up an order by its number")
    .get("https://api.example.com/orders/{order_id}")
    .path_param("order_id", Schema.string().describe("The order number, e.g. A-1042"))
)

wf = Workflow()
(
    wf.converse("triage", "Find out what the caller needs")
    .when("Caller gave an order number")
    .tool("lookup", [get_order])
    .on_success()
    .converse("resolve", "Explain the order status")
)

agent = Agent(
    "Support line",
    prompt="You are a support agent for Acme.",
    first_message="Hi, how can I help?",
    llm="gemini-2.0-flash",
    voice_id="21m00Tcm4TlvDq8ikWAM",
    tools=[SystemTool.end_call()],
    workflow=wf,
)

result = elevenlabs.conversational_ai.agents.push(agent)
print(result.agent_id, result.tools["get_order"].action)  # "created"
```

```typescript
import {
  Agent,
  ElevenLabsClient,
  Schema,
  SystemTool,
  Tool,
  Workflow,
} from "@elevenlabs/elevenlabs-js";

const elevenlabs = new ElevenLabsClient();

const getOrder = Tool.webhook("get_order", "Look up an order by its number")
  .get("https://api.example.com/orders/{order_id}")
  .pathParam("order_id", Schema.string().describe("The order number, e.g. A-1042"));

const wf = new Workflow();
wf.converse("triage", "Find out what the caller needs")
  .when("Caller gave an order number")
  .tool("lookup", [getOrder])
  .onSuccess()
  .converse("resolve", "Explain the order status");

const agent = new Agent("Support line", {
  prompt: "You are a support agent for Acme.",
  firstMessage: "Hi, how can I help?",
  llm: "gemini-2.0-flash",
  voiceId: "21m00Tcm4TlvDq8ikWAM",
  tools: [SystemTool.endCall()],
  workflow: wf,
});

const result = await elevenlabs.conversationalAi.agents.push(agent);
console.log(result.agentId, result.tools.get_order.action); // "created"
```

The workflow's tool node takes the `Tool` object itself rather than an ID. `push()` creates `get_order`, then writes its new ID into the node. Tools used only by the workflow don't also need to be listed in `tools`.

Without an agent ID, `push()` creates a new agent each time, just as `agents.create()` does. Keep the returned ID and pass it on later pushes, or use a [project](#keep-agents-in-version-control), which records it for you:

```python
elevenlabs.conversational_ai.agents.push(agent, agent_id=result.agent_id)
```

```typescript
await elevenlabs.conversationalAi.agents.push(agent, { agentId: result.agentId });
```

`AsyncElevenLabs` has the same `push()` and `pull()` in Python, to `await`.

## Agent options

The typed options cover the settings most agents change. Each one maps to a field of the agent's config:

| Python                  | JavaScript            | Sets                                                                                                         |
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------ |
| `prompt`                | `prompt`              | The system prompt, `conversation_config.agent.prompt.prompt`.                                                |
| `first_message`         | `firstMessage`        | What the agent says first, `conversation_config.agent.first_message`.                                        |
| `language`              | `language`            | The agent's language, such as `"en"`, `conversation_config.agent.language`.                                  |
| `llm`, `temperature`    | `llm`, `temperature`  | The [LLM](/docs/eleven-agents/customization/llm) and its temperature, in `conversation_config.agent.prompt`. |
| `voice_id`, `tts_model` | `voiceId`, `ttsModel` | The voice and text-to-speech model, in `conversation_config.tts`.                                            |
| `tags`                  | `tags`                | The agent's tags.                                                                                            |
| `tools`                 | `tools`               | `Tool` objects the agent can use. See [Tools](#tools).                                                       |
| `tool_ids`              | `toolIds`             | IDs of existing tools to attach as they are. `push()` doesn't create or change them.                         |
| `workflow`              | `workflow`            | A [workflow](/docs/eleven-agents/customization/agents-as-code/workflows).                                    |
| `conversation_config`   | `conversationConfig`  | Any other conversation setting. See [Other settings](#other-settings).                                       |
| `platform_settings`     | `platformSettings`    | Any platform setting, such as privacy or widget settings.                                                    |

`update()` changes options after the agent is created, and `add_tool()` / `addTool()` adds one tool:

```python
agent.update(first_message="Hello! What can I do for you?", temperature=0.3)
agent.add_tool(SystemTool.skip_turn())
```

```typescript
agent.update({ firstMessage: "Hello! What can I do for you?", temperature: 0.3 });
agent.addTool(SystemTool.skipTurn());
```

### Other settings

`conversation_config` / `conversationConfig` and `platform_settings` / `platformSettings` take any setting the typed options don't cover, in the same shape as `agents.create()`. In Python they can be the SDK's generated models or dictionaries with snake_case keys. They're merged with the typed options, so you can use both:

```python
agent = Agent(
    "Support line",
    prompt="You are a support agent for Acme.",
    conversation_config={"turn": {"turn_timeout": 7}},
    platform_settings={"privacy": {"record_voice": False}},
)
```

```typescript
const agent = new Agent("Support line", {
  prompt: "You are a support agent for Acme.",
  conversationConfig: { turn: { turnTimeout: 7 } },
  platformSettings: { privacy: { recordVoice: false } },
});
```

If a raw setting and a typed option set the same field, such as `prompt` and `conversation_config.agent.prompt.prompt`, validation reports an `option_conflict` instead of letting one silently win.

## Tools

`tools` takes every kind of tool from [tools as code](/docs/eleven-agents/customization/agents-as-code/tools), and each kind ends up in a different place:

| Tool                       | What `push()` does                                                                                                               |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Webhook and client tools   | Creates or updates the tool, then attaches it to the agent by ID.                                                                |
| System tools               | Adds the tool to the agent's built-in tools. System tools are part of the agent's config, so no tools request is made.           |
| Tools used by the workflow | Creates or updates the tool, then writes its ID into each tool node, and each agent node's `tool_ids` / `toolIds`, that uses it. |

`agent.tools()` returns every webhook and client tool the agent and its workflow use: the set `push()` creates and updates. Two different tools can't share a name, but the same `Tool` object can be used in several places: it's pushed once and gets one ID.

### How push matches tools

Tool names aren't unique in a workspace, so `push()` never looks tools up by name across the whole workspace. With an agent ID, it lists the tools that agent already uses and matches those by name. A tool with the same name that only another agent uses is never touched, so a push can't change an agent you didn't mean to. With a [project](#keep-agents-in-version-control), tools are matched by the IDs the project records instead.

For each tool, `push()` then:

1. Leaves the tool alone if the existing one already matches the definition.
2. Updates it if it differs.
3. Creates it if there's no match.

### Push results

`push()` returns what it did to the agent and to each tool, keyed by tool name:

| Field                  | Value                                                    |
| ---------------------- | -------------------------------------------------------- |
| `agent_id` / `agentId` | The agent's ID.                                          |
| `action`               | `"created"` or `"updated"`.                              |
| `tools[name].id`       | The tool's ID.                                           |
| `tools[name].action`   | `"created"`, `"updated"`, `"unchanged"` or `"detached"`. |

A `"detached"` tool is one the agent used before this push and no longer does. It's removed from the agent but not deleted, since another agent may still use it.

### Failed pushes

`push()` validates the agent before it makes any request, so an invalid agent writes nothing. If a request fails partway, for example after some tools are created, `push()` raises or throws an `AgentPushError`. Its `result` lists the tools already written and their IDs, so nothing is left unaccounted for. The original error is its cause.

```python
from elevenlabs.agent_builder import AgentPushError

try:
    elevenlabs.conversational_ai.agents.push(agent, agent_id=agent_id)
except AgentPushError as err:
    print(err)  # what failed, and why
    for name, tool in err.result.tools.items():
        print(name, tool.id, tool.action)
```

```typescript
import { AgentPushError } from "@elevenlabs/elevenlabs-js";

try {
  await elevenlabs.conversationalAi.agents.push(agent, { agentId });
} catch (err) {
  if (err instanceof AgentPushError) {
    console.error(err.message); // what failed, and why
    for (const [name, tool] of Object.entries(err.result.tools))
      console.error(name, tool.id, tool.action);
  } else {
    throw err;
  }
}
```

### Push options

| Python                | JavaScript           | Does                                                                                               |
| --------------------- | -------------------- | -------------------------------------------------------------------------------------------------- |
| `agent_id`            | `agentId`            | Updates this agent. Without it, a new agent is created.                                            |
| `project`             | `project`            | Uses a [project](#keep-agents-in-version-control) to match IDs and writes it. Not with `agent_id`. |
| `branch_id`           | `branchId`           | Updates this [branch](/docs/eleven-agents/operate/versioning) instead of the main one.             |
| `version_description` | `versionDescription` | Describes the new version, for agents with versioning enabled.                                     |
| `request_options`     | `requestOptions`     | Passed to every request `push()` makes.                                                            |

## Make the requests yourself

`push()` is optional. `build()` returns the request body for `agents.create()` and `agents.update()`, given the IDs of the tools the agent uses, keyed by tool name. Use it to create the tools in your own way first:

```python
order_tool = elevenlabs.conversational_ai.tools.create(request=get_order.build())

created = elevenlabs.conversational_ai.agents.create(**agent.build(tool_ids={"get_order": order_tool.id}))
```

```typescript
const orderTool = await elevenlabs.conversationalAi.tools.create(getOrder.build());

const created = await elevenlabs.conversationalAi.agents.create(
  agent.build({ toolIds: { get_order: orderTool.id } })
);
```

If a tool has no ID in the map, `build()` reports an `unresolved_tool` issue naming it.

## Keep agents in version control

`AgentProject` reads and writes the [CLI](/docs/eleven-agents/operate/cli)'s project layout, so the same repository works with the SDK and with `elevenlabs agents push`:

| File             | Holds                                                                |
| ---------------- | -------------------------------------------------------------------- |
| `agents.json`    | Each agent's config file and, once pushed, its ID and branch.        |
| `tools.json`     | Each webhook and client tool's config file and, once pushed, its ID. |
| `agent_configs/` | One file per agent, in the API's wire format.                        |
| `tool_configs/`  | One file per tool, in the API's wire format.                         |

Pass a project to `push()` and it matches agents and tools by the IDs the project records, rather than by an agent ID you keep. It writes the configs it sent and any new IDs back to the project, so running the same script again updates the agent instead of creating another:

```python
from elevenlabs.agent_builder import AgentProject

project = AgentProject.open(".")  # an empty directory works too
elevenlabs.conversational_ai.agents.push(agent, project=project)
```

```typescript
import { AgentProject } from "@elevenlabs/elevenlabs-js";

const project = await AgentProject.open("."); // Node.js; an empty directory works too
await elevenlabs.conversationalAi.agents.push(agent, { project });
```

### Edit an agent stored in a project

`project.agent(name)` loads an agent from its config file as an `Agent`. Tools listed in `tools.json` come back as `Tool` objects, and IDs of other tools stay in `tool_ids` / `toolIds`. Settings the builder doesn't model are kept, so pushing it back only changes what you changed:

```python
support = project.agent("Support line")
support.update(first_message="Hello!")
elevenlabs.conversational_ai.agents.push(support, project=project)
```

```typescript
const support = project.agent("Support line");
support.update({ firstMessage: "Hello!" });
await elevenlabs.conversationalAi.agents.push(support, { project });
```

`agent.workflow` gives you the agent's workflow to edit with the [workflow builder](/docs/eleven-agents/customization/agents-as-code/workflows), with its tool nodes pointing at the same `Tool` objects.

### Pull an agent from the dashboard

`agents.pull(agent_id)` loads an existing agent as an `Agent`, with its webhook and client tools as `Tool` objects. With a project, it also writes the agent and its tools there and records their IDs, so an agent built in the dashboard can be moved into a repository:

```python
support = elevenlabs.conversational_ai.agents.pull("agent_123", project=project)
```

```typescript
const support = await elevenlabs.conversationalAi.agents.pull("agent_123", { project });
```

### Validate in CI

Validation needs no API key, so a CI job can check every agent in a project on each pull request, then push them on merge:

```python
from elevenlabs.agent_builder import AgentProject

project = AgentProject.open(".")
for agent in project.agents():
    agent.validate()
```

```typescript
import { AgentProject } from "@elevenlabs/elevenlabs-js";

const project = await AgentProject.open(".");
for (const agent of project.agents()) agent.validate();
```

> **Note**
>
> Projects support JSON config files only for now. If `agents.json` points at a YAML or TOML config,
> opening the project raises an `AgentProjectError`.

## Validation

`validate()` checks the agent and everything it uses, without needing tool IDs. `build()` and `push()` call it first. It raises or throws a single `AgentValidationError` whose `issues` list every problem, each with a `code`, a `message` and the `path` of the part it concerns:

```python
from elevenlabs.agent_builder import AgentValidationError

try:
    agent.validate()
except AgentValidationError as err:
    for issue in err.issues:
        print(issue.code, issue.path, issue.message)
```

```typescript
import { AgentValidationError } from "@elevenlabs/elevenlabs-js";

try {
  agent.validate();
} catch (err) {
  if (err instanceof AgentValidationError) {
    for (const issue of err.issues) console.error(issue.code, issue.path, issue.message);
  } else {
    throw err;
  }
}
```

| Code                      | Problem                                                                                                          |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `missing_name`            | The agent has no name.                                                                                           |
| `option_conflict`         | A typed option and the raw config set the same field.                                                            |
| `invalid_config`          | A raw setting has a value the API's schema doesn't accept.                                                       |
| `duplicate_tool_name`     | Two different tools have the same name.                                                                          |
| `invalid_tool`            | A tool fails [tool validation](/docs/eleven-agents/customization/agents-as-code/tools#validation).               |
| `invalid_workflow`        | The workflow fails [workflow validation](/docs/eleven-agents/customization/agents-as-code/workflows#validation). |
| `system_tool_in_workflow` | A workflow tool node uses a system tool. Add system tools to the agent's `tools` instead.                        |
| `unresolved_tool`         | `build()` was given no ID for a tool the agent uses.                                                             |

An agent with no prompt is reported as a `missing_prompt` warning, which doesn't fail validation. Pass `on_warning` / `onWarning` to `validate()` to receive warnings.