跳到导航

以代码定义工具

使用 Python 和 JavaScript SDK 构建、编辑并管理智能体工具版本

概述

一个工具以配置形式存储,其参数采用嵌套 JSON 架构。手写该配置意味着必须让路径参数与 URL 保持同步、让 required 列表与其属性保持同步,并为每个参数指定恰好一个值来源。Python 和 JavaScript SDK 中的工具构建器让你通过链式方法调用描述同一个工具,随后生成 tools.create() 和 tools.update() 已接受的请求。

可用于:

  • 在代码中定义 webhook、客户端和系统工具,并像审查其他代码更改一样审查它们。
  • 加载工具、更改一个参数,然后推送回去,同时不影响其余配置。
  • 在版本控制中将工具存储为 JSON,并在 CI 中验证。

构建器完全在 SDK 中运行,不会调用新的 API 端点,且它构建的任何内容都可以在控制台中打开和编辑。

要求

  • Python:elevenlabs 包。构建器从 elevenlabs.agent_tools 导入。
  • JavaScript:@elevenlabs/elevenlabs-js 包。构建器从包根目录导出。

构建 webhook 工具

Tool.webhook(name, description) 会创建一个webhook 工具。名称和描述是 LLM 决定是否调用该工具时看到的内容。此示例会通过调用者提供的编号查询订单,从工作区密钥中发送 API 密钥,并将订单状态存储在动态变量中:

from elevenlabs import ElevenLabs
from elevenlabs.agent_tools import Header, Schema, Tool
elevenlabs = ElevenLabs()
get_order = (
Tool.webhook("get_order", "Look up an order by the number the caller gives")
.get("https://api.example.com/orders/{order_id}")
.path_param("order_id", Schema.string().describe("The order number, e.g. A-1042"))
.query_param("include", Schema.string().constant("items"))
.header("Authorization", Header.secret("sec_orders_api"))
.assign("order_status", "order.status")
.options(response_timeout_secs=10)
)
tool = elevenlabs.conversational_ai.tools.create(request=get_order.build())

请求方法会设置 HTTP 方法和 URL。URL 中的 {name} 占位符由路径参数填充:

PythonJavaScript设置内容
get(url), post(url), put(url), patch(url), delete(url)相同方法和 URL。POST、PUT 和 PATCH 需要请求体;GET 不能有请求体。
path_param(name, schema)pathParam(name, schema)路径参数,对应 URL 中的 {name} 占位符。
query_param(name, schema)queryParam(name, schema)查询参数。
body(schema)body(schema)请求体。必须是对象架构。
response(schema)response(schema)响应体架构。必须是对象架构。
header(name, value)header(name, value)请求标头。参见标头和身份验证。
auth(connection)auth(connection)要使用的身份验证连接。
assign(variable, path)assign(variable, path)将响应中 path(点记法)处的值存储到动态变量中。

设置名称已存在的参数或标头会将其替换,并保留原位置。remove_path_param()、remove_query_param()、remove_header() 和 remove_assignment()(JavaScript 中为 removePathParam() 等)会移除对应项。路径、查询和请求体中的参数名称必须唯一。

请求体是逐个属性构建的对象架构:

refund = (
Tool.webhook("issue_refund", "Refund an order the caller asked to return")
.post("https://api.example.com/refunds")
.body(
Schema.object()
.property("order_id", Schema.string().from_variable("order_id"))
.property(
"reason",
Schema.string().describe("Why the caller wants a refund").choices(["damaged", "late", "other"]),
)
.property("note", Schema.string().describe("Anything else the caller said").optional())
)
)

参数架构

Schema 用于构建 webhook 和客户端工具使用的参数架构。每个方法都会返回新架构,不会更改调用它的架构,因此可以定义一次架构,并在多个工具中使用。

构造函数构建内容
Schema.string(), Schema.integer(), Schema.number(), Schema.bool()字面值
Schema.object()对象。使用 property() 添加属性。
Schema.array(items)元素匹配 items 架构的数组

值的来源

每个字面值无论出现在哪里,都需要恰好一个值来源:参数、请求体、响应架构,或对象和数组内部。对象或数组也可以有一个值来源,此时会提供整个值。

