How to Build a Voice AI Agent with Python and FastAPI

Read the article
VH CHAUDHARY
How to Build a Voice AI Agent with Python and FastAPI
In this article

Introduction

A Voice AI agent built with Python and FastAPI can answer phone calls, understand spoken questions, generate natural responses, and connect conversations to business systems. Unlike a traditional IVR that follows fixed menus, a conversational agent can respond to different requests and use approved tools to perform tasks.

In this tutorial, you will learn how to build a real time Voice AI agent with Python and FastAPI, connect Twilio phone calls to the OpenAI Realtime API, and understand how to extend the prototype for CRM integration, customer support, and production deployment.


1. How Does a Voice AI Agent Work?

A Voice AI agent processes an audio conversation and returns a spoken response. For phone calling, it also needs a telephony connection that carries audio between the caller and your backend.

Voice AI Architecture

The basic workflow is:

  1. Caller: A customer calls a phone number connected to Twilio.
  2. Twilio: Twilio streams the call audio to a secure FastAPI WebSocket endpoint.
  3. FastAPI: The Python backend forwards audio to the AI model and manages the session.
  4. Realtime AI: The model understands speech and generates spoken responses.
  5. Response: FastAPI streams the generated audio back to the caller through Twilio.

For business operations, the backend can also connect the agent to a CRM, help desk, booking system, or ERP through authenticated APIs.

Speech to Speech vs. Speech to Text

A speech to speech model processes audio input and generates speech directly, making it suitable for responsive conversations.

An alternative architecture combines speech to text, a language model, and text to speech as separate services. That approach can offer more control over individual components, but each stage adds integration and latency considerations.

This tutorial uses the speech to speech approach.


2. Set Up Python and FastAPI for Voice AI Development

You will need Python 3.10 or later, a Twilio phone number with Media Streams support, and access to the OpenAI Realtime API.

Install the Python Dependencies

Create a virtual environment and install the packages:

python -m venv venv
source venv/bin/activate
pip install fastapi "uvicorn[standard]" websockets twilio python-multipart python-dotenv

On Windows, activate the environment using venv\Scripts\activate.

Configure the Environment Variables

Create a file named .env in your project:

OPENAI_API_KEY=your_openai_api_key
TWILIO_AUTH_TOKEN=your_twilio_auth_token
PUBLIC_HOST=your-public-host.example.com
OPENAI_REALTIME_MODEL=gpt-realtime-2.1

Use the public hostname only for PUBLIC_HOST, without https:// or a trailing slash. Never commit API credentials to source control.


3. Connect Twilio to a FastAPI Voice Webhook

Twilio can open a bidirectional Media Stream, which allows your backend to receive caller audio and send generated audio back into the same call.

Create the Incoming Call Endpoint

Create a file named main.py. Start with the following imports, configuration, and webhook:

import asyncio
import json
import logging
import os

from dotenv import load_dotenv
from fastapi import FastAPI, Request, WebSocket
from fastapi.responses import Response
from fastapi.websockets import WebSocketDisconnect
from twilio.request_validator import RequestValidator
from twilio.twiml.voice_response import VoiceResponse
from websockets.asyncio.client import connect

load_dotenv()

app = FastAPI()
HOST = os.environ["PUBLIC_HOST"]
API_KEY = os.environ["OPENAI_API_KEY"]
TWILIO_AUTH_TOKEN = os.environ["TWILIO_AUTH_TOKEN"]
MODEL = os.getenv("OPENAI_REALTIME_MODEL", "gpt-realtime-2.1")


@app.post("/voice")
async def incoming_call(request: Request):
    form = dict(await request.form())
    signature = request.headers.get("x-twilio-signature", "")
    public_url = f"https://{HOST}/voice"

    validator = RequestValidator(TWILIO_AUTH_TOKEN)
    if not validator.validate(public_url, form, signature):
        return Response(status_code=403)

    voice_response = VoiceResponse()
    connection = voice_response.connect()
    connection.stream(url=f"wss://{HOST}/media-stream")

    return Response(str(voice_response), media_type="application/xml")

What This Code Does

When a call arrives, Twilio sends a request to /voice. The endpoint validates the webhook and returns TwiML that instructs Twilio to connect the call to /media-stream over a WebSocket.

The public URL used for signature validation must match the URL configured in Twilio. If a reverse proxy changes the host, scheme, or path, adjust your configuration accordingly.


4. Build a Real Time Voice AI Agent with FastAPI WebSockets

Next, add a WebSocket endpoint that relays audio between Twilio and the OpenAI Realtime API.

Add the Audio Streaming Endpoint

Append the following code to main.py:

