How to Build a Gemini Live Voice Agent with Twilio Agent Connect and Python

November 24, 2026
Written by
Reviewed by

How to Build a Gemini Live Voice Agent with Twilio Agent Connect and Python

Voice AI can sound flawless in a local microphone test and fall apart the moment real phone audio enters the picture. In this tutorial, you’ll build a Python appointment concierge that connects Twilio Programmable Voice to the Gemini Live API through a custom Twilio Agent Connect provider. The agent can greet callers, handle interruptions, call Python tools, stream a transcript, and place outbound calls.

What you’ll build

The finished demo gives you:

  • An inbound phone agent powered by Gemini 3.8 Live
  • Full-duplex audio between a phone call and Gemini Live
  • Barge-in support, so callers can interrupt the agent naturally
  • Python tools that check appointment availability and create a demo booking
  • A live web dashboard for transcripts, tool activity, call state, and architecture
  • An outbound calling option that reuses the same voice channel

The fictional Northstar Service Center is the business scenario. A caller can ask for an oil-change appointment, hear available times, confirm the details, and receive a clearly labeled demo confirmation.

Prerequisites

Before you begin, you’ll need:

The project uses twilio-agent-connect[server] 2.4, the google-genai Python SDK, FastAPI, and python-dotenv. As of October 2026, gemini-3.8-live is the stable Gemini Live model recommended for most low-latency voice agent experiences.

Understand the voice path

A browser microphone and a phone call do not deliver the same audio. Twilio Media Streams sends phone audio as base64-encoded, 8 kHz μ-law. Gemini Live accepts raw, little-endian, 16-bit pulse-code modulation (PCM) audio and natively expects 16 kHz input. Its audio output is 24 kHz PCM.

That makes the custom provider the translator at the center of the application:

flowchart LR
    A["Phone caller"] <-->|"8 kHz μ-law"| B["Twilio Voice<br/>Media Streams"]
    B <-->|"WSS"| C["Agent Connect<br/>GeminiLiveProvider"]
    C <-->|"16 kHz PCM in<br/>24 kHz PCM out"| D["Gemini Live API"]
    D <-->|"Function calls"| E["Python appointment tools"]
    C -->|"Call events"| F["Live dashboard"]

Think of Twilio Agent Connect (TAC) as the channel layer and the custom GeminiLiveProvider as an adapter. TAC owns the voice-channel lifecycle and Twilio integration, while the provider opens the Gemini session, converts the audio in both directions, executes tools, and publishes observable events.

Set up the Python project

The demo keeps the business logic in app.py and the reusable provider in src/tac_gemini_live/. Install the locked dependencies from the project root:

uv sync
cp .env.example .env

Open .env and add your credentials:

# Twilio Agent Connect / Programmable Voice
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_API_KEY=SKxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_API_SECRET=your_api_secret
TWILIO_PHONE_NUMBER=+15551234567
TWILIO_VOICE_PUBLIC_DOMAIN=your-subdomain.ngrok.app
# Gemini Developer API
GEMINI_API_KEY=your_gemini_api_key
GEMINI_LIVE_MODEL=gemini-3.8-live
# Optional demo controls
GEMINI_VOICE_NAME=Kore
DEMO_OUTBOUND_TO=
LOG_LEVEL=INFO

Set TWILIO_VOICE_PUBLIC_DOMAIN to the hostname only. For example, use your-subdomain.ngrok.app, without https:// or a trailing path.

Keep .env out of source control. API keys and Twilio credentials should remain server-side and must never be included in the dashboard JavaScript.

Keep .env out of source control. API keys and Twilio credentials should remain server-side and must never be included in the dashboard JavaScript.

Convert phone audio for Gemini Live

The audio bridge in src/tac_gemini_live/audio.py performs two stateful conversions. Incoming μ-law audio becomes 16 kHz PCM for Gemini, and Gemini’s 24 kHz PCM output becomes 8 kHz μ-law for Twilio.

