Skip to main content

Connect to OpenAI and build a voice chatbot

Time: 10:35 AM to 11:25 AM
In this section, you will connect your robot to a real large language model and have a spoken conversation with it. By the end, the full loop will be running: you speak, the robot transcribes, GPT responds, and the robot speaks the answer out loud.

The architecture

Here is what you are building: Every component runs on your Raspberry Pi except the OpenAI API, which runs in the cloud. Vosk (speech-to-text) and espeak (text-to-speech) both run locally — no internet needed for those.

Set up the API key

The facilitator will provide an OpenAI API key. Store it on your robot:
Paste the key between the quotes:
Save with Ctrl+O, Enter, Ctrl+X.
If espeak is not producing sound, run bash ~/camp/troubleshoot.sh and select the audio check.

Program 1: Test the API connection

Before adding voice, confirm that your robot can talk to GPT over the internet.

Step 1 — Import and connect

Load the API key from your secret file and create an OpenAI client:
sys.path.insert tells Python where to find secret.py. The OpenAI client handles all communication with the API.

Step 2 — Send a single prompt

The API uses a messages list. Each message has a role and content:
There are three roles:
  • system — hidden instructions that shape the model’s behavior
  • user — what you (the human) say
  • assistant — what the model says back
The model reads the entire list and generates the next assistant message.

Step 3 — Interactive chat loop

To have a back-and-forth conversation, keep a growing messages list. Append each user message and assistant response so the model remembers the conversation:
Each time through the loop, the model sees the entire conversation history. This is how you give an LLM “memory” within a single session.

Run it

You should see:
If you get an authentication error, double-check the API key in ~/camp/secret.py. Make sure there are no extra spaces or missing quotes.

Program 2: Test speech-to-text

Now test the microphone and Vosk speech recognition. This program listens through your USB mic and prints what it hears in real time.

Step 1 — Suppress ALSA noise and import libraries

The Pi’s audio system prints dozens of harmless warnings. This block silences them before importing the audio libraries:
You do not need to understand the ctypes code — it just tells ALSA to be quiet. The important imports are vosk (speech recognition) and pyaudio (microphone access).

Step 2 — Find the USB microphone

The Pi may have multiple audio devices. This function scans for one with “usb” in its name:
It returns the device index and the mic’s native sample rate (usually 44100 Hz for USB mics). Using the native rate avoids “Invalid sample rate” errors.

Step 3 — Load Vosk and open the mic stream

Create the speech recognition model and open a live audio stream from the mic:
chunk is how many audio samples to read at a time — one quarter of a second’s worth. The recognizer processes these chunks and detects when you finish a sentence.

Step 4 — The transcription loop

Read audio chunks in a loop. When Vosk detects a complete sentence, print it:
AcceptWaveform returns True when the recognizer detects a pause — meaning you finished a word or sentence. The result is a JSON string containing the transcribed text.

Run it

Speak clearly into the USB microphone:
Press Ctrl-C to stop.
Tips for better recognition:
  • Speak slowly and clearly — about half your normal speed
  • Keep the microphone 6-12 inches from your mouth
  • Minimize background noise (close windows, turn off fans)
  • Short, distinct phrases work better than long sentences

Program 3: The voice chatbot

Now combine everything into a full conversation loop.

Step 1 — The speak function

Use espeak to convert text to speech:
This blocks until the robot finishes speaking, so the mic does not pick up the robot’s own voice.

Step 2 — The listen function

Wrap the Vosk transcription loop in a function with a timeout. This listens for a single sentence:
If no speech is detected within timeout seconds, it returns whatever partial text it has (or an empty string).

Step 3 — The system prompt

Define the robot’s personality. This hidden instruction shapes every response:
Short answers work best because espeak reads them aloud. A 3-paragraph response would take 30 seconds to speak.

Step 4 — The main conversation loop

Tie everything together. Listen, send to GPT, speak the response, repeat:
The messages list grows with every exchange. The model sees the full history, so it can reference things you said earlier in the conversation.

Run it

Or use keyboard mode if your mic is giving trouble:
You should hear the robot greet you and then listen for your questions:
Say “goodbye” to end the conversation.

Customize the personality

The system prompt defines who the robot thinks it is. Try changing the SYSTEM_PROMPT variable in voice_chatbot.py to give the robot a different personality: Edit the file:
Find the SYSTEM_PROMPT variable near the top and replace the text between the triple quotes.
The system prompt is the single most powerful control you have over the model’s behavior. There is no wrong answer here — experiment freely. The weirder the persona, the more fun it is.

Challenge

Create a persona that refuses to answer questions about anything except robots. If someone asks about the weather, it should steer the conversation back to robots. Test it with 5 different questions and see if it stays in character.