Why Build a Voice‑Enabled Chatbot?
Voice is the most natural way humans communicate. With the rise of smart speakers, in‑car assistants, and hands‑free workflows, developers are looking for ways to bring conversational AI into everyday life. A voice‑enabled chatbot lets users:
- Interact without screens – great for mobile, automotive, or IoT scenarios.
- Leverage advanced language models – OpenAI’s GPT‑4 or GPT‑3.5 turbo can generate context‑rich responses.
- Deliver high‑quality speech – ElevenLabs offers state‑of‑the‑art TTS and voice cloning that sound almost human.
In this article we’ll walk through a minimal, end‑to‑end prototype that ties together:
- Speech‑to‑Text (STT) – transcribe the user’s voice into text.
- OpenAI – generate a natural language reply.
- ElevenLabs – synthesize the reply back into speech (optionally in a cloned voice).
We’ll use Python for the server side and a tiny front‑end in HTML/JavaScript to capture audio. Ready? Let’s dive in.
1. Project Structure
voice‑chatbot/
├─ app.py # FastAPI backend
├─ static/
│ ├─ index.html # Simple UI
│ └─ script.js # Audio capture & fetch logic
└─ requirements.txt
We’ll keep everything in one repository for simplicity. Feel free to split the logic into micro‑services if you scale up.
2. Setting Up the Environment
# Create a virtual environment
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# Install dependencies
pip install fastapi uvicorn openai elevenlabs python-multipart
Tip: If you’re on Windows, use
pip install uvicorn[standard]to get the ASGI server with the best performance.
Create a requirements.txt for reproducibility:
fastapi
uvicorn[standard]
openai
elevenlabs
python-multipart
3. OpenAI Integration
We’ll use the OpenAI Python SDK to send the user’s text and receive a response. Make sure you have an API key from the OpenAI dashboard.
# openai_client.py
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
def get_gpt_response(prompt: str) -> str:
"""Return GPT‑3.5 turbo completion for a given prompt."""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
max_tokens=300,
)
return response.choices[0].message.content.strip()
Security note: Never commit your API key. Use environment variables or a secrets manager.
4. ElevenLabs TTS and Voice Cloning
ElevenLabs provides a fast, high‑fidelity TTS API. Their voice cloning feature lets you generate speech that mimics a target voice from a few minutes of audio.
# elevenlabs_client.py
import os
from elevenlabs import generate, play, set_api_key
set_api_key(os.getenv("ELEVENLABS_API_KEY"))
def synthesize(text: str, voice_id: str = None) -> bytes:
"""Return raw audio data for the given text."""
audio = generate(
text=text,
voice=voice_id or "default", # replace with a real voice ID if you have one
model="eleven_monolingual_v1",
)
return audio # bytes that can be sent as MP3
How to get a voice ID: In the ElevenLabs dashboard, go to Voices → Create Voice → Upload Samples. After the model finishes training, you’ll see an ID you can use here.
5. Speech‑to‑Text (Optional)
If you want to capture raw voice and convert it to text on the fly, you can use OpenAI’s Whisper or any other STT service. For brevity, we’ll skip the STT code and assume the front‑end sends plain text. If you need STT, consider:
pip install openai-whisper
and then:
import whisper
model = whisper.load_model("base")
result = model.transcribe("audio.wav")
prompt = result["text"]
6. FastAPI Backend
# app.py
import os
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from openai_client import get_gpt_response
from elevenlabs_client import synthesize
app = FastAPI()
# Allow local front‑end to talk to the API
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:8000"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/chat")
async def chat(prompt: str):
"""Handle a text prompt and return synthesized speech."""
# 1. Get GPT reply
reply = get_gpt_response(prompt)
# 2. Synthesize speech
audio_bytes = synthesize(reply)
# 3. Stream back as MP3
return StreamingResponse(
iter([audio_bytes]),
media_type="audio/mpeg",
headers={"Content-Disposition": "attachment; filename=reply.mp3"},
)
Why StreamingResponse? It streams the audio directly to the browser without saving it on disk.
7. Front‑End: Capture & Play
Create a simple UI that records audio, sends it to the backend, and plays the reply.
<!-- static/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Voice Chatbot Demo</title>
</head>
<body>
<h1>Speak to the Bot</h1>
<button id="recordBtn">Start Recording</button>
<p id="status"></p>
<script src="script.js"></script>
</body>
</html>
// static/script.js
const recordBtn = document.getElementById('recordBtn');
const status = document.getElementById('status');
let mediaRecorder;
let audioChunks = [];
recordBtn.onclick = async () => {
if (recordBtn.textContent === 'Start Recording') {
// Start recording
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
status.textContent = 'Recording...';
mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
mediaRecorder.onstop = sendAudio;
recordBtn.textContent = 'Stop Recording';
} else {
// Stop recording
mediaRecorder.stop();
recordBtn.textContent = 'Start Recording';
}
};
async function sendAudio() {
const blob = new Blob(audioChunks, { type: 'audio/webm' });
audioChunks = []; // reset for next recording
// Send raw audio to the backend (you can also do STT here)
const formData = new FormData();
formData.append('file', blob, 'recording.webm');
status.textContent = 'Processing...';
// For demo purposes, we’ll just convert the audio to text with a placeholder
// Replace this with real STT if you have one
const prompt = 'Hello, how can I help you?';
const response = await fetch('http://localhost:8000/chat', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: prompt,
});
if (!response.ok) {
status.textContent = 'Error!';
return;
}
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();
status.textContent = 'Done!';
}
Note: The front‑end above sends a hard‑coded prompt. In a real app, you’d run STT on the recorded audio or use Web Speech API for live transcription.
8. Running the Demo
# Start the FastAPI server
uvicorn app:app --reload
Open http://localhost:8000/static/index.html in your browser, hit “Start Recording”, speak a short phrase, and watch the bot answer in synthesized voice.
9. Scaling & Deployment
- Use HTTPS – both OpenAI and ElevenLabs require secure connections for production.
- Containerize – Dockerfile:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "80"]
- Autoscaling – Deploy to a platform like Fly.io, Render, or Azure Functions. FastAPI + Uvicorn scales nicely with worker processes.
10. Tips & Tricks
| Topic | How to Improve |
|---|---|
| Latency | Use ElevenLabs’ eleven_monolingual_v1 which is lightweight. Cache frequent prompts. |
| Voice Cloning | Upload 5–10 minutes of clear audio to ElevenLabs, then use the generated voice_id in synthesize(). |
| Privacy | If you’re handling sensitive data, store audio only in memory and delete it after processing. |
| Fallback | If the TTS fails, return a plain text response and let the front‑end display it. |
| Multilingual | ElevenLabs supports multiple languages. Set the model and voice accordingly. |
11. Wrap‑Up
You now have a working prototype that turns spoken words into a GPT‑powered answer and speaks it back using ElevenLabs’ high‑quality TTS. From here you can:
- Add real STT (Whisper, Google Cloud Speech, etc.).
- Enable voice cloning for personalized avatars.
- Integrate with smart speakers or car infotainment systems.
- Deploy to production and monitor usage.
The combination of OpenAI for natural language understanding and ElevenLabs for realistic speech synthesis gives you a powerful foundation for any voice‑enabled application.
Try ElevenLabs Today
If you’re excited to build voice experiences that sound human‑like, start with ElevenLabs. Sign up and get a free trial credit at https://try.elevenlabs.io/kr07zfuqn1bp and experiment with voice cloning, TTS, and more. Happy coding!
Top comments (0)