> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# 客户端工具

**客户端工具**让助手能够执行客户端函数。与[ webhook 工具](/docs/zh/eleven-agents/customization/tools/webhook-tools)不同，客户端工具可让助手执行触发浏览器事件、运行客户端函数或向 UI 发送通知等操作。

## 概述

应用可能需要助手直接与用户环境交互。客户端工具让助手能够执行客户端操作。

以下是一些适合使用客户端工具的示例：

* **触发 UI 事件**：让助手触发浏览器事件，例如警报、模态框或通知。
* **与 DOM 交互**：让助手操作文档对象模型（DOM），以动态更新内容或引导用户使用复杂界面。

> **Info**
>
> 如需调用服务器端 API，请改用 [webhook 工具](/docs/zh/eleven-agents/customization/tools/webhook-tools)。

## 指南

### 前提条件

* 一个 [ElevenLabs 账户](https://elevenlabs.io)
* 已配置的 ElevenLabs 对话式 AI 智能体（[在此创建](https://elevenlabs.io/app/agents)）

#### 创建新的客户端工具

配置一个名为 `logMessage` 的客户端工具，并添加必填字符串参数 `message`（“要在控制台记录的消息”）。

#### 通过控制台添加

前往智能体控制台。在 **工具** 部分，点击 **添加工具**。确保 **工具类型** 设置为 **客户端**。然后按以下内容配置：

| 设置 | 参数                    |
| -- | --------------------- |
| 名称 | logMessage            |
| 描述 | 使用此客户端工具将消息记录到用户的客户端。 |

然后创建一个新参数 `message`，按以下配置：

| 设置   | 参数                      |
| ---- | ----------------------- |
| 数据类型 | String                  |
| 标识符  | message                 |
| 必填   | true                    |
| 描述   | 要在控制台记录的消息。确保消息内容清晰且相关。 |

![logMessage 客户端工具设置](/docs/_fern-img/f7ed25d49a2a814b76112f3e385d471e0dc8444705e11f2f6fad0bd23f1eae12.webp)

#### 通过 CLI 添加

#### 创建工具配置文件

将以下内容保存为 `tool_configs/log_message.json`：

```json
{
  "type": "client",
  "name": "logMessage",
  "description": "Use this client-side tool to log a message to the user's client.",
  "expects_response": false,
  "parameters": {
    "type": "object",
    "properties": {
      "message": {
        "type": "string",
        "description": "The message to log in the console."
      }
    },
    "required": ["message"]
  }
}
```

#### 添加工具

```bash
elevenlabs tools add "logMessage" --type "client" --config-path ./tool_configs/log_message.json
```

#### 在智能体中引用工具

编辑 `agent_configs/<agent-name>.json`，将工具 ID 添加到 `conversation_config.agent.prompt.tool_ids`，然后推送：

```bash
elevenlabs agents push --agent "<agent-name>"
```

#### 通过 API 添加

```python
from elevenlabs import ElevenLabs, ToolRequestModel

elevenlabs = ElevenLabs()

tool = elevenlabs.conversational_ai.tools.create(
    request=ToolRequestModel(
        tool_config={
            "type": "client",
            "name": "logMessage",
            "description": "Use this client-side tool to log a message to the user's client.",
            "expects_response": False,
            "parameters": {
                "type": "object",
                "properties": {
                    "message": {
                        "type": "string",
                        "description": "The message to log in the console.",
                    }
                },
                "required": ["message"],
            },
        }
    )
)

elevenlabs.conversational_ai.agents.update(
    agent_id="agent_7101k5zvyjhmfg983brhmhkd98n6",
    conversation_config={
        "agent": {"prompt": {"tool_ids": [tool.id]}},
    },
)
```

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

const elevenlabs = new ElevenLabsClient();

const tool = await elevenlabs.conversationalAi.tools.create({
  toolConfig: {
    type: "client",
    name: "logMessage",
    description: "Use this client-side tool to log a message to the user's client.",
    expectsResponse: false,
    parameters: {
      type: "object",
      properties: {
        message: {
          type: "string",
          description: "The message to log in the console.",
        },
      },
      required: ["message"],
    },
  },
});

await elevenlabs.conversationalAi.agents.update("agent_7101k5zvyjhmfg983brhmhkd98n6", {
  conversationConfig: {
    agent: { prompt: { toolIds: [tool.id] } },
  },
});
```

#### 在代码中注册客户端工具

与 webhook 工具不同，客户端工具需要在代码中注册。

使用以下代码注册客户端工具：

**`Python`**

```python title="Python" focus={4-16}
from elevenlabs import ElevenLabs
from elevenlabs.conversational_ai.conversation import Conversation, ClientTools

def log_message(parameters):
    message = parameters.get("message")
    print(message)

client_tools = ClientTools()
client_tools.register("logMessage", log_message)

conversation = Conversation(
    client=ElevenLabs(api_key="your-api-key"),
    agent_id="agent_7101k5zvyjhmfg983brhmhkd98n6",
    requires_auth=True,
    client_tools=client_tools,
    # ...
)

conversation.start_session()
```

**`JavaScript`**

```javascript title="JavaScript" focus={2-10}
// ...
const conversation = await Conversation.startSession({
  // ...
  clientTools: {
    logMessage: async ({message}) => {
      console.log(message);
    }
  },
  // ...
});
```

**`Swift`**

```swift title="Swift" focus={2-10}
// ...
var clientTools = ElevenLabsSDK.ClientTools()

clientTools.register("logMessage") { parameters async throws -> String? in
    guard let message = parameters["message"] as? String else {
        throw ElevenLabsSDK.ClientToolError.invalidParameters
    }
    print(message)
    return message
}
```

> **Note**
>
> 智能体配置中的工具和参数名称区分大小写，且**必须**与代码中注册的名称一致。

#### 测试

与智能体发起对话，并说出类似以下内容：

> *在控制台中记录一条显示 Hello World 的消息*

控制台中应会出现一条 `Hello World` 日志。

#### 后续步骤

现在已设置基本客户端事件，你可以：

* 探索更复杂的客户端工具，例如打开模态框、跳转页面或与 DOM 交互。
* 将客户端工具与服务器端 webhook 结合，实现全栈交互。
* 使用客户端工具提升用户参与度，并在对话期间提供实时反馈。

### 将客户端工具结果传递至对话上下文

如果希望智能体接收客户端工具返回的数据，请确保在工具配置中勾选 **等待响应** 选项。

![客户端工具配置中的等待响应选项](/docs/_fern-img/0ecc615fc9f25446b67369fd3e010e34b39549a22146a2483ea17251206caf1e.webp)

添加客户端工具后，当调用该函数时，智能体会等待其响应，并将响应追加到对话上下文中。

**`Python`**

```python title="Python"
def get_customer_details():
    # Fetch customer details (e.g., from an API or database)
    customer_data = {
        "id": 123,
        "name": "Alice",
        "subscription": "Pro"
    }
    # Return the customer data; it can also be a JSON string if needed.
    return customer_data

client_tools = ClientTools()
client_tools.register("getCustomerDetails", get_customer_details)

conversation = Conversation(
    client=ElevenLabs(api_key="your-api-key"),
    agent_id="agent_7101k5zvyjhmfg983brhmhkd98n6",
    requires_auth=True,
    client_tools=client_tools,
    # ...
)

conversation.start_session()
```

**`JavaScript`**

```javascript title="JavaScript"
const clientTools = {
  getCustomerDetails: async () => {
    // Fetch customer details (e.g., from an API)
    const customerData = {
      id: 123,
      name: "Alice",
      subscription: "Pro"
    };
    // Return data directly to the agent.
    return customerData;
  }
};

// Start the conversation with client tools configured.
const conversation = await Conversation.startSession({ clientTools });
```

在此示例中，当智能体调用 **getCustomerDetails** 时，函数会在客户端执行，智能体将收到返回数据，并将其用于对话上下文。响应中的值也可选择性地分配给动态变量，类似于 [webhook 工具](https://elevenlabs.io/docs/eleven-agents/customization/tools/webhook-tools)。请注意，系统工具无法更新动态变量。

### 故障排除

#### 工具未触发

* 确保智能体配置中的工具和参数名称与代码中注册的名称一致。
* 在智能体控制台中查看对话记录，确认工具是否正在执行。

#### 控制台错误

* 打开浏览器控制台检查是否存在错误。
* 确保代码能妥善处理未定义或意外的参数。

## 最佳实践

#### 使用直观的工具名称和详细说明

如果发现助手没有调用正确的工具，可能需要更新工具名称和说明，让助手更清楚地理解何时应选择各个工具。避免使用缩写或首字母缩略词来简化工具和参数名称。

还可以详细说明应在何时调用工具。对于复杂工具，应为每个参数添加说明，帮助助手了解需要向用户询问哪些信息来收集该参数。

#### 使用直观的工具参数名称和详细说明

为工具参数使用清晰且描述性强的名称。适用时，请在说明中指定参数的预期格式（例如日期采用 YYYY-mm-dd 或 dd/mm/yy）。

#### 考虑在助手的系统提示词中提供有关如何及何时调用工具的补充信息

在系统提示词中提供清晰指示，可显著提高助手调用工具的准确性。例如，可使用以下指示引导助手：

```plaintext
Use `check_order_status` when the user inquires about the status of their order, such as 'Where is my order?' or 'Has my order shipped yet?'.
```

为复杂场景提供上下文。例如：

```plaintext
Before scheduling a meeting with `schedule_meeting`, check the user's calendar for availability using check_availability to avoid conflicts.
```

#### LLM 选择

> **Warning**
>
> 使用工具时，建议选择 GPT 5.2、Gemini-2.5-Flash 或
> Claude Sonnet 4.5 等高智能模型，并避免使用 Gemini-2.0-Flash。

请注意，LLM 的选择会影响函数调用的成功率。某些 LLM 可能难以从对话中提取相关参数。