Skip to navigation

Tools as code

Build, edit, and version agent tools with the Python and JavaScript SDKs

Overview

A tool is stored as a config with nested JSON schemas for its parameters. Writing that config by hand means you have to keep path parameters in step with the URL, required lists in step with their properties, and give every parameter exactly one value source. The tool builder in the Python and JavaScript SDKs lets you describe the same tool with chained method calls. It then produces the request that tools.create() and tools.update() already accept.

Use it to:

  • Define webhook, client and system tools in code and review them like any other code change.
  • Load a tool, change one parameter, and push it back without disturbing the rest of its config.
  • Store tools as JSON in version control and validate them in CI.

The builder runs entirely in the SDK. It calls no new API endpoints, and anything it builds can be opened and edited in the dashboard.

Requirements

  • Python: the elevenlabs package. The builder is imported from elevenlabs.agent_tools.
  • JavaScript: the @elevenlabs/elevenlabs-js package. The builder is exported from the package root.

Build a webhook tool

Tool.webhook(name, description) starts a webhook tool. The name and description are what the LLM sees when it decides whether to call the tool. This example looks up an order by the number the caller gives, sends an API key from the workspace’s secrets, and stores the order’s status in a dynamic variable:

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

The request methods set the HTTP method and URL. {name} placeholders in the URL are filled from path parameters:

PythonJavaScriptSets
get(url), post(url), put(url), patch(url), delete(url)sameThe method and URL. POST, PUT and PATCH need a body; GET can’t have one.
path_param(name, schema)pathParam(name, schema)A path parameter, for the {name} placeholder in the URL.
query_param(name, schema)queryParam(name, schema)A query parameter.
body(schema)body(schema)The request body. Must be an object schema.
response(schema)response(schema)The response body schema. Must be an object schema.
header(name, value)header(name, value)A request header. See Headers and authentication.
auth(connection)auth(connection)The auth connection to use.
assign(variable, path)assign(variable, path)Stores the value at path in the response (dot notation) in a dynamic variable.

Setting a parameter or header whose name already exists replaces it and keeps its position. remove_path_param(), remove_query_param(), remove_header() and remove_assignment() (removePathParam() and so on in JavaScript) take one out. Parameter names must be unique across the path, query and body.

A body is an object schema built property by property:

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

Parameter schemas

Schema builds the parameter schemas that webhook and client tools use. Every method returns a new schema and leaves the one it was called on unchanged, so you can define a schema once and use it in several tools.

ConstructorBuilds
Schema.string(), Schema.integer(), Schema.number(), Schema.bool()A literal value
Schema.object()An object. Add properties with property().
Schema.array(items)An array whose elements match the items schema

Where a value comes from

Every literal needs exactly one value source, wherever it appears: in a parameter, in a body, in a response schema, or inside an object or array. An object or array can have one too, which then supplies the whole value.

PythonJavaScriptThe value
describe(text)describe(text)Is provided by the LLM, guided by text.
from_variable(name)fromVariable(name)Is read from a dynamic variable when the tool runs.
constant(value)constant(value)Is always value.
system_provided()systemProvided()Is filled in by the system when the tool runs. Literals only.
omit()omit()Is left out of the request. Only for an optional property.

On an object or array, describe() documents the container for the LLM, and each property or element still has its own source.

Other schema methods

PythonJavaScriptDoes
optional()optional()Makes a property optional. Properties are required unless marked optional.
choices(values)choices(values)Limits a string to a fixed set of values, which the LLM picks from.
allowed_from(variable)allowedFrom(variable)Rejects an LLM value that isn’t in the list held by a dynamic variable. Needs describe().
property(name, schema) / without(name)property(name, schema) / without(name)Adds, replaces or removes an object property. A replaced property keeps its position.
require_any_of(names) / require_all_of(names)requireAnyOf(names) / requireAllOf(names)Requires at least one, or all, of a group of optional properties.

Headers and authentication

A header value comes from one of four places. Use a secret or an environment variable for anything sensitive, so the value never appears in the tool config:

ConstructorThe header value is
Header.value(text)Fixed text.
Header.secret(id)A secret from the workspace’s secret store.
Header.variable(name)A dynamic variable, read when the tool runs.
Header.env_var(label) / Header.envVar(label)A workspace environment variable, resolved for the current environment.