@app.websocket("/media-stream")
async def media_stream(twilio: WebSocket):
    # Prototype only: authenticate Twilio's WebSocket
    # signature before using this endpoint in production.
    await twilio.accept()

    realtime_url = (
        "wss://api.openai.com/v1/realtime?model=" + MODEL
    )

    async with connect(
        realtime_url,
        additional_headers={
            "Authorization": f"Bearer {API_KEY}"
        },
    ) as ai:
        await ai.send(json.dumps({
            "type": "session.update",
            "session": {
                "type": "realtime",
                "output_modalities": ["audio"],
                "instructions": (
                    "You are an AI customer support assistant. "
                    "Identify yourself as AI and speak briefly. "
                    "Never claim an action was completed "
                    "unless a trusted system confirms it."
                ),
                "audio": {
                    "input": {
                        "format": {"type": "audio/pcmu"},
                        "turn_detection": {
                            "type": "server_vad",
                            "create_response": True,
                            "interrupt_response": True,
                        },
                    },
                    "output": {
                        "format": {"type": "audio/pcmu"},
                        "voice": "marin",
                    },
                },
            },
        }))

        stream_sid = None

        async def caller_to_ai():
            nonlocal stream_sid
            try:
                while True:
                    message = await twilio.receive_json()
                    event = message.get("event")

                    if event == "start":
                        stream_sid = message["start"]["streamSid"]
                    elif event == "media":
                        await ai.send(json.dumps({
                            "type": "input_audio_buffer.append",
                            "audio": message["media"]["payload"],
                        }))
                    elif event == "stop":
                        break
            except WebSocketDisconnect:
                pass

        async def ai_to_caller():
            async for raw in ai:
                event = json.loads(raw)
                event_type = event.get("type")

                if (event_type == "response.output_audio.delta"
                        and stream_sid):
                    await twilio.send_json({
                        "event": "media",
                        "streamSid": stream_sid,
                        "media": {"payload": event["delta"]},
                    })
                elif (event_type == "input_audio_buffer.speech_started"
                        and stream_sid):
                    await twilio.send_json({
                        "event": "clear",
                        "streamSid": stream_sid,
                    })
                elif event_type == "error":
                    logging.error("Realtime API: %s", event)

        tasks = [
            asyncio.create_task(caller_to_ai()),
            asyncio.create_task(ai_to_caller()),
        ]
        done, pending = await asyncio.wait(
            tasks, return_when=asyncio.FIRST_COMPLETED
        )
        for task in pending:
            task.cancel()
        await asyncio.gather(*pending, return_exceptions=True)
        for task in done:
            if not task.cancelled() and task.exception():
                raise task.exception()

How the WebSocket Connection Works

Caller to AI: FastAPI receives base64 encoded audio chunks from Twilio and forwards them as input_audio_buffer.append events.

AI to caller: FastAPI receives response.output_audio.delta events from OpenAI and sends the encoded audio back to Twilio.

Interruptions: When speech is detected, the example sends a Twilio clear message to remove queued playback. A full implementation must also track which audio was actually heard and synchronize cancellation with conversation history.

Twilio uses G.711 μ-law audio at 8 kHz. Setting both Realtime audio formats to audio/pcmu keeps the prototype's audio formats compatible.

Important: This example demonstrates the core relay but is not production ready. In particular, it does not yet validate the WebSocket handshake signature, implement full playback tracking, or provide resilient failure recovery. Do not expose it as an unrestricted public service.


5. Run and Test Your Python Voice AI Agent

Start the FastAPI Server

Run the application:

uvicorn main:app --host 0.0.0.0 --port 8000

For local testing, use a secure tunnel that forwards an HTTPS public hostname to port 8000, and set PUBLIC_HOST to that hostname.

Configure the Twilio Phone Number

In Twilio's phone number settings, configure the incoming voice webhook as an HTTP POST request to:

https://your-public-host.example.com/voice

Call the number and ask a simple question. The caller's audio should reach FastAPI, the realtime model should generate a spoken response, and Twilio should play that response on the call.

What to Test

Test ordinary questions, silence, interruptions, long responses, connection failures, and noisy audio. Track both answer quality and the delay between a caller finishing a question and hearing the agent respond.


6. Connect the Voice AI Agent to a CRM or Business API

A Python voice agent becomes more valuable when it can complete a real business workflow instead of only answering general questions.

Example: CRM Integrated Voice AI Agent

Imagine a customer calls to check an order status. The agent can:

  1. Recognize the order status request.
  2. Ask for the information needed to identify the order.
  3. Invoke an approved backend tool.
  4. Retrieve the order record from a CRM or ERP after authorization checks.
  5. Explain the confirmed status to the caller.

The same approach can qualify inbound leads, create help desk tickets, or schedule appointments.

What Needs to Be Added to the Code?

The audio relay above does not perform these actions by itself. You must define tool schemas for the realtime model, process tool call events in Python, call authenticated business APIs, and send verified tool results back to the session.

For sensitive actions such as changing account details or placing orders, require the appropriate caller verification and explicit confirmation.


7. Prepare the Voice AI Agent for Production Deployment

A working voice AI demo is different from a production system serving real customers.

Production Requirements

Security: Validate both HTTP and WebSocket Twilio signatures, protect API keys, authenticate backend tools, and enforce access controls.

Latency: Measure response time across telephony, your FastAPI server, the AI model, and connected APIs.

