Minimal example consisting of a small FastAPI service (backend.py)
that mints an EPHEMERAL_KEY for the OpenAI realtime WebRTC API and a
matching Streamlit app (app.py) that demonstrates the browser
interaction.
-
Install the dependencies
The backend only depends onfastapi,uvicornandopenaiwhile the app relies onstreamlit:pip install fastapi uvicorn streamlit openai
-
Set up your credentials
The backend will refuse to start unless the environment variableOPENAI_API_KEYis defined:export OPENAI_API_KEY="sk-..." # replace with your key
-
Run the backend
In one shell run:uvicorn backend:app --host 0.0.0.0 --port 8000
-
Run the Streamlit frontend
In another terminal execute:streamlit run app.py --server.port 8501
The demo page becomes available at http://localhost:8501 and will internally call
http://localhost:8000/sessionwhen the "Connect & Talk" button is pressed.
Basic syntax check for both python files:
python3 -m py_compile backend.py app.pyTo ensure the backend is reachable, start it as shown above and try to fetch a session:
curl http://localhost:8000/sessionThis should return a JSON document containing a client_secret. When
running in restricted environments the call may fail with Realtime
token request failed if the openai library lacks realtime
functionality or the outgoing connection is blocked.
- Provide a
requirements.txtorpyproject.tomlto make the dependency versions explicit. This also allows forpip install -r requirements.txtstyle bootstrapping. - Automatically read configuration from a
.envfile usingpython-dotenvto avoid the need for external environment variables. - Add input validation and better error reporting in
create_sessionso it becomes obvious whether the OpenAI request failed due to network restrictions or missing API capabilities. - Ship a
Dockerfileanddocker-compose.ymlfor reproducible local runs (especially handy when the local python environment is missing some requirements). - Include unit tests for the FastAPI route and a simple smoke test for the Streamlit component to facilitate regression testing.
- Lint/format the project via tools such as
flake8,pylint, orblackto keep the code quality high (CI integration would help automate this.) - Expose the service on a configurable host/port instead of fixed values to simplify embedding into other systems.