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

# 将智能体定义为代码

## 概览

智能体由多个部分组成。其配置是一个大型嵌套对象，webhook 和客户端工具需单独创建并通过 ID 关联，工作流也会引用这些工具 ID。手动操作时，需要创建每个工具，将返回的 ID 复制到智能体配置及工作流节点中，然后创建或更新智能体。只有在智能体运行时才会发现缺少 ID，而重复运行同一脚本会创建重复的工具。

Python 和 JavaScript SDK 中的 `Agent` 构建器可在一个定义中描述完整智能体：包括设置、所用的 [工具](/docs/zh/eleven-agents/customization/agents-as-code/tools) 和 [工作流](/docs/zh/eleven-agents/customization/agents-as-code/workflows)。随后，`agents.push()` 会创建或更新每个工具和智能体，并自动填入工具 ID。

适用场景：

* 用代码定义智能体，并像审查其他代码变更一样审查相关改动。
* 无需 API 密钥即可在 CI 中验证智能体。
* 安全地重复运行部署脚本：未变更的工具不会被处理，也不会创建重复项。
* 按照与 [CLI](/docs/zh/eleven-agents/operate/cli) 相同的布局将智能体保存在代码仓库中，并可通过两者进行操作。

> **Note**
>
> 构建器在 SDK 中运行。`push()` 和 `pull()` 会调用现有的智能体和工具端点，
> 所创建的任何内容都可以在控制台中打开和编辑。

## 要求

* Python：`elevenlabs` 包。构建器从 `elevenlabs.agent_builder` 导入，工具从 `elevenlabs.agent_tools` 导入，工作流从 `elevenlabs.agent_workflows` 导入。
* JavaScript：`@elevenlabs/elevenlabs-js` 包。所有内容均从包根目录导出。

## 定义并推送智能体

`Agent(name, options)` 接受智能体名称和设置。此智能体包含一个供工作流使用的 webhook 工具，以及内置的结束通话工具：

```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"
```

工作流的工具节点接收 `Tool` 对象本身，而非 ID。`push()` 会创建 `get_order`，然后将其新 ID 写入节点。仅供工作流使用的工具无需同时列在 `tools` 中。