Interruption handling: Keep generated speech, actual playback, and conversation state synchronized when someone speaks over the agent.

Scalability: Monitor active WebSocket connections, concurrent calls, model limits, and resource usage.

Reliability: Add timeouts, retries where safe, structured logging, and a clear fallback when an external service fails.

Human handoff: Route complex or sensitive requests to a human when the agent cannot safely complete them.

Privacy: Apply suitable recording consent, retention, and data protection practices for the countries and industries you serve.

For a reference implementation with playback tracking and tool support, see the OpenAI Agents SDK Twilio example.


8. Where Can Businesses Use Voice AI Agents?

AI Customer Support Agent

Answer common questions, check authorized account records, create tickets, and escalate unresolved issues.

AI Sales and Lead Qualification Agent

Handle inbound sales calls, collect prospect requirements, and update CRM records with confirmed information.

AI Appointment Booking Agent

Check available times through a scheduling API, confirm bookings, and trigger approved follow up messages.

AI Phone Calling Agent

Support inbound calls or properly authorized outbound workflows, including reminders and confirmations.

Voice AI Agent for Odoo ERP

Connect calls with Odoo CRM, Helpdesk, Sales, and other modules through authenticated backend services.


9. How Much Does It Cost to Build a Voice AI Agent?

Voice AI development cost depends on the required workflows, integrations, call volume, and production requirements.

Main Cost Factors

Development: FastAPI backend, conversation logic, API integrations, and testing.

AI usage: Realtime speech processing and generated audio.

Telephony: Phone number rental, call minutes, and provider charges.

Infrastructure: Hosting, observability, and concurrent session capacity.

Maintenance: Monitoring, updates, compliance changes, and ongoing improvements.

For a meaningful estimate, define the expected number of calls, average call duration, languages, CRM or ERP integrations, and tasks the agent must complete.


10. How PySquad Helps Build Custom Voice AI Agents

Developing a voice agent prototype with Python and FastAPI is a useful first step. Connecting that prototype to real customer workflows requires reliable APIs, secure data access, telephony integration, and production engineering.

PySquad helps businesses develop custom voice AI agents for customer support, sales automation, appointment scheduling, and other call driven processes. Our engineering capabilities include Python and FastAPI development, realtime AI integration, custom backend APIs, CRM and Odoo ERP integration, and deployment support.

If you already have a prototype, we can help assess its architecture and identify what is needed for production. If you are starting from a business requirement, we can help define the call workflow and the backend integrations required to support it.

Explore PySquad's Voice AI Agents for Customer Support and Sales to discuss your project.


Conclusion

Building a Voice AI agent with Python and FastAPI involves more than sending audio to a model. Twilio handles the call, FastAPI manages the real time WebSocket connections, and the OpenAI Realtime API processes speech and generates spoken responses.

A useful production voice agent also needs accurate business data, authorized tool execution, interruption management, monitoring, and dependable human handoff. Start with one clear calling workflow, test it with real scenarios, and expand the implementation once its reliability is established.


Frequently Asked Questions

1. How do I build a Voice AI agent with Python and FastAPI?

Use FastAPI WebSockets to stream audio between a telephony or browser client and a realtime speech model. Add conversation instructions, session management, and backend tools for business workflows. For phone calls, Twilio Media Streams can carry the incoming and outgoing audio.

2. Can FastAPI handle real time voice conversations?

Yes. FastAPI supports asynchronous WebSocket connections for streaming audio and events. It manages backend communication while the speech model handles voice processing. Production reliability also depends on concurrency controls and connection management.

3. How do I connect a Twilio voice AI agent with OpenAI?

Configure a Twilio incoming call webhook that connects to a bidirectional Media Stream. Your Python backend forwards the incoming base64 encoded audio to the OpenAI Realtime API and returns generated audio to Twilio in the required format.

4. Can I integrate a Python Voice AI agent with Salesforce, HubSpot, or Odoo?

Yes. You can connect the agent to business systems using authenticated backend tools and APIs. The AI can request actions such as looking up an order or creating a support ticket, while the backend validates permissions and confirms the result.

5. Can a Voice AI agent book appointments and qualify leads?

Yes, when connected to a scheduling platform or CRM. It can collect necessary information and request a backend action. The actual appointment or lead update should be confirmed by the connected system before the agent tells the caller it is complete.

6. How much does custom Voice AI agent development cost?

The cost varies with business workflows, real time model usage, call volumes, integrations, infrastructure, and security requirements. A scoping exercise is the best way to estimate both development and ongoing operating expenses.

7. What is needed to deploy a production ready Voice AI agent?

Beyond a working audio connection, you need secure authentication, reliable tool execution, interruption handling, monitoring, scalability, suitable privacy controls, and escalation paths for callers who need human assistance.

After this article

Where this applies in the work.

How to Build a Voice AI Agent with Python and FastAPI sits in our AI Agents writing. Continue into related articles, the matching service pages, or a conversation about your workflows.

See it on your workflows

Walk through this with your operation in mind.

Discuss your requirements