import audioop
import base64
from dataclasses import dataclass, field
from typing import Any
TWILIO_SAMPLE_RATE = 8_000
GEMINI_INPUT_SAMPLE_RATE = 16_000
GEMINI_OUTPUT_SAMPLE_RATE = 24_000
SAMPLE_WIDTH_BYTES = 2
TWILIO_FRAME_BYTES = 160  # 20 ms of 8 kHz μ-law audio.
@dataclass
class TwilioGeminiAudioBridge:
    _input_rate_state: Any = None
    _output_rate_state: Any = None
    _twilio_output_buffer: bytearray = field(default_factory=bytearray)
    def twilio_payload_to_gemini_pcm(self, payload: str) -> bytes:
        mulaw = base64.b64decode(payload, validate=True)
        pcm_8k = audioop.ulaw2lin(mulaw, SAMPLE_WIDTH_BYTES)
        pcm_16k, self._input_rate_state = audioop.ratecv(
            pcm_8k,
            SAMPLE_WIDTH_BYTES,
            1,
            TWILIO_SAMPLE_RATE,
            GEMINI_INPUT_SAMPLE_RATE,
            self._input_rate_state,
        )
        return pcm_16k
    def gemini_pcm_to_twilio_frames(self, pcm_24k: bytes) -> list[bytes]:
        pcm_8k, self._output_rate_state = audioop.ratecv(
            pcm_24k,
            SAMPLE_WIDTH_BYTES,
            1,
            GEMINI_OUTPUT_SAMPLE_RATE,
            TWILIO_SAMPLE_RATE,
            self._output_rate_state,
        )
        self._twilio_output_buffer.extend(
            audioop.lin2ulaw(pcm_8k, SAMPLE_WIDTH_BYTES)
        )
        frames: list[bytes] = []
        while len(self._twilio_output_buffer) >= TWILIO_FRAME_BYTES:
            frames.append(bytes(self._twilio_output_buffer[:TWILIO_FRAME_BYTES]))
            del self._twilio_output_buffer[:TWILIO_FRAME_BYTES]
        return frames

The resampler state is preserved between chunks. That detail matters: resetting the converter for every WebSocket message can introduce clicks, gaps, and uneven pacing. The outgoing buffer also returns 160-byte frames, representing 20 milliseconds of Twilio audio, so playback remains steady.

Python removed the standard-library audioop module in Python 3.13. The project includes audioop-lts for Python 3.13 and newer, allowing the same import and conversion code to work across the supported Python versions.

Create a custom Agent Connect voice provider

The GeminiLiveProviderConfig class extends TAC’s MediaStreamsProviderConfig. Its create_provider() method is the small but important seam that lets VoiceChannel instantiate the custom implementation.

class GeminiLiveProviderConfig(MediaStreamsProviderConfig):
    api_key: str | None = Field(default_factory=_default_api_key, repr=False)
    model: str = Field(
        default_factory=lambda: os.getenv("GEMINI_LIVE_MODEL", "gemini-3.8-live")
    )
    live_config: dict[str, Any] = Field(default_factory=_default_live_config)
    tools: list[TACTool] = Field(default_factory=list)
    welcome_instruction: str | None = None
    event_handler: Callable[[dict[str, Any]], Awaitable[None]] | None = None
    def create_provider(
        self,
        channel: VoiceChannel,
        tac_config: TACConfig,
    ) -> VoiceProvider:
        return GeminiLiveProvider(channel, tac_config, self)

Inside provider.py, the provider validates Twilio’s audio/x-mulaw format when the Media Stream starts. It then creates one Gemini Live session and one TwilioGeminiAudioBridge per call. Per-call state prevents audio buffers, transcripts, and tool tasks from leaking between callers.

The connection method converts TAC tools into Gemini function declarations before opening the Live API session:

async def _connect_gemini(self, conversation_id: str) -> None:
    state = self._calls[conversation_id]
    live_config = deepcopy(self.config.live_config)
    if self.config.tools:
        declarations = [
            types.FunctionDeclaration(
                name=tool.name,
                description=tool.description,
                parameters_json_schema=tool.params_json_schema,
            )
            for tool in self.config.tools
        ]
        live_config["tools"] = [
            types.Tool(function_declarations=declarations)
        ]
    state.live_context = self._client.aio.live.connect(
        model=self.config.model,
        config=types.LiveConnectConfig(**live_config),
    )
    state.live_session = await state.live_context.__aenter__()
    if self.config.welcome_instruction:
        await state.live_session.send_client_content(
            turns=types.Content(
                role="user",
                parts=[types.Part(text=self.config.welcome_instruction)],
            ),
            turn_complete=True,
        )

The provider sends each converted caller chunk to Gemini with the required MIME type:

pcm = state.audio.twilio_payload_to_gemini_pcm(payload)
await state.live_session.send_realtime_input(
    audio=types.Blob(
        data=pcm,
        mime_type="audio/pcm;rate=16000",
    )
)

Audio coming back from Gemini takes the reverse path. Each 24 kHz PCM response is converted to μ-law, base64-encoded, and sent as a Twilio media event.

