The official Python SDK for ElevenLabs. ElevenLabs brings the most compelling, rich and lifelike voices to creators and developers in just a few lines of code.
Our most expressive, highest quality speech synthesis model
Supports 90+ languages
Exceptional voice cloning and natural multi-speaker dialogue
Recommended for content creation, audiobooks and voiceovers
Eleven v4 Turbo (eleven_v4_turbo)
Our most expressive real-time model, with a median latency of ~100ms
Supports 90+ languages
Audio tags for fine-grained control
Recommended for voice agents and other real-time use cases
Eleven Multilingual v2 (eleven_multilingual_v2)
Lifelike, consistent quality
Supports 29 languages
Most stable on long-form generations
Eleven Flash v2.5 (eleven_flash_v2_5)
Ultra-low latency (~100ms median)
Supports 32 languages
50% lower price per character
For speech to text use Scribe v2 (scribe_v2, or scribe_v2_realtime for live audio), and for music use Eleven Music v2.5 (music_v2_5). For more detailed information about these models and others, visit the ElevenLabs Models documentation.
from dotenv import load_dotenv
from elevenlabs.client import ElevenLabs
from elevenlabs.play import play
load_dotenv()
elevenlabs = ElevenLabs()
audio = elevenlabs.text_to_speech.convert(
text="The first move is what sets everything in motion.",
voice_id="JBFqnCBsd6RMkjVDRZzb",
model_id="eleven_v4",
output_format="mp3_44100_128",
)
play(audio)
Play
🎧 Try it out! Want to hear our voices in action? Visit the ElevenLabs Voice Lab to experiment with different voices, languages, and settings.
Build a voice object with custom settings to personalize the voice style, or call
elevenlabs.voices.settings.get("your-voice-id") to get the default settings for the voice.
Clone Voice
Clone your voice in an instant. Note that voice cloning requires an API key, see below.
from elevenlabs.client import ElevenLabs
from elevenlabs.play import play
elevenlabs = ElevenLabs(
api_key="YOUR_API_KEY",
)
voice = elevenlabs.voices.ivc.create(
name="Alex",
description="An old American male voice with a slight hoarseness in his throat. Perfect for news", # Optional
files=["./sample_0.mp3", "./sample_1.mp3", "./sample_2.mp3"],
)
Streaming
Stream audio in real-time, as it's being generated.
from elevenlabs import stream
from elevenlabs.client import ElevenLabs
elevenlabs = ElevenLabs(
api_key="YOUR_API_KEY",
)
audio_stream = elevenlabs.text_to_speech.stream(
text="This is a test",
voice_id="JBFqnCBsd6RMkjVDRZzb",
model_id="eleven_v4"
)
# option 1: play the streamed audio locally
stream(audio_stream)
# option 2: process the audio bytes manually
for chunk in audio_stream:
if isinstance(chunk, bytes):
print(chunk)
Async Client
Use AsyncElevenLabs if you want to make API calls asynchronously.
reason is "user" for end_session(), "agent" for a normal server close, or "error" for an abnormal close or other exception. WebSocket close details are included when available; message describes errors. The callback runs once, after callback_end_session. For AsyncConversation, provide an async callback.
Unhandled Client Tool Calls
Pass callback_unhandled_client_tool_call to be told when the agent calls a client tool that has no handler registered in client_tools. It receives the client_tool_call payload with tool_name, tool_call_id, parameters and expects_response. The agent still receives an error result for the call:
For advanced use cases involving context propagation, resource reuse, or specific event loop management, ClientTools supports custom asyncio event loops:
import asyncio
from elevenlabs.conversational_ai.conversation import ClientTools
elevenlabs = ElevenLabs(
api_key="YOUR_API_KEY",
)
async def main():
# Get the current event loop
custom_loop = asyncio.get_running_loop()
# Create ClientTools with custom loop to prevent "different event loop" errors
client_tools = ClientTools(loop=custom_loop)
# Register your tools
async def get_weather(params):
location = params.get("location", "Unknown")
# Your async logic here
return f"Weather in {location}: Sunny, 72°F"
client_tools.register("get_weather", get_weather, is_async=True)
# Use with conversation
conversation = Conversation(
client=elevenlabs,
agent_id="your-agent-id",
requires_auth=True,
audio_interface=audio_interface,
client_tools=client_tools
)
asyncio.run(main())
Benefits of Custom Event Loop:
Context Propagation: Maintain request-scoped state across async operations
Resource Reuse: Share existing async resources like HTTP sessions or database pools
Loop Management: Prevent "Task got Future attached to a different event loop" errors
Performance: Better control over async task scheduling and execution
Important: When using a custom loop, you're responsible for its lifecycle
Don't close the loop while ClientTools are still using it.
Tool Registration
Register custom tools that the AI agent can call during conversations:
Build an agent workflow with chained methods instead of a hand-written graph of nodes and edges. The Workflow object stands for the start node. Each verb adds a node and returns it, so flows read top to bottom:
Verb
Adds
converse(id, prompt, **options)
The agent holds a conversation with prompt added to its instructions (a subagent node)
tool(id, tool_ids, **options)
A node that runs tools (by id, or as Tool objects that agents.push() creates); route on the result with on_result(), or on_success() / on_failure()
transfer(id, destination, **options)
A transfer to a phone number, SIP URI or another agent
end(id="end")
The end of the conversation (shared "end" node unless you pass an id)
when(condition) opens a conditional branch. A string is an LLM condition; an Expr is an expression over dynamic variables. go_to(node) moves the conversation to a node that already exists, for merges and loops. The API allows one edge between any two nodes, so going back to a node that already leads here is sent as that edge's backward condition; any other second edge between the same two nodes fails build().
up() returns the node the current one was chained from, so you can write a whole workflow as one chain:
(
wf.converse("triage", "Greet the caller and find out why they're calling")
.when("Caller wants a human").transfer("human", Destination.phone("+15551234567")).up()
.when("Caller is done").end()
)
from elevenlabs import ElevenLabs
from elevenlabs.agent_workflows import Destination, Expr, Workflow
wf = Workflow()
triage = wf.converse("triage", "Greet the caller and find out why they're calling")
identify = triage.when("Caller wants to check an order").converse("identify", "Ask for the order number")
lookup = identify.when("Caller gave an order number").tool("lookup_order", ["tool_get_order"])
lookup.on_result(
success=lambda ok: ok.converse("resolve", "Explain the order status").when("Caller is satisfied").end(),
failure=lambda failed: failed.go_to(identify),
)
triage.when(Expr.variable("tier").eq("gold")).transfer("vip", Destination.agent("agent_vip"))
triage.when("Caller wants a human").transfer("human", Destination.phone("+15551234567"))
client = ElevenLabs()
client.conversational_ai.agents.update("agent_id", workflow=wf.build())
build() checks the whole graph and raises one WorkflowValidationError whose issues list every problem it finds. It also generates edge ids and edge order, and lays out nodes that don't have a position, so they don't all stack on top of each other in the editor.
Editing an existing agent
agent = client.conversational_ai.agents.get("agent_id")
wf = Workflow.from_agent(agent) # keeps node ids, editor positions and edge order
wf.node("resolve").update(prompt="Explain the status, then offer a discount code")
verify = wf.insert_between("identify", "lookup_order", lambda start: start.converse("verify", "Verify the caller's identity"))
if verify is not None: # None if there's no such edge
verify.when("Caller can't verify").end(id="unverified")
wf.remove("vip")
client.conversational_ai.agents.update("agent_id", workflow=wf.build())
Storing workflows in git
to_json_string() writes the workflow in API format: snake_case keys, sorted, the same shape the REST API and the ElevenLabs CLI use, and byte for byte what the other ElevenLabs SDKs write. Workflow.from_json() reads it back. It also accepts a full agent config file that has a workflow key.
from pathlib import Path
Path("workflows/support.json").write_text(wf.to_json_string())
stored = Workflow.from_json(Path("workflows/support.json").read_text())
A workflow loaded from the API or a file can contain node types that are newer than your SDK version. They round-trip through from_json() and to_json_string() unchanged, and build() warns about each one (pass on_warning= to see them). build() can't type those nodes, so Pydantic warns when the request is serialized. Upgrade the SDK, or send the wire format directly:
Define webhook, client and system tools with chained methods instead of nested JSON schemas. build() returns the request tools.create() and tools.update() accept, and to_json_string() writes the same file the ElevenLabs CLI keeps in tool_configs/:
from pathlib import Path
from elevenlabs import ElevenLabs
from elevenlabs.agent_tools import Destination, Header, Schema, SystemTool, Tool
refund = (
Tool.webhook("issue_refund", "Refund an order the caller asked to return")
.post("https://api.example.com/orders/{order_id}/refunds")
.path_param("order_id", Schema.string().describe("The order number, e.g. A-1042"))
.header("Authorization", Header.secret("sec_orders_api"))
.body(
Schema.object()
.property("customer_id", Schema.string().from_variable("customer_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())
)
.assign("refund_id", "refund.id")
.options(response_timeout_secs=10)
)
client = ElevenLabs()
client.conversational_ai.tools.create(request=refund.build())
Path("tool_configs/issue_refund.json").write_text(refund.to_json_string())
transfer = SystemTool.transfer_to_number().transfer("Caller asks for billing", Destination.phone("+15551234567"))
Each schema property gets its value from exactly one place: the LLM (describe()), a dynamic variable (from_variable()), a constant(), the system (system_provided()), or nowhere (omit()). Properties are required unless you call optional(). Schemas are values, so you can reuse one across tools.
System tools aren't created with tools.create(). build_config() returns their entry for the agent's built_in_tools:
build() checks the whole tool first and raises a ToolValidationError whose issues list every problem (each with a code, path and message). For example, it reports a {placeholder} in the URL with no matching path_param(), a property with two value sources, or a GET with a body. Load an existing tool with Tool.from_response(client.conversational_ai.tools.get(tool_id)) or Tool.from_json(file), edit it, and push it back with tools.update(). To create or update tools together with the agent that uses them, see Agents as code.
Client tools from functions
For a client tool, @client_tool builds the tool from a function: its name, its docstring and its typed params. The same function then runs when the agent calls the tool.
# cart_tools.py
from typing import Literal, Optional
from typing_extensions import Annotated
from elevenlabs.agent_tools import Param, client_tool
@client_tool(expects_response=True)
def add_to_cart(
sku: str,
quantity: int = 1,
size: Optional[Literal["S", "M", "L"]] = None,
store_id: Annotated[str, Param(from_variable="store_id")] = "",
) -> dict:
"""Add a product to the shopper's cart.
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)}
Push the tool's schema once, when you deploy, not each time a conversation starts:
# deploy.py, run from CI or by hand
from cart_tools import add_to_cart
if tool_id: # the id from the first push, kept in your config
client.conversational_ai.tools.update(tool_id, request=add_to_cart)
else:
tool_id = client.conversational_ai.tools.create(request=add_to_cart).id
client.conversational_ai.agents.update( # replaces the agent's tool list
agent_id, conversation_config={"agent": {"prompt": {"tool_ids": [tool_id]}}}
)
At runtime, only register the function so it runs when the agent calls the tool:
from elevenlabs.conversational_ai.conversation import ClientTools, Conversation
from cart_tools import add_to_cart
# Warns about each param the function and the agent's tool disagree on. strict=True raises instead.
client.conversational_ai.tools.check_client_tools(agent_id, add_to_cart)
client_tools = ClientTools()
client_tools.register_tools(add_to_cart)
conversation = Conversation(client, agent_id, requires_auth=True, client_tools=client_tools)
check_client_tools() compares each function with the client tool of the same name on the agent: param names, types, choices and which params are required. It ignores descriptions and value sources, which don't change what the function receives. Each difference is issued as a ToolSchemaDriftWarning and returned as a ToolSchemaDrift, so a mismatch shows up when the app starts rather than when the agent calls the tool.
The schema is shared. The tool's params are stored on the server with the tool, and every client that talks to the agent gets the same schema, including copies of your app that are still running an older version. A pushed change reaches all of them right away. Adding an optional param is safe. Renaming or removing a param, 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.
Params:str, int, float, bool, Literal of strings, List[T] and TypedDict map to the matching schema types. A param with a default or an Optional type is optional.
Descriptions and value sources: descriptions come from the docstring's Args: section (or :param name: lines). Annotated[T, Param(...)] sets a description, a dynamic variable or a constant instead.
No build() step: pass the function itself to tools.create() or tools.update(). The tool is checked when the function is defined, so a mistake raises ToolValidationError at import.
Still a function and still a builder: you can call it directly in tests, and add_to_cart.tool is a normal ClientTool, for to_json_string() or any setting the signature can't express.
Agents as code
Agent puts an agent's settings, tools and workflow in one definition. agents.push() creates or updates every webhook and client tool it uses, then the agent, with the tools' ids filled in:
from elevenlabs import ElevenLabs
from elevenlabs.agent_builder import Agent
from elevenlabs.agent_tools import Schema, SystemTool, Tool
from elevenlabs.agent_workflows import Workflow
get_order = (
Tool.webhook("get_order", "Look up an order by its number")
.get("https://api.example.com/orders/{order_id}")
.path_param("order_id", Schema.string().describe("The order number, e.g. A-1042"))
)
wf = Workflow()
(
wf.converse("triage", "Find out what the caller needs")
.when("Caller gave an order number")
.tool("lookup", [get_order]) # a Tool object: push fills in its id
.on_success()
.converse("resolve", "Explain the order status")
)
agent = Agent(
"Support line",
prompt="You are a support agent for Acme.",
first_message="Hi, how can I help?",
voice_id="21m00Tcm4TlvDq8ikWAM",
tools=[SystemTool.end_call()],
workflow=wf,
)
client = ElevenLabs()
result = client.conversational_ai.agents.push(agent) # creates the agent and get_order
client.conversational_ai.agents.push(agent, agent_id=result.agent_id) # later: updates only what changed
Validation first:push() calls agent.validate() before any request, so an invalid agent writes nothing. CI can call validate() without an API key; it raises an AgentValidationError whose issues list every problem.
Tools are matched safely: with agent_id, existing tools are found among the tools that agent already uses, by name. A tool with the same name that another agent uses is never touched. Tools the agent stops using are reported as "detached", not deleted.
Escape hatch:conversation_config and platform_settings take any other setting, as the generated models or as snake_case dicts, merged under the typed options. tool_ids attaches existing tools that push() leaves alone. agent.build(tool_ids=...) returns the keyword arguments agents.create() takes, if you'd rather make the calls yourself.
Partial failures: if a request fails, push() raises an AgentPushError whose result lists the tools it had already created.
Async:AsyncElevenLabs has the same push() and pull(), to await.
Keeping agents in git
AgentProject reads and writes the ElevenLabs CLI's project layout (agents.json, tools.json, agent_configs/, tool_configs/). The same repo works with the SDK and with elevenlabs agents push. The project records each agent's and tool's id, so running a script again updates them instead of making copies:
from elevenlabs.agent_builder import AgentProject
project = AgentProject.open(".") # an empty directory works too
client.conversational_ai.agents.push(agent, project=project) # writes the configs and ids it pushed
# Edit an agent stored in the project
support = project.agent("Support line")
support.update(first_message="Hello!")
client.conversational_ai.agents.push(support, project=project)
# Bring an agent made in the dashboard into the repo
client.conversational_ai.agents.pull("agent_123", project=project)
Configs are kept in API format and settings the SDK doesn't model survive a round trip. Only JSON configs are supported for now; projects that use YAML or TOML configs raise an AgentProjectError.
Speech Engine
Speech Engine lets you build server-side voice agents that receive real-time transcripts from the ElevenLabs API and stream LLM responses back for text-to-speech synthesis. Your server acts as a WebSocket endpoint — ElevenLabs connects to it, sends user transcripts, and your code decides how to respond.
Speech Engine is async-only and available on AsyncElevenLabs.
When a new transcript arrives while a previous response is still streaming, the previous handler's asyncio.Task is cancelled automatically. Any await in your handler (including LLM SDK calls) will raise asyncio.CancelledError, which cleanly aborts the in-flight request. No manual signal handling needed.
Custom Server Integration (FastAPI, Starlette)
For integrating with an existing web server, use create_session() instead of serve():
For full control over the server lifecycle, use SpeechEngineServer directly:
from elevenlabs.speech_engine import SpeechEngineServer
server = SpeechEngineServer(
port=3001,
debug=True,
on_transcript=handle_transcript,
)
# In one task:
await server.serve()
# In another task (e.g. signal handler):
await server.stop()
Authentication
Both engine.serve() and SpeechEngineServer automatically verify the X-Elevenlabs-Speech-Engine-Authorization header on every incoming connection, rejecting any requests that were not signed by ElevenLabs. The API key is read from the AsyncElevenLabs client (or api_key= on SpeechEngineServer), falling back to the ELEVENLABS_API_KEY environment variable.
Disabling authentication
If your server sits behind an infrastructure layer that already restricts incoming traffic to ElevenLabs (typically an IP allowlist scoped to ElevenLabs' egress ranges), you can skip JWT verification by passing disable_auth=True:
# Via engine.serve() — no api_key required when disable_auth is True
await engine.serve(port=3001, disable_auth=True, on_transcript=on_transcript)
# Or directly on SpeechEngineServer
server = SpeechEngineServer(port=3001, disable_auth=True, on_transcript=on_transcript)
await server.serve()
When auth is disabled the server accepts any client that can reach it and emits a UserWarning on startup. Only use this if you have an IP allowlist or equivalent network-level restriction in front of the server — without one, anyone on the internet can open a session and consume your compute and downstream LLM quota.
While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!
On the other hand, contributions to the README are always very welcome!
Alternatives
Use instead of elevenlabs: tools that do the same job, closest first.