PythonJavaScript值
describe(text)describe(text)由 LLM 根据 text 指引提供。
from_variable(name)fromVariable(name)工具运行时从动态变量读取。
constant(value)constant(value)始终为 value。
system_provided()systemProvided()工具运行时由系统填充。仅限字面值。
omit()omit()从请求中省略。仅适用于可选属性。

对于对象或数组,describe() 会为 LLM 记录容器说明,而每个属性或元素仍有自己的值来源。

其他架构方法

PythonJavaScript作用
optional()optional()将属性设为可选。除非标记为可选,否则属性均为必填。
choices(values)choices(values)将字符串限制为一组固定值,由 LLM 从中选择。
allowed_from(variable)allowedFrom(variable)拒绝不在动态变量所存列表中的 LLM 值。需要 describe()。
property(name, schema) / without(name)property(name, schema) / without(name)添加、替换或移除对象属性。被替换的属性会保留原位置。
require_any_of(names) / require_all_of(names)requireAnyOf(names) / requireAllOf(names)要求一组可选属性中至少有一个或全部存在。

标头和身份验证

标头值可来自四个位置之一。对于任何敏感信息,请使用密钥或环境变量,以免值出现在工具配置中:

构造函数标头值为
Header.value(text)固定文本。
Header.secret(id)工作区密钥存储中的密钥。
Header.variable(name)动态变量,在工具运行时读取。
Header.env_var(label) / Header.envVar(label)工作区环境变量,会针对当前环境解析。

AuthConnection.id(id) 使用工作区中按 ID 指定的身份验证连接。AuthConnection.env_var(label) / AuthConnection.envVar(label) 会从环境变量中选择它,因此同一工具配置可在各环境中使用不同连接。

from elevenlabs.agent_tools import AuthConnection, Header
update_profile = (
Tool.webhook("update_profile", "Update the caller's email address")
.put("https://api.example.com/profiles/{profile_id}")
.path_param("profile_id", Schema.string().from_variable("profile_id"))
.body(Schema.object().property("email", Schema.string().describe("The new email address")))
.header("X-Api-Key", Header.env_var("profiles_api_key"))
.auth(AuthConnection.env_var("profiles_oauth"))
)

构建客户端工具

Tool.client(name, description) 可创建一个客户端工具,它会在承载对话的应用中运行。使用 param(name, schema) 添加参数。需要让智能体等待应用返回结果时,设置 expects_response / expectsResponse。该结果来自承载对话的应用,因此在用户设备上运行时不可信。参阅信任与安全:

show_map = (
Tool.client("show_store_map", "Show the caller a map of the nearest store")
.param("store_id", Schema.string().describe("The store to show"))
.options(expects_response=False)
)

通过函数定义客户端工具

客户端工具包含两部分:智能体看到的配置,以及智能体调用工具时应用运行的处理函数。@client_tool 装饰器可通过一个函数定义这两部分。函数名会成为工具名称,文档字符串会成为描述,带类型的参数会成为工具参数。智能体调用工具时,会运行同一个函数。

@client_tool 可用于 Python SDK。在其他 SDK 中,请使用 Tool.client() 构建配置,并单独注册处理函数。