AuthConnection.id(id) uses an auth connection from the workspace by ID. AuthConnection.env_var(label) / AuthConnection.envVar(label) picks it from an environment variable, so the same tool config can use a different connection in each environment.

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

Build a client tool

Tool.client(name, description) starts a client tool, which runs in the application that holds the conversation. Add its parameters with param(name, schema). Set expects_response / expectsResponse when the agent should wait for your application’s result. That result comes from whichever application holds the conversation, so on a user’s device it can’t be trusted. See trust and security:

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)
)

Define a client tool from a function

A client tool has two halves: the config the agent sees, and the handler your application runs when the agent calls it. The @client_tool decorator defines both from one function. The function’s name becomes the tool’s name, its docstring becomes the description, and its typed parameters become the tool’s parameters. When the agent calls the tool, the same function runs.

@client_tool is available in the Python SDK. In other SDKs, build the config with Tool.client() and register the handler separately.

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)

Push the schema when you deploy, not each time a conversation starts. Creating the tool at runtime makes a new tool on every run, and the last client to start replaces the agent’s tools for everyone.

A tool’s schema is stored on the server and shared by every client that talks to the agent, including copies of your app that still run an older version. A pushed change reaches all of them right away. Adding an optional parameter is safe. Renaming or removing a parameter, changing its type, or making it required breaks clients that are already deployed, so ship that kind of change under a new tool name, such as add_to_cart_v2, and remove the old tool once no client uses it. Release client tool changes walks through it.

tools.check_client_tools() catches a mismatch when the app starts. It compares each function with the client tool of the same name on the agent, and issues a ToolSchemaDriftWarning for each function the agent has no tool for, and for each parameter whose name, type, choices or required status differs. Descriptions and value sources are ignored, because they don’t change what the function receives. Pass strict=True to raise a ToolSchemaDriftError instead, for example to stop a deployment.

Each parameter needs a type hint. The hint sets the parameter’s schema:

Type hintParameter schema
str, int, float, boolSchema.string(), Schema.integer(), Schema.number(), Schema.bool()
Literal["a", "b"]A string limited to those choices
List[T]An array of T
A TypedDictAn object. NotRequired fields, and every field of a total=False TypedDict, are optional.
Optional[T], or any parameter with a defaultT, marked optional

Other types, such as dict or a union of two types, raise a TypeError that names the parameter.

Each parameter also needs a value source, as with Schema. By default its value comes from the LLM, guided by the parameter’s line in the docstring. The decorator reads Google-style Args: sections and reStructuredText :param name: lines, and a TypedDict field’s description comes from the Attributes: section of the class docstring. Wrap a type in Annotated[T, Param(...)] to set the value source directly:

Param argumentThe value
Param("text")Is provided by the LLM, guided by text. Takes precedence over the docstring.
from_variable="name"Is read from a dynamic variable when the tool runs.
constant=valueIs always value.

@client_tool also takes name and description, which override the function’s name and docstring. Its other keyword arguments, such as expects_response, are passed to options().

The decorated function behaves like this:

  • It needs no build() step. Pass the function itself to tools.create() or tools.update(). It’s checked when it’s defined, so a problem that build() would report, such as a parameter with no description, raises ToolValidationError when the module is imported.
  • It’s still a function. You can call it directly, for example in tests.
  • fn.tool is a normal client tool builder. Use it with to_json_string(), or to set anything a signature can’t express, such as system_provided() or require_any_of().
  • ClientTools.register_tools() registers each function under its tool name. When the agent calls a tool, the function gets the parameters the agent sends as keyword arguments. Keys it doesn’t declare, such as tool_call_id, are dropped unless it takes **kwargs. async functions are supported.
  • Its state is shared by every conversation in the process. A module-level function can only reach module-level state. That’s fine on a device that holds one conversation, but on a server that runs many, define the functions inside a function that takes that conversation’s state, and register them with that conversation’s own ClientTools.

The decorator doesn’t change where the function runs or who can see its calls. The client tool trust rules apply in the same way.

The decorator only defines client tools. A webhook tool runs on your server and needs a URL, a location for each parameter, and headers, none of which a function signature can express. Build webhook tools with Tool.webhook().

Build a system tool

