ElevenLabs Python SDK

repository·main·Indexed 25 days ago

https://github.com/elevenlabs/elevenlabs-python

Official Python SDK for ElevenLabs (v2.59.0) providing interfaces for AI voice generation, instant voice cloning, and real-time conversational AI. Features include text-to-speech conversion, audio streaming, sound effects generation, and audio isolation. It supports both synchronous and asynchronous clients (AsyncElevenLabs), as well as tools for building server-side voice agents via the Speech Engine and interactive agents with ElevenAgents.

Tokens
115.8K
Snippets
436
Records
556
Agent score
80%

What's inside elevenlabs-python

  1. Build voice agents with Speech Engine

    main

    The Speech Engine allows you to build server-side voice agents. Your server acts as a WebSocket endpoint that ElevenLabs connects to. ElevenLabs sends real-time user transcripts, and your server responds by streaming LLM responses back for text-to-speech synthesis.

    Note: Speech Engine is async-only and requires using AsyncElevenLabs.

    import asyncio
    from openai import AsyncOpenAI
    from elevenlabs import AsyncElevenLabs
    
    openai_client = AsyncOpenAI()
    elevenlabs = AsyncElevenLabs()
    
    async def main():
        engine = await elevenlabs.speech_engine.get("seng_123")
    
        async def on_transcript(transcript, session):
            stream = await openai_client.responses.create(
                model="gpt-4o",
                input=[
                    {"role": "assistant" if m.role == "agent" else m.role, "content": m.content}
                    for m in transcript
                ],
                stream=True,
            )
            await session.send_response(stream)
    
        async def on_init(conversation_id, session):
            print(f"Session started: {conversation_id}")
    
        async def on_close(session):
            print(f"Session ended: {session.conversation_id}")
    
        async def on_error(err, session):
            print(f"Error: {err}")
    
        await engine.serve(
            port=3001,
            debug=True,
            on_init=on_init,
            on_transcript=on_transcript,
            on_close=on_close,
            on_error=on_error,
        )
    
    asyncio.run(main())
  2. Integrate Speech Engine with FastAPI or Starlette

    main

    To integrate the Speech Engine into an existing web server instead of using the standalone serve() method, use engine.create_session(). This allows you to manage the WebSocket connection manually within your framework's routing.

    from fastapi import FastAPI, WebSocket
    
    app = FastAPI()
    engine = ...  # SpeechEngineResource from await client.speech_engine.get(...)
    
    @app.websocket("/api/speech-engine/ws")
    async def speech_engine_ws(ws: WebSocket):
        await ws.accept()
        session = engine.create_session(ws, debug=True)
        session.on("user_transcript", handle_transcript)
        await session.run()
  3. Build interactive AI agents with ElevenAgents

    main

    Use Conversation and DefaultAudioInterface to build real-time conversational AI agents. You can start a session with conversation.start_session() and end it with conversation.end_session().

    from elevenlabs.client import ElevenLabs
    from elevenlabs.conversational_ai.conversation import Conversation, ClientTools
    from elevenlabs.conversational_ai.default_audio_interface import DefaultAudioInterface
    
    elevenlabs = ElevenLabs(
      api_key="YOUR_API_KEY",
    )
    
    # Create audio interface for real-time audio input/output
    audio_interface = DefaultAudioInterface()
    
    # Create conversation
    conversation = Conversation(
        client=elevenlabs,
        agent_id="your-agent-id",
        requires_auth=True,
        audio_interface=audio_interface,
    )
    
    # Start the conversation
    conversation.start_session()
    
    # The conversation runs in background until you call:
    conversation.end_session()
  4. Configure Speech Engine Authentication

    main

    By default, engine.serve() and SpeechEngineServer verify the X-Elevenlabs-Speech-Engine-Authorization header using the API key from your AsyncElevenLabs client or the ELEVENLABS_API_KEY environment variable.

    Disabling Authentication: If your server is protected by an IP allowlist (e.g., restricting traffic to ElevenLabs' egress ranges), you can disable JWT verification by passing disable_auth=True.

    Warning: Only disable authentication if you have network-level restrictions in place. Without them, anyone can access your server and consume your LLM/compute quota.

    # Via engine.serve()
    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()
  5. Manage environment variables asynchronously

    main

    Use AsyncElevenLabs to perform environment variable operations in an asynchronous event loop. The methods list, create, get, and update are all async and must be awaited.

    import asyncio
    from elevenlabs import AsyncElevenLabs
    from elevenlabs.environment_variables import (
        EnvironmentVariablesCreateRequestBody_String,
    )
    
    client = AsyncElevenLabs(
        api_key="YOUR_API_KEY",
    )
    
    async def main() -> None:
        # Example: List
        await client.environment_variables.list(
            cursor="cursor",
            page_size=1,
            label="label",
            environment="environment",
            type="string",
        )
        
        # Example: Create
        await client.environment_variables.create(
            request=EnvironmentVariablesCreateRequestBody_String(
                label="label",
                values={"key": "value"},
            ),
        )
    
    asyncio.run(main())
  6. Stream audio in real-time

    main

    Use elevenlabs.text_to_speech.stream() to generate audio as a stream. You can either play the stream locally using the stream() function or iterate through the audio_stream to process raw audio bytes manually.

    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_multilingual_v2"
    )
    
    # 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)
  7. Stream audio with timestamps using `client.text_to_speech.stream_with_timestamps`

    main

    Converts text into speech and returns a stream of JSON objects. Each JSON contains a base64 encoded audio string and metadata indicating exactly when each character was spoken.

    Returns: typing.Iterator[bytes] (where bytes represent JSON strings).

    Key Parameters:

    • voice_id (str): The ID of the voice to use.
    • text (str): The text to convert.
    • output_format (optional): Audio format.
    • optimize_streaming_latency (int, optional): Latency optimization level (0-4).
    • apply_text_normalization (optional): Modes: 'auto', 'on', or 'off'.
    from elevenlabs import ElevenLabs
    from elevenlabs.environment import ElevenLabsEnvironment
    
    client = ElevenLabs(
        environment=ElevenLabsEnvironment.PRODUCTION,
    )
    
    client.text_to_speech.stream_with_timestamps(
        voice_id="JBFqnCBsd6RMkjVDRZzb",
        output_format="mp3_44100_128",
        text="The first move is what sets everything in motion.",
        model_id="eleven_multilingual_v2",
    )
  8. Retrieve or create RAG indexes for knowledge base documents

    main

    Use client.conversational_ai.knowledge_base.get_or_create_rag_indexes() to manage Retrieval-Augmented Generation (RAG) indexes for multiple documents in a single request. You can process up to 100 items per request.

    Parameters:

    • items (List[GetOrCreateRagIndexRequestModel]): A list of requested RAG indexes. Each item requires a document_id and can specify create_if_missing and a model (e.g., 'e5_mistral_7b_instruct').
    from elevenlabs import ElevenLabs, GetOrCreateRagIndexRequestModel
    from elevenlabs.environment import ElevenLabsEnvironment
    
    client = ElevenLabs(
        environment=ElevenLabsEnvironment.PRODUCTION,
    )
    
    client.conversational_ai.knowledge_base.get_or_create_rag_indexes(
        items=[
            GetOrCreateRagIndexRequestModel(
                document_id="document_id",
                create_if_missing=True,
                model="e5_mistral_7b_instruct",
            )
        ],
    )
  9. Retrieve standard voice sample audio

    main

    Use client.voices.samples.audio.get to return the audio bytes corresponding to a sample attached to a voice. This returns an iterator of bytes.

    from elevenlabs import ElevenLabs
    from elevenlabs.environment import ElevenLabsEnvironment
    
    client = ElevenLabs(
        environment=ElevenLabsEnvironment.PRODUCTION,
    )
    
    client.voices.samples.audio.get(
        voice_id="voice_id",
        sample_id="sample_id",
    )
  10. Unshare a workspace resource

    main

    Remove an existing role from a user, group, or service account API key for a workspace resource. You must have admin access to the resource. Note that you cannot remove permissions from the user who originally created the resource.

    from elevenlabs import ElevenLabs
    from elevenlabs.environment import ElevenLabsEnvironment
    
    client = ElevenLabs(
        environment=ElevenLabsEnvironment.PRODUCTION,
    )
    
    client.workspace.resources.unshare(
        resource_id="resource_id",
        resource_type="voice",
    )