from typing import List, Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
from elevenlabs import ElevenLabs
from elevenlabs.agent_tools import Param, client_tool
from elevenlabs.conversational_ai.conversation import ClientTools, Conversation
# This runs on a shopping kiosk: one shopper, one conversation at a time, so the
# module-level `cart` and `screen` belong to that shopper.
class Address(TypedDict):
"""A delivery address.
Attributes:
street: Street and house number
city: City
"""
street: str
city: str
postcode: NotRequired[Annotated[str, Param("Postcode, if the shopper knows it")]]
@client_tool(expects_response=True, response_timeout_secs=5)
def add_to_cart(
sku: str,
quantity: int = 1,
size: Optional[Literal["S", "M", "L", "XL"]] = None,
store_id: Annotated[str, Param(from_variable="store_id")] = "",
) -> dict:
"""Add a product to the shopper's cart and report how many items it holds.
Args:
sku: The product SKU, e.g. TSH-0042
quantity: How many to add
size: Clothing size, only for apparel
"""
cart.add(sku, quantity, size, store_id)
return {"items": len(cart)}
@client_tool
def start_checkout(
delivery: Literal["pickup", "home"],
address: Optional[Address] = None,
gift_tags: Optional[List[Annotated[str, Param("The name for one gift tag")]]] = None,
) -> str:
"""Move the screen to checkout.
Args:
delivery: Pick up in store or deliver home
address: Only for home delivery
gift_tags: Names to print on gift tags
"""
screen.checkout(delivery, address, gift_tags)
return "checkout started"
elevenlabs = ElevenLabs()
# At deploy time, from CI or a script: push the tools' schemas, then add their IDs to the agent.
# No build() step: pass the function itself. Use tools.update(tool_id, request=fn) once a tool exists.
for fn in (add_to_cart, start_checkout):
elevenlabs.conversational_ai.tools.create(request=fn)
# At runtime, in the kiosk app: check the functions still match the agent's tools, then register them
elevenlabs.conversational_ai.tools.check_client_tools("your-agent-id", add_to_cart, start_checkout)
client_tools = ClientTools()
client_tools.register_tools(add_to_cart, start_checkout)
conversation = Conversation(elevenlabs, "your-agent-id", requires_auth=True, client_tools=client_tools)

请在部署时推送 schema,而非每次对话开始时。运行时创建工具会在每次运行时新建一个工具,最后启动的客户端会替换所有用户智能体的工具。

工具的 schema 存储在服务器上,供所有与该智能体对话的客户端共享, 包括仍在运行旧版本应用的副本。推送的更改会立即影响所有客户端。 添加可选参数是安全的。重命名或移除参数、更改其类型,或将其设为必填项, 都会导致已部署的客户端失效。因此,请使用新工具名称发布这类更改, 例如 add_to_cart_v2,并在没有客户端使用旧工具后将其移除。 发布客户端工具更改介绍了具体流程。

应用启动时,tools.check_client_tools() 可捕获不匹配情况。它会将每个函数与智能体上同名的客户端工具进行比较:对于智能体没有工具的每个函数,以及名称、类型、选项或必填状态不同的每个参数,都会发出 ToolSchemaDriftWarning。描述和值来源会被忽略,因为它们不会改变函数接收的内容。传入 strict=True 则会改为抛出 ToolSchemaDriftError,例如可用于阻止部署。

每个参数都需要类型提示。该提示会设置参数的 schema:

类型提示参数 schema
str、int、float、boolSchema.string()、Schema.integer()、Schema.number()、Schema.bool()
Literal["a", "b"]限定为这些选项的字符串
List[T]T 的数组
TypedDict对象。NotRequired 字段,以及 total=False 的 TypedDict 中所有字段,均为可选字段。
Optional[T],或任何带默认值的参数标记为可选的 T

其他类型(如 dict 或两种类型的联合)会抛出 TypeError,并指出参数名称。

每个参数还需要一个值来源,与 Schema 相同。默认情况下,其值由 LLM 提供,并由文档字符串中该参数所在行引导。装饰器会读取 Google 风格的 Args: 部分和 reStructuredText 的 :param name: 行;TypedDict 字段的描述则来自类文档字符串的 Attributes: 部分。将类型包装在 Annotated[T, Param(...)] 中,可直接设置值来源:

Param 参数值
Param("text")由 LLM 提供,并由 text 引导。优先于文档字符串。
from_variable="name"工具运行时从动态变量读取。
constant=value始终为 value。

@client_tool 还接受 name 和 description,可覆盖函数名和文档字符串。其余关键字参数(如 expects_response)会传递给 options()。

装饰后的函数具有以下行为:

  • 无需 build() 步骤。 将函数本身传给 tools.create() 或 tools.update()。函数定义时就会检查,因此 build() 原本会报告的问题(例如参数没有描述)会在导入模块时抛出 ToolValidationError。
  • 它仍是一个函数。 可以直接调用,例如在测试中。
  • fn.tool 是普通的客户端工具构建器。 可搭配 to_json_string() 使用,或设置签名无法表达的内容,例如 system_provided() 或 require_any_of()。
  • ClientTools.register_tools() 会按工具名称注册每个函数。 智能体调用工具时,函数会以关键字参数形式接收智能体发送的参数。未声明的键(如 tool_call_id)会被丢弃,除非函数接受 **kwargs。支持 async 函数。
  • 其状态由进程中的所有对话共享。 模块级函数只能访问模块级状态。这适合在设备上承载单个对话的场景;但对于运行多个对话的服务器,应在接收该对话状态的函数内定义这些函数,并通过该对话自己的 ClientTools 注册它们。