System tools are built into the platform. Each has its own constructor on SystemTool, which takes that tool’s settings:

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

The two transfer tools take their destinations from transfer(condition, destination, options). The condition tells the LLM when to transfer there, and the destination uses the same Destination as workflows as code. A transfer to a SIP URI needs a SIP REFER transfer:

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

Tool options

Settings shared by every kind of tool go in options(), as keyword arguments in Python and an object in JavaScript. Their names match the tool config’s fields in the API:

Applies toPythonJavaScript
All toolsname, description, response_timeout_secs, interruption_mode, pre_tool_speech, tool_call_sound, tool_error_handling_mode, …name, description, responseTimeoutSecs, interruptionMode, preToolSpeech, toolCallSound, toolErrorHandlingMode, …
Webhook toolsexecution_mode, content_type, response_filter, follow_redirects, follow_redirects_allowed_domains, dynamic_variable_placeholdersexecutionMode, contentType, responseFilter, followRedirects, followRedirectsAllowedDomains, dynamicVariablePlaceholders
Client toolsexecution_mode, expects_response, dynamic_variable_placeholdersexecutionMode, expectsResponse, dynamicVariablePlaceholders

A webhook tool’s response timeout is 5 to 300 seconds. A client tool’s is 1 to 120 seconds, or -1 to wait as long as it takes, which needs expects_response / expectsResponse. follow_redirects / followRedirects needs a list of allowed domains.

Attach tools to an agent

Webhook and client tools are created on their own with tools.create() and attached to agents by ID, so one tool can be shared by several agents. System tools are part of the agent’s config: build_config() / buildConfig() returns the entry for the agent’s built-in tools.

The agent builder does these steps for you: pass Tool objects to an Agent, and agents.push() creates or updates them and attaches their IDs.

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(),
),
)
)
),
)

The agent’s prompt.tools field, which holds tool configs inline, is deprecated. It can’t be combined with tool_ids, and when a request includes it, the agent’s built-in tools are replaced by the system tools it contains. Create tools with tools.create() and attach them by ID instead.

Edit an existing tool

Tool.from_response() / Tool.fromResponse() loads a tool returned by tools.get(). Fields the builder doesn’t model, and the defaults the API fills in, are kept, so pushing it back only changes what you changed. as_webhook(), as_client() and as_system() (asWebhook() and so on in JavaScript) give you the typed tool to edit, or None / undefined if it’s another kind.

To change a body property, read the body schema, set the property again, and set the 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())

Store tools in version control

to_json_string() / toJSONString() writes the tool in the API’s wire format: snake_case keys, sorted at every level, with 2-space indentation. It’s the same shape the CLI keeps in its tool_configs/ directory, and both SDKs write byte-for-byte identical files for the same tool, so diffs stay small. Tool.from_json() / Tool.fromJSON() reads it back.

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

A typical setup is the same as for workflows: seed the files with elevenlabs tools pull, edit them directly or with the builder, run Tool.from_json(file).build() / Tool.fromJSON(file).build() in CI on every pull request, and push them with tools.update() or elevenlabs tools push on merge.

Validation

Chained calls never fail on their own. build(), build_config() / buildConfig(), to_json() / toJSON() and to_json_string() / toJSONString() check the whole tool and raise or throw a single ToolValidationError whose issues list every problem, each with a code, a message and the path of the part it concerns, such as 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)

Errors include:

  • A URL placeholder with no path parameter, or a path parameter with no placeholder. Environment variable templates such as {{system__env_api_host}} aren’t placeholders.
  • A literal with no value source, or with more than one.
  • A body on a GET, or no body on a POST, PUT or PATCH.
  • The same parameter name in more than one of the path, query and body.
  • omit() on a required property, choices() on a schema that isn’t a string, or a constant that doesn’t match the schema’s type.
  • A transfer tool with no destinations, a destination of the wrong kind, or a SIP URI destination without a SIP REFER transfer.
  • An option that doesn’t apply to the kind of tool, or a timeout outside its range.

Tool types newer than your SDK

A tool loaded from the API or from a file can be of a type that the builder can’t edit, such as an MCP tool. It loads with the kind "other" and round-trips through from_json() / fromJSON() and to_json_string() / toJSONString() unchanged, and build() reports it as a warning through on_warning / onWarning.