如果没有智能体 ID，`push()` 每次都会创建新智能体，与 `agents.create()` 一样。请保留返回的 ID 并在后续推送中传入，或者使用会自动记录 ID 的[项目](#keep-agents-in-version-control)：

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

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

Python 中的 `AsyncElevenLabs` 也提供相同的 `push()` 和 `pull()`，可使用 `await`。

## 智能体选项

类型化选项涵盖了大多数智能体会修改的设置。每个选项都映射到智能体配置中的一个字段：

| Python                  | JavaScript            | 设置内容                                                                                          |
| ----------------------- | --------------------- | --------------------------------------------------------------------------------------------- |
| `prompt`                | `prompt`              | 系统提示词，`conversation_config.agent.prompt.prompt`。                                              |
| `first_message`         | `firstMessage`        | 智能体首先说的话，`conversation_config.agent.first_message`。                                           |
| `language`              | `language`            | 智能体语言，例如 `"en"`，`conversation_config.agent.language`。                                         |
| `llm`, `temperature`    | `llm`, `temperature`  | [LLM](/docs/zh/eleven-agents/customization/llm) 及其温度参数，位于 `conversation_config.agent.prompt`。 |
| `voice_id`, `tts_model` | `voiceId`, `ttsModel` | 音色和文本转语音模型，位于 `conversation_config.tts`。                                                      |
| `tags`                  | `tags`                | 智能体标签。                                                                                        |
| `tools`                 | `tools`               | 智能体可使用的 `Tool` 对象。参见[工具](#tools)。                                                             |
| `tool_ids`              | `toolIds`             | 按原样关联的现有工具 ID。`push()` 不会创建或更改它们。                                                             |
| `workflow`              | `workflow`            | 一个[工作流](/docs/zh/eleven-agents/customization/agents-as-code/workflows)。                       |
| `conversation_config`   | `conversationConfig`  | 其他任意对话设置。参见[其他设置](#other-settings)。                                                           |
| `platform_settings`     | `platformSettings`    | 任意平台设置，例如隐私或小组件设置。                                                                            |

`update()` 可在智能体创建后更改选项，`add_tool()` / `addTool()` 可添加一个工具：

```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());
```

### 其他设置

`conversation_config` / `conversationConfig` 和 `platform_settings` / `platformSettings` 可接受类型化选项未覆盖的任意设置，其结构与 `agents.create()` 相同。在 Python 中，它们可以是 SDK 生成的模型，也可以是使用 snake_case 键的字典。它们会与类型化选项合并，因此可同时使用：

```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 } },
});
```

如果原始设置和类型化选项设置了相同字段，例如 `prompt` 和 `conversation_config.agent.prompt.prompt`，验证会报告 `option_conflict`，而不会让其中一个静默覆盖另一个。

## 工具

`tools` 接受[将工具定义为代码](/docs/zh/eleven-agents/customization/agents-as-code/tools)中的各种工具，每种工具会放在不同位置：

| 工具             | `push()` 的操作                                                    |
| -------------- | --------------------------------------------------------------- |
| Webhook 和客户端工具 | 创建或更新工具，然后通过 ID 将其关联到智能体。                                       |
| 系统工具           | 将工具添加到智能体内置工具中。系统工具属于智能体配置，因此不会发起工具请求。                          |
| 工作流使用的工具       | 创建或更新工具，然后将其 ID 写入使用它的每个工具节点及每个智能体节点的 `tool_ids` / `toolIds` 中。 |

`agent.tools()` 返回智能体及其工作流使用的所有 webhook 和客户端工具，也就是 `push()` 会创建和更新的集合。两个不同工具不能共用名称，但同一个 `Tool` 对象可以在多个位置使用：它只会被推送一次，并获得一个 ID。

### push 如何匹配工具

工具名称在工作区中并不唯一，因此 `push()` 从不会在整个工作区中按名称查找工具。如果提供了智能体 ID，它会列出该智能体已使用的工具，并按名称进行匹配。即使另一个智能体使用了同名工具，也绝不会被修改，因此一次推送不会更改非预期的智能体。使用[项目](#keep-agents-in-version-control)时，则会按项目记录的 ID 匹配工具。

对于每个工具，`push()` 会：

1. 如果现有工具已与定义一致，则不做处理。
2. 如果不同，则更新。
3. 如果找不到匹配项，则创建。

### 推送结果

`push()` 会返回对智能体和每个工具所做的操作，工具以名称为键：

| 字段                     | 值                                                     |
| ---------------------- | ----------------------------------------------------- |
| `agent_id` / `agentId` | 智能体 ID。                                               |
| `action`               | `"created"` 或 `"updated"`。                            |
| `tools[name].id`       | 工具 ID。                                                |
| `tools[name].action`   | `"created"`、`"updated"`、`"unchanged"` 或 `"detached"`。 |

`"detached"` 工具指该智能体在本次推送前使用、现在不再使用的工具。它会从智能体中移除，但不会被删除，因为其他智能体可能仍在使用。

### 推送失败

`push()` 会在发起任何请求前验证智能体，因此无效智能体不会写入任何内容。如果请求在中途失败，例如部分工具已创建，`push()` 会引发或抛出 `AgentPushError`。其 `result` 会列出已写入的工具及其 ID，因此不会有任何内容无法追踪。原始错误将作为其原因。

```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;
  }
}
```

### 推送选项

| Python                | JavaScript           | 作用                                                                      |
| --------------------- | -------------------- | ----------------------------------------------------------------------- |
| `agent_id`            | `agentId`            | 更新此智能体。未提供时，将创建新智能体。                                                    |
| `project`             | `project`            | 使用[项目](#keep-agents-in-version-control)匹配 ID 并写入项目。不能与 `agent_id` 一同使用。 |
| `branch_id`           | `branchId`           | 更新此[分支](/docs/zh/eleven-agents/operate/versioning)，而非主分支。               |
| `version_description` | `versionDescription` | 描述新版本，适用于已启用版本控制的智能体。                                                   |
| `request_options`     | `requestOptions`     | 会传递给 `push()` 发起的每个请求。                                                  |

## 自行发起请求

`push()` 是可选的。只要提供智能体所用工具的 ID（以工具名称为键），`build()` 就会返回供 `agents.create()` 和 `agents.update()` 使用的请求体。可先通过自己的方式创建工具：

```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 } })
);
```

如果映射中没有某个工具的 ID，`build()` 会报告一个指明该工具的 `unresolved_tool` 问题。

## 将智能体纳入版本控制

`AgentProject` 可读取和写入 [CLI](/docs/zh/eleven-agents/operate/cli) 的项目布局，因此同一代码仓库既能与 SDK 配合使用，也能使用 `elevenlabs agents push`：

| 文件               | 内容                                |
| ---------------- | --------------------------------- |
| `agents.json`    | 每个智能体的配置文件，以及推送后的 ID 和分支。         |
| `tools.json`     | 每个 webhook 和客户端工具的配置文件，以及推送后的 ID。 |
| `agent_configs/` | 每个智能体一个文件，采用 API 的传输格式。           |
| `tool_configs/`  | 每个工具一个文件，采用 API 的传输格式。            |

将项目传给 `push()` 后，它会按项目记录的 ID 匹配智能体和工具，而不是按你保存的智能体 ID。它会将发送的配置和任何新 ID 写回项目，因此再次运行相同脚本时会更新智能体，而不是再创建一个：

```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 });
```

### 编辑存储在项目中的智能体

`project.agent(name)` 会将智能体从其配置文件加载为 `Agent`。`tools.json` 中列出的工具会作为 `Tool` 对象返回，其他工具的 ID 则保留在 `tool_ids` / `toolIds` 中。构建器未建模的设置会被保留，因此推送回去时只会更改你修改的内容：

```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` 可让你访问智能体的工作流，以便使用[工作流构建器](/docs/zh/eleven-agents/customization/agents-as-code/workflows)进行编辑，其工具节点会指向相同的 `Tool` 对象。

### 从控制台拉取智能体

`agents.pull(agent_id)` 会将现有智能体加载为 `Agent`，其 webhook 和客户端工具会作为 `Tool` 对象加载。使用项目时，它还会将智能体及其工具写入项目并记录其 ID，因此可将通过控制台构建的智能体迁移到代码仓库：

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

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

### 在 CI 中验证

验证无需 API 密钥，因此 CI 作业可在每次拉取请求时检查项目中的所有智能体，并在合并后推送它们：

```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**
>
> 项目目前仅支持 JSON 配置文件。如果 `agents.json` 指向 YAML 或 TOML 配置，
> 打开项目时会引发 `AgentProjectError`。

## 验证

`validate()` 会检查智能体及其使用的所有内容，无需工具 ID。`build()` 和 `push()` 会先调用它。它会引发或抛出一个 `AgentValidationError`，其 `issues` 会列出所有问题，每项均包含 `code`、`message` 以及相关部分的 `path`：

```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;
  }
}
```

| 代码                        | 问题                                                                                       |
| ------------------------- | ---------------------------------------------------------------------------------------- |
| `missing_name`            | 智能体没有名称。                                                                                 |
| `option_conflict`         | 类型化选项与原始配置设置了相同字段。                                                                       |
| `invalid_config`          | 原始设置的值不符合 API 架构要求。                                                                      |
| `duplicate_tool_name`     | 两个不同工具使用相同名称。                                                                            |
| `invalid_tool`            | 工具未通过[工具验证](/docs/zh/eleven-agents/customization/agents-as-code/tools#validation)。       |
| `invalid_workflow`        | 工作流未通过[工作流验证](/docs/zh/eleven-agents/customization/agents-as-code/workflows#validation)。 |
| `system_tool_in_workflow` | 工作流工具节点使用了系统工具。请改为将系统工具添加到智能体的 `tools` 中。                                                |
| `unresolved_tool`         | 未向 `build()` 提供智能体所用工具的 ID。                                                              |

没有提示词的智能体会报告 `missing_prompt` 警告，但不会导致验证失败。向 `validate()` 传入 `on_warning` / `onWarning` 可接收警告。