装饰器不会改变函数的运行位置或谁能看到其调用。客户端工具信任规则同样适用。

该装饰器仅定义客户端工具。Webhook 工具在服务器上运行,需要 URL、每个参数的位置及请求头, 而这些都无法通过函数签名表达。请使用 Tool.webhook() 构建 Webhook 工具。

构建系统工具

系统工具内置于平台中。每种工具在 SystemTool 上都有对应构造函数,接收该工具的设置:

PythonJavaScript
SystemTool.end_call()SystemTool.endCall()
SystemTool.skip_turn(wait_timeout_secs=...)SystemTool.skipTurn({ waitTimeoutSecs })
SystemTool.language_detection(...)SystemTool.languageDetection(options?)
SystemTool.play_keypad_touch_tone(...)SystemTool.playKeypadTouchTone(options?)
SystemTool.voicemail_detection(voicemail_message=...)SystemTool.voicemailDetection({ voicemailMessage })
SystemTool.knowledge_base(enabled_strategies=...)SystemTool.knowledgeBase({ enabledStrategies })
SystemTool.transfer_to_number(...)SystemTool.transferToNumber(options?)
SystemTool.transfer_to_agent()SystemTool.transferToAgent()

两个转接工具通过 transfer(condition, destination, options) 接收目标。条件会告诉 LLM 何时转接,目标使用与以代码定义 workflow相同的 Destination。转接至 SIP URI 需要使用 SIP REFER 转接:

from elevenlabs.agent_tools import SystemTool
from elevenlabs.agent_workflows import Destination
transfer = (
SystemTool.transfer_to_number()
.transfer("Caller asks for billing", Destination.phone("+15551234567"))
.transfer("Caller is a reseller partner", Destination.sip("sip:partners@pbx.example.com"), transfer_type="sip_refer")
)
to_sales = SystemTool.transfer_to_agent().transfer(
"Caller wants to buy something", Destination.agent("agent_sales"), transfer_message="Connecting you to sales"
)

工具选项

所有类型工具共用的设置通过 options() 指定:Python 使用关键字参数,JavaScript 使用对象。其名称与 API 中工具配置字段一致:

适用对象PythonJavaScript
所有工具name, description, response_timeout_secs, interruption_mode, pre_tool_speech, tool_call_sound, tool_error_handling_mode, …name, description, responseTimeoutSecs, interruptionMode, preToolSpeech, toolCallSound, toolErrorHandlingMode, …
Webhook 工具execution_mode, content_type, response_filter, follow_redirects, follow_redirects_allowed_domains, dynamic_variable_placeholdersexecutionMode, contentType, responseFilter, followRedirects, followRedirectsAllowedDomains, dynamicVariablePlaceholders
客户端工具execution_mode, expects_response, dynamic_variable_placeholdersexecutionMode, expectsResponse, dynamicVariablePlaceholders

Webhook 工具的响应超时时间为 5 至 300 秒。客户端工具为 1 至 120 秒,或设为 -1 以无限等待;后者需要 expects_response / expectsResponse。follow_redirects / followRedirects 需要提供允许的域名列表。

将工具附加到智能体

Webhook 和客户端工具通过 tools.create() 独立创建,并通过 ID 附加到智能体,因此一个工具可以由多个智能体共享。系统工具属于智能体配置:build_config() / buildConfig() 会返回智能体内置工具的条目。

智能体构建器可为你完成这些步骤: 将 Tool 对象传给 Agent,agents.push() 会创建或更新它们,并附加其 ID。

