How to Build a Gemini Live Voice Agent with Twilio Agent Connect and Python
Time to read:
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:
- Python 3.11 through 3.14 and
uv - A Twilio account and a voice-capable Twilio phone number
- A Twilio Account SID, Auth Token, API Key SID, and API Key Secret from the Twilio Console
- A Gemini API key with access to a Live API model
- A public HTTPS and secure WebSocket (WSS) endpoint; ngrok works well for local development
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:
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:
Open .env and add your credentials:
Set TWILIO_VOICE_PUBLIC_DOMAIN to the hostname only. For example, use your-subdomain.ngrok.app, without https:// or a trailing path.
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.
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.
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:
The provider sends each converted caller chunk to Gemini with the required MIME type:
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:
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.
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:
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:
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:
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:
Copy the ngrok hostname into TWILIO_VOICE_PUBLIC_DOMAIN, then start the application in another terminal:
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:
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:
The flag sets DEMO_OUTBOUND_TO, and the application uses the existing VoiceChannel:
TAC asks Twilio to place the call, connects the bidirectional Media Stream, and hands it to the same GeminiLiveProvider used for inbound calls.
Additional resources
- Twilio Agent Connect documentation
- Twilio Agent Connect Python quickstart
- Twilio Media Streams WebSocket messages
- Gemini Live API guide
- Gemini Live API capabilities
- Gemini 3.8 Live model reference
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 .
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.