Make interruptions feel natural

A full-duplex model can detect that the caller has started speaking while the agent is talking. Stopping model generation is only half of the job because Twilio may still have generated audio buffered for playback.

When Gemini reports an interruption, the provider resets its outgoing audio state and sends a Twilio clear event:

if content.interrupted:
    state.audio.reset_output()
    await self._emit("call.interrupted", conversation_id)
    await self._send_twilio_event(
        conversation_id,
        {
            "event": "clear",
            "streamSid": state.stream_sid,
        },
    )

Twilio empties the Media Stream playback buffer when it receives clear. This prevents the previous response from talking over the caller and makes barge-in feel much closer to a human conversation.

Add appointment tools and the Gemini session config

The demo uses TAC’s @function_tool decorator for business logic. Type annotations and docstrings give the provider enough information to generate Gemini function declarations.

@function_tool()
async def check_appointment_availability(
    service: str,
    day: str,
) -> dict[str, object]:
    """Check demo appointment times for a service on a requested day."""
    await asyncio.sleep(0.4)
    return {
        "service": service,
        "day": day,
        "available_times": ["9:30 AM", "1:00 PM", "3:30 PM"],
        "timezone": "America/Chicago",
    }
@function_tool()
async def book_demo_appointment(
    name: str,
    service: str,
    day: str,
    time: str,
) -> dict[str, str]:
    """Book a fictional appointment after explicit caller confirmation."""
    await asyncio.sleep(0.4)
    return {
        "status": "confirmed",
        "confirmation": "DEMO-4821",
        "name": name,
        "service": service,
        "day": day,
        "time": time,
        "note": "This is a demo booking; no real appointment was created.",
    }

The artificial delay makes the tool boundary visible in the dashboard. Replace these functions with a scheduling API or database when you adapt the project, and make booking operations idempotent so retries cannot create duplicate appointments.

Next, create the TAC instance and attach the custom provider configuration to VoiceChannel:

tac = TAC(config=TACConfig.from_env())
SYSTEM_INSTRUCTION = """
You are the voice concierge for Northstar Service Center, a fictional demo business.
Speak naturally and keep each turn to one or two short sentences. Never use markdown,
emoji, or bullet lists because every response is played over a phone call. Use the
availability tool before offering times. Before booking, repeat the name, service, day,
and time and obtain an explicit yes. Clearly say that any booking is only a demo.
""".strip()
voice_channel = VoiceChannel(
    tac,
    config=GeminiLiveProviderConfig(
        tools=[check_appointment_availability, book_demo_appointment],
        event_handler=dashboard_events.publish,
        welcome_instruction=(
            "Greet the caller now with: Hello, you've reached the Northstar "
            "Service Center demo assistant, powered by Twilio Agent Connect "
            "and Gemini Live. How can I help?"
        ),
        live_config={
            "response_modalities": ["AUDIO"],
            "system_instruction": SYSTEM_INSTRUCTION,
            "speech_config": {
                "language_code": "en-US",
                "voice_config": {
                    "prebuilt_voice_config": {
                        "voice_name": os.getenv("GEMINI_VOICE_NAME", "Kore")
                    }
                },
            },
            "input_audio_transcription": {},
            "output_audio_transcription": {},
            "context_window_compression": {"sliding_window": {}},
        },
    ),
)

welcome_instruction prompts the model to speak as soon as it connects. Input and output transcription power both the final call transcript and the live dashboard, while context-window compression helps longer sessions manage their history.

Return tool results to the conversation

Gemini sends a structured function call when it needs availability or booking data. The provider looks up the matching TAC tool, runs it asynchronously, and returns a FunctionResponse to the same Live session:

output = await tool(**arguments)
await state.live_session.send_tool_response(
    function_responses=types.FunctionResponse(
        id=function_call.id,
        name=name,
        response={"result": output},
    )
)

This separation keeps business logic outside the audio loop. The model decides when a tool is needed, Python performs the work, and Gemini turns the result into a natural spoken response.

Wire the server and live dashboard

TACFastAPIServer attaches the TwiML and WebSocket routes to a FastAPI application. The same server also hosts the dashboard and its event endpoints:

fastapi_app = FastAPI(
    title="Twilio Agent Connect + Gemini Live",
    lifespan=lifespan,
)
server = TACFastAPIServer(
    tac=tac,
    voice_channel=voice_channel,
    app=fastapi_app,
)
app = server.app
app.mount(
    "/assets",
    StaticFiles(directory=STATIC_DIR),
    name="dashboard-assets",
)
@app.get("/")
async def dashboard() -> FileResponse:
    return FileResponse(STATIC_DIR / "index.html")