from elevenlabs import AgentConfig, BuiltInToolsOutput, ConversationalConfig, PromptAgentApiModelOutput
order_tool = elevenlabs.conversational_ai.tools.create(request=get_order.build())
agent = elevenlabs.conversational_ai.agents.create(
name="Support line",
conversation_config=ConversationalConfig(
agent=AgentConfig(
prompt=PromptAgentApiModelOutput(
prompt="You are a support agent for Acme.",
tool_ids=[order_tool.id],
built_in_tools=BuiltInToolsOutput(
end_call=SystemTool.end_call().build_config(),
transfer_to_number=transfer.build_config(),
),
)
)
),
)

智能体的 prompt.tools 字段会内联保存工具配置,现已弃用。它无法与 tool_ids 组合使用; 请求中包含该字段时,智能体的内置工具会被其中包含的系统工具替换。 请改用 tools.create() 创建工具,并通过 ID 附加。

编辑现有工具

Tool.from_response() / Tool.fromResponse() 可加载由 tools.get() 返回的工具。构建器未建模的字段以及 API 填充的默认值都会保留,因此推送回去时只会更改你修改的内容。as_webhook()、as_client() 和 as_system()(JavaScript 中为 asWebhook() 等)会返回可编辑的带类型工具;若工具属于其他类型,则返回 None / undefined。

要更改 body 属性,请读取 body schema,再次设置该属性,然后设置 body:

from elevenlabs.agent_tools import ObjectSchema
loaded = Tool.from_response(elevenlabs.conversational_ai.tools.get("tool_id")).as_webhook()
if loaded is None:
raise ValueError("Not a webhook tool")
body = loaded.body_schema
assert isinstance(body, ObjectSchema)
loaded.body(body.property("reason", Schema.string().describe("Why the caller wants a refund")))
loaded.query_param("locale", Schema.string().describe("The caller's language").optional())
elevenlabs.conversational_ai.tools.update("tool_id", request=loaded.build())

在版本控制中存储工具

to_json_string() / toJSONString() 会以 API 的传输格式写入工具:使用 snake_case 键,每一级排序,并采用 2 空格缩进。其结构与 CLI 在 tool_configs/ 目录中保存的格式相同;两个 SDK 为同一工具写出的文件也完全一致,因此 diff 会保持简洁。Tool.from_json() / Tool.fromJSON() 可将其读回。

from pathlib import Path
from elevenlabs.agent_tools import Tool
Path("tool_configs/get_order.json").write_text(get_order.to_json_string())
stored = Tool.from_json(Path("tool_configs/get_order.json").read_text())
elevenlabs.conversational_ai.tools.update("tool_id", request=stored.build())

典型设置与 workflow相同:先用 elevenlabs tools pull 初始化文件,直接编辑或使用构建器编辑,在每个拉取请求的 CI 中运行 Tool.from_json(file).build() / Tool.fromJSON(file).build(),并在合并时通过 tools.update() 或 elevenlabs tools push 推送。

验证

链式调用本身不会失败。build()、build_config() / buildConfig()、to_json() / toJSON() 和 to_json_string() / toJSONString() 会检查整个工具,并抛出单个 ToolValidationError。其 issues 会列出每个问题,每个问题均包含 code、message 以及所涉及部分的 path,例如 body.reason。

from elevenlabs.agent_tools import ToolValidationError
try:
request = refund.build()
except ToolValidationError as err:
for issue in err.issues:
print(issue.code, issue.path, issue.message)

错误包括:

  • URL 占位符没有对应的路径参数,或路径参数没有对应的占位符。{{system__env_api_host}} 等环境变量模板不是占位符。
  • 字面量没有值来源,或有多个值来源。
  • GET 请求包含 body,或 POST、PUT、PATCH 请求没有 body。
  • 路径、查询和 body 中有多个参数使用相同名称。
  • 在必填属性上使用 omit()、在非字符串 schema 上使用 choices(),或常量不符合 schema 类型。
  • 转接工具没有目标、目标类型不正确,或 SIP URI 目标未使用 SIP REFER 转接。
  • 某个选项不适用于该工具类型,或超时时间超出允许范围。

比 SDK 更新的工具类型

从 API 或文件加载的工具可能属于构建器无法编辑的类型,例如 MCP 工具。它会以 "other" 类型加载,并可通过 from_json() / fromJSON() 和 to_json_string() / toJSONString() 原样往返处理;build() 会通过 on_warning / onWarning 将其报告为警告。