跳到导航

以代码管理工具

通过 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)要求一组可选属性中至少有一个或全部存在。

标头与身份验证

标头值可来自以下 4 个位置之一。敏感内容请使用密钥或环境变量,避免值出现在工具配置中:

构造器标头值为
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)
)

构建系统工具

系统工具内置于平台中。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 何时转接,目标使用与以代码管理工作流相同的 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() 返回智能体内置工具的条目。

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。

要修改请求体属性,请读取请求体架构,再次设置该属性,然后设置请求体:

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 为相同工具写入的文件也完全一致,因此差异很小。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())

典型设置与工作流相同:先通过 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 包含请求体,或 POST、PUT、PATCH 没有请求体。
  • 路径、查询和请求体中有多个参数使用相同名称。
  • 必填属性使用 omit()、非字符串架构使用 choices(),或常量与架构类型不匹配。
  • 转接工具没有目标、目标类型错误,或 SIP URI 目标未使用 SIP REFER 转接。
  • 选项不适用于该工具类型,或超时超出范围。

SDK 中较新的工具类型

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