@app.get("/api/state")
async def dashboard_state() -> dict[str, object]:
    return await dashboard_events.snapshot()
@app.get("/api/events")
async def dashboard_event_stream() -> StreamingResponse:
    return StreamingResponse(
        dashboard_events.listen(),
        media_type="text/event-stream",
    )

The provider emits small events such as call.started, transcript.partial, tool.completed, and call.interrupted. DashboardEventBus reduces those events into one call snapshot and sends it to the browser with Server-Sent Events (SSE). The result is a showcase page that makes the invisible parts of the phone call visible without introducing a frontend framework or build step.

Open http://localhost:8000/ while a call is active to see the caller and Gemini transcript, function inputs and outputs, interruption count, current model, call timer, and the audio architecture.

Connect a Twilio phone number

Start ngrok in one terminal:

ngrok http 8000

Copy the ngrok hostname into TWILIO_VOICE_PUBLIC_DOMAIN, then start the application in another terminal:

uv run python app.py

In the Twilio Console, open Phone Numbers, select Manage > Active Numbers, and choose your voice-capable number. Under Voice Configuration, set A Call Comes In to Webhook, enter the following URL, choose HTTP POST, and select Save:

https://YOUR_PUBLIC_DOMAIN/twiml

Call the number and say, “I need an oil-change appointment next Tuesday.” The agent should greet you first, call check_appointment_availability, ask for any missing details, repeat the selection, request explicit confirmation, and call book_demo_appointment.

Voila! You now have a tool-using Gemini Live agent running on a real phone call, with the entire interaction visible in your browser.

Troubleshoot the most common phone-call issues

The phone rings, but you hear silence. Confirm that the webhook uses POST, the public hostname in .env matches the active tunnel, and welcome_instruction is configured. Open /health through the public URL to confirm the tunnel can reach the app.

The WebSocket connects and immediately closes. Inspect the server log for a media-format validation error. Twilio Media Streams should report audio/x-mulaw, an 8,000 Hz sample rate, and one channel.

Audio sounds choppy or too fast. Make sure μ-law bytes are decoded before resampling, keep the sample-rate converter state between chunks, and send complete 20-millisecond output frames. Treating μ-law as PCM produces noise rather than speech.

The agent keeps speaking over the caller. Confirm that Gemini interruption events cause both the local output buffer to reset and a Twilio clear event to be sent. Clearing only one side leaves stale audio queued on the other.

The transcript looks duplicated. Streaming transcription APIs can emit deltas or cumulative text. The demo’s _merge_transcription() helper handles both forms before a turn is committed to TAC session metadata.

Place an outbound call

The same provider supports outbound calls, so the audio bridge and tools do not need a second implementation. Pass an E.164-formatted destination when the app starts:

uv run python app.py --to +15551234567

The flag sets DEMO_OUTBOUND_TO, and the application uses the existing VoiceChannel:

async def place_outbound_call(to: str) -> None:
    result = await voice_channel.initiate_outbound_conversation(
        InitiateVoiceConversationOptions(to=to)
    )
    print(f"Outbound call placed to {to}: {result.call_sid}")

TAC asks Twilio to place the call, connects the bidirectional Media Stream, and hands it to the same GeminiLiveProvider used for inbound calls.

Prepare the demo for production This project is intentionally compact, but the seams are ready for production-minded upgrades. Externalize active session and dashboard state before running multiple replicas, add structured latency metrics, support session resumption for long calls, and protect tool calls with authentication and idempotency. Add call-duration limits, spend alerts, load shedding, and a clear human-handoff path before introducing real customer traffic.

Additional resources

Conclusion

You built a Python voice agent that connects Twilio Programmable Voice to Gemini Live through a reusable Agent Connect provider. Along the way, you translated real phone audio in both directions, handled caller interruptions, exposed Python tools, streamed a live transcript, and reused the same channel for outbound calls. The appointment concierge is a starting point for order status, scheduling, support triage, and other workflows that need natural conversation plus trusted backend actions. I can’t wait to see what you build!

Rishab Kumar is a Developer Evangelist at Twilio and a cloud enthusiast. Get in touch with Rishab on Twitter @rishabincloud and follow his personal blog on cloud, DevOps, and DevRel adventures at youtube.com/@rishabincloud .