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

# 发布客户端工具变更

一个[客户端工具](/docs/zh/eleven-agents/customization/tools/client-tools)由两个独立发布的部分组成。工具定义位于服务器端，通过 SDK 或控制台推送。其处理程序位于前端，只有用户加载新版本时才能获得。本指南介绍如何让两者保持同步：每个前端版本都在其构建所基于的智能体版本上发起对话，而工具的破坏性更改会作为新工具与旧工具一同发布。

## 工具更改如何传达至已部署客户端

智能体会进行[版本控制](/docs/zh/eleven-agents/operate/versioning)，工具不会。一个版本会通过工具 ID 记录智能体使用的工具，但工具定义（包括名称和参数）存储在工具本身，并由使用它的所有智能体、分支和版本共享。更新工具会立即在所有位置生效。[安全编辑工具](/docs/zh/eleven-agents/customization/tools/tool-configuration/editing-tools#how-tools-relate-to-branches-and-versions)对此有详细说明。

这对客户端工具有两个影响：

* `agents.push()` 会原地更新已更改的工具，因此新定义会传达至前端的每个已部署副本，包括只有旧处理程序的版本。即使推送到分支也会如此。
* 将前端固定到某个智能体版本，可避免受到智能体提示词、设置和附加工具变更的影响，但无法避免工具定义变更。

将已发布前端使用的客户端工具视为固定不变。向后兼容的更改可原地推送，破坏性更改则应作为使用新名称的新工具发布。

## 判断更改是否具有破坏性

如果已部署的处理程序无法处理智能体现在发送的内容，或不再返回智能体现在期望的内容，那么该更改就具有破坏性。

| 更改                                    | 是否具有破坏性 | 发布方式                                         |
| ------------------------------------- | ------- | -------------------------------------------- |
| 添加可选参数                                | 否       | 原地推送，然后发布更新后的处理程序。                           |
| 修改工具或参数的描述                            | 否       | 原地推送。这会改变 LLM 调用它的方式。                        |
| 重命名或删除参数                              | 是       | [新工具](#ship-a-breaking-change-as-a-new-tool) |
| 将参数设为必填、更改其类型或缩小允许的值范围                | 是       | [新工具](#ship-a-breaking-change-as-a-new-tool) |
| 更改 `expects_response`，或智能体期望处理程序返回的内容 | 是       | [新工具](#ship-a-breaking-change-as-a-new-tool) |
| 重命名工具                                 | 是       | [新工具](#ship-a-breaking-change-as-a-new-tool) |

只有当现有处理程序会忽略不认识的参数时，新增可选参数才是安全的。JavaScript 和 React SDK 中的处理程序将参数作为单个对象接收，因此除非代码拒绝它们，否则会忽略额外键。

## 将每个前端版本固定到智能体版本

每个版本都要固定，而不只是引入破坏性更改的版本。在主分支上发起对话的版本会随主分支的变化而变化，包括之后删除其所处理工具的合并。

#### 推送智能体并记录其版本

执行 `agents.push()` 后，读取智能体当前版本并将其写入随前端构建发布的文件。在与推送相同的部署任务中运行此操作，确保期间不会有其他推送插入：

```python
import json

from elevenlabs import ElevenLabs
from elevenlabs.agent_builder import Agent
from elevenlabs.agent_tools import Schema, Tool

AGENT_ID = "agent_7101k5zvyjhmfg983brhmhkd98n6"

elevenlabs = ElevenLabs()

add_to_cart = (
    Tool.client("add_to_cart", "Add a product to the shopper's cart")
    .param("sku", Schema.string().describe("The product SKU, e.g. TSH-0042"))
    .options(expects_response=True)
)

agent = Agent(
    "Kiosk assistant",
    prompt="You help shoppers find products and add them to their cart.",
    tools=[add_to_cart],
)

elevenlabs.conversational_ai.agents.push(agent, agent_id=AGENT_ID)

pushed = elevenlabs.conversational_ai.agents.get(agent_id=AGENT_ID)
with open("web/src/agent-release.json", "w") as f:
    json.dump({"versionId": pushed.version_id}, f)
```

```typescript
import { writeFile } from "node:fs/promises";

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

const AGENT_ID = "agent_7101k5zvyjhmfg983brhmhkd98n6";

const elevenlabs = new ElevenLabsClient();

const addToCart = Tool.client("add_to_cart", "Add a product to the shopper's cart")
  .param("sku", Schema.string().describe("The product SKU, e.g. TSH-0042"))
  .options({ expectsResponse: true });

const agent = new Agent("Kiosk assistant", {
  prompt: "You help shoppers find products and add them to their cart.",
  tools: [addToCart],
});

await elevenlabs.conversationalAi.agents.push(agent, { agentId: AGENT_ID });

const pushed = await elevenlabs.conversationalAi.agents.get(AGENT_ID);
await writeFile("web/src/agent-release.json", JSON.stringify({ versionId: pushed.versionId }));
```

版本 ID（例如 `agtvrsn_3901k6kz2c4ep8vm7tq5hd1xw9fb`）标识智能体的固定快照。后续推送会创建新版本，而此版本保持不变。

#### 为该版本生成对话令牌

在服务器端固定版本，即创建[对话令牌](/docs/zh/eleven-agents/api-reference/conversations/get-webrtc-token)或[签名 URL](/docs/zh/eleven-agents/api-reference/conversations/get-signed-url)的位置。两者都接受 `version_id`。客户端 SDK 在启动会话时接受 `branchId`，但不接受版本 ID。

前端发送其构建时使用的版本，而服务器只接受已发布的版本。没有这项检查，客户端就可以在智能体的任意版本上发起对话，包括未发布分支上的版本：

```python
import os

from elevenlabs import ElevenLabs

AGENT_ID = "agent_7101k5zvyjhmfg983brhmhkd98n6"
# For example "agtvrsn_3901k6kz2c4ep8vm7tq5hd1xw9fb,agtvrsn_5201k7p4m9wcx3rd8ht2vq6ne1sa"
RELEASED_VERSIONS = set(os.environ["RELEASED_AGENT_VERSIONS"].split(","))

elevenlabs = ElevenLabs()


def conversation_token(version_id: str) -> str:
    if version_id not in RELEASED_VERSIONS:
        raise ValueError(f"Unknown agent version: {version_id}")
    response = elevenlabs.conversational_ai.conversations.get_webrtc_token(
        agent_id=AGENT_ID,
        version_id=version_id,
    )
    return response.token
```

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

const AGENT_ID = "agent_7101k5zvyjhmfg983brhmhkd98n6";
// For example "agtvrsn_3901k6kz2c4ep8vm7tq5hd1xw9fb,agtvrsn_5201k7p4m9wcx3rd8ht2vq6ne1sa"
const RELEASED_VERSIONS = new Set(process.env.RELEASED_AGENT_VERSIONS!.split(","));

const elevenlabs = new ElevenLabsClient();

export async function conversationToken(versionId: string): Promise<string> {
  if (!RELEASED_VERSIONS.has(versionId)) {
    throw new Error(`Unknown agent version: ${versionId}`);
  }
  const { token } = await elevenlabs.conversationalAi.conversations.getWebrtcToken({
    agentId: AGENT_ID,
    versionId,
  });
  return token;
}
```

将智能体 ID 保留在服务器端，这样客户端只能在该智能体的各个版本之间选择。

#### 使用令牌从前端启动会话

前端将构建中的版本发送到服务器，使用返回的令牌启动会话，并为该版本使用的每个客户端工具注册处理程序。`onUnhandledClientToolCall` 会报告当前版本没有处理程序的调用。SDK 已会向智能体返回此类调用的错误，因此回调只需记录日志：

```tsx
import { useConversation } from "@elevenlabs/react";

import release from "./agent-release.json";
import { cart } from "./cart";

export function useKioskConversation() {
  const conversation = useConversation({
    clientTools: {
      add_to_cart: async ({ sku }: { sku: string }) => {
        cart.add(sku);
        return { items: cart.size };
      },
    },
    onUnhandledClientToolCall: (call) => {
      console.error(`No handler for client tool ${call.tool_name}`);
    },
  });

  async function start() {
    const response = await fetch(
      `/api/conversation-token?version_id=${encodeURIComponent(release.versionId)}`
    );
    const conversationToken = await response.text();
    await conversation.startSession({ conversationToken });
  }

  return { conversation, start };
}
```

部署前端前，将该版本的版本号添加到 `RELEASED_AGENT_VERSIONS`；当没有已部署版本再使用它时，再移除该版本。

## 将破坏性更改作为新工具发布

为更改后的工具指定新名称，将其推送到分支，并发布固定到该分支版本的前端。已部署的版本仍固定在各自的版本上，继续使用旧工具。

#### 使用新名称定义工具

`push()` 按名称匹配工具，因此新名称会创建新工具，旧工具保持不变。这个版本的 `add_to_cart` 添加了必填的 `quantity` 参数：

```python
add_to_cart_v2 = (
    Tool.client("add_to_cart_v2", "Add a product to the shopper's cart")
    .param("sku", Schema.string().describe("The product SKU, e.g. TSH-0042"))
    .param("quantity", Schema.integer().describe("How many to add"))
    .options(expects_response=True)
)

agent = Agent(
    "Kiosk assistant",
    prompt="You help shoppers find products and add them to their cart.",
    tools=[add_to_cart_v2],
)
```

```typescript
const addToCartV2 = Tool.client("add_to_cart_v2", "Add a product to the shopper's cart")
  .param("sku", Schema.string().describe("The product SKU, e.g. TSH-0042"))
  .param("quantity", Schema.integer().describe("How many to add"))
  .options({ expectsResponse: true });

const agent = new Agent("Kiosk assistant", {
  prompt: "You help shoppers find products and add them to their cart.",
  tools: [addToCartV2],
});
```

使用 Python `@client_tool` 装饰器时，传入 `@client_tool(name="add_to_cart_v2")` 以保留函数名称。如果智能体提示词按名称提及该工具，也请更新提示词。

#### 推送到分支

从主分支当前版本创建分支，并将智能体推送至该分支。在分支上，`push()` 会创建 `add_to_cart_v2`，并将 `add_to_cart` 报告为 `"detached"`。主分支仍使用 `add_to_cart`：

```python
main = elevenlabs.conversational_ai.agents.get(agent_id=AGENT_ID)

branch = elevenlabs.conversational_ai.agents.branches.create(
    agent_id=AGENT_ID,
    parent_version_id=main.version_id,
    name="add-to-cart-quantity",
    description="add_to_cart_v2 takes a required quantity",
)

elevenlabs.conversational_ai.agents.push(
    agent,
    agent_id=AGENT_ID,
    branch_id=branch.created_branch_id,
)

pushed = elevenlabs.conversational_ai.agents.get(
    agent_id=AGENT_ID,
    branch_id=branch.created_branch_id,
)
with open("web/src/agent-release.json", "w") as f:
    json.dump({"versionId": pushed.version_id}, f)
```

```typescript
const main = await elevenlabs.conversationalAi.agents.get(AGENT_ID);

const branch = await elevenlabs.conversationalAi.agents.branches.create(AGENT_ID, {
  parentVersionId: main.versionId!,
  name: "add-to-cart-quantity",
  description: "add_to_cart_v2 takes a required quantity",
});

await elevenlabs.conversationalAi.agents.push(agent, {
  agentId: AGENT_ID,
  branchId: branch.createdBranchId,
});

const pushed = await elevenlabs.conversationalAi.agents.get(AGENT_ID, {
  branchId: branch.createdBranchId,
});
await writeFile("web/src/agent-release.json", JSON.stringify({ versionId: pushed.versionId }));
```

发布前先测试分支。[在不影响生产环境的情况下测试工具更改](/docs/zh/eleven-agents/customization/tools/tool-configuration/editing-tools#test-a-tool-change-without-affecting-production)介绍了如何针对分支运行测试和模拟工具。

#### 使用新处理程序发布前端

在基于该分支版本构建的版本中注册 `add_to_cart_v2`。将该版本添加到 `RELEASED_AGENT_VERSIONS`，然后部署前端。加载新版本的客户端会在分支版本上发起对话，仍使用旧版本的客户端则继续使用 `add_to_cart`。

不要通过[流量部署](/docs/zh/eleven-agents/operate/versioning#deploying-traffic)将客户端路由到新版本。部署会按对话 ID 在分支之间拆分对话，而不是按前端版本，因此可能将旧客户端发送到调用其无法处理工具的版本。

#### 合并分支并停用旧工具

发布上线后，将分支合并到主分支，这样主分支以及所有未固定版本便发起对话的内容都会使用 `add_to_cart_v2`。[合并分支](/docs/zh/eleven-agents/operate/versioning#merging-branches)介绍了如何预览和执行合并。

保留 `add_to_cart` 工具，直到没有已部署版本固定到使用它的版本。这些版本通过 ID 引用该工具，因此删除它会破坏仍在使用它的版本。删除前，[检查仍有哪些内容在使用它](/docs/zh/eleven-agents/customization/tools/tool-configuration/editing-tools#check-what-uses-a-tool-before-editing-it)，并从 `RELEASED_AGENT_VERSIONS` 中移除旧版本。

## 根据智能体检查处理程序

在 Python 中，[`tools.check_client_tools()`](/docs/zh/eleven-agents/customization/agents-as-code/tools#define-a-client-tool-from-a-function) 会将 `@client_tool` 函数与智能体主分支上的客户端工具进行比较。它会报告智能体没有对应工具的每个函数，以及所有不同的参数。在 CI 中使用 `strict=True` 运行它，以阻止处理程序与智能体不匹配的版本发布。JavaScript SDK 暂无等效功能。

## 后续步骤

#### [版本控制](/docs/zh/eleven-agents/operate/versioning)

创建分支、合并分支并读取特定版本

#### [安全编辑工具](/docs/zh/eleven-agents/customization/tools/tool-configuration/editing-tools)

工具编辑如何与分支和版本交互

#### [以代码定义智能体](/docs/zh/eleven-agents/customization/agents-as-code/agents)

定义智能体及其工具，并通过一次调用推送

#### [客户端工具](/docs/zh/eleven-agents/customization/tools/client-tools)

在应用中注册客户端工具处理程序