Gemini 4 Live Translate for Python
Build live speech-to-speech translation with Gemini 4 Live Translate, Python and Agora.
实践教程
本教程目录
文档语言:作者未标注语言
Gemini 4 Live Translate Speech Translation (Python)
Goal
Build a live speech-to-speech translation app. The user speaks into the browser microphone, and an Agora Conversational AI agent running Gemini 4 Live Translate (gemini-4-live-translate) speaks the translation back in the chosen target language. The browser shows a live transcript (source speech and translation), agent state, latency metrics and connection status. A FastAPI backend issues Agora tokens and starts and stops the agent. A Next.js client handles audio and the UI.
Stack and prerequisites
- Python 3.10 or newer (FastAPI, uvicorn) for
server/. - bun for the JS workspace; Next.js 16, React 19 for
web/. - SDK:
agora-agents==2.16.0from PyPI (pinned inserver/requirements.txtandpyproject.toml). - An Agora project with an App ID and App Certificate (Conversational AI enabled).
- A Google API key with Gemini Live access.
Quick start
git clone https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python.git
cd agora-gemini-4-live-translate-python
bun run setupbun run setup creates server/venv, installs the Python and JS dependencies, and copies server/.env.example to server/.env.local. Fill in server/.env.local:
| Variable | Required | Purpose |
|---|---|---|
AGORA_APP_ID | yes | Agora project App ID. |
AGORA_APP_CERTIFICATE | yes | Agora App Certificate, used to sign tokens. Server-only. |
GOOGLE_API_KEY | yes | Gemini Live API key. Server-only; the backend refuses to start without it. |
PORT | no | FastAPI port, default 8000. Set at launch only. |
If you use the Agora CLI, agora project env write server/.env.local writes the Agora values.
Run both processes:
bun run devOpen the Next.js URL it prints (http://localhost:3000 by default), allow microphone access, pick a target language and start the call. bun run dev sets AGENT_BACKEND_URL=http://localhost:8000 for the web process. A deployed web app needs AGENT_BACKEND_URL set to the FastAPI URL (see web/.env.local.example).
Architecture
Two processes in one repo: web/ (Next.js client) and server/ (FastAPI). The browser only calls /api/*, and Next.js rewrites those paths to FastAPI.
- The browser calls
GET /api/get_config. FastAPI returns the App ID, a single RTC+RTM token for a concrete user UID, a channel name and the agent UID. - The browser joins the RTC channel, logs in to RTM and publishes the microphone.
- The browser calls
POST /api/startAgentwith the channel, UIDs,translateToandechoTargetLanguage. - FastAPI builds the agent with the Agora SDK and starts it in the channel. Gemini receives the user's audio from the channel.
- The agent publishes the translated speech into the channel. Transcripts, agent state, metrics and errors arrive in the browser over RTM.
- On hang-up the browser calls
POST /api/stopAgentwith theagentId.
Key files (links resolve from this file):
- server/src/server.py: routes, request models, token generation, error mapping.
- server/src/agent.py: builds, starts and stops the agent; validates language and options.
- web/next.config.ts: the
/api/*rewrites driven byAGENT_BACKEND_URL. - web/src/services/api.ts: browser fetch helpers.
- web/src/components/LandingPage.tsx: config fetch, agent start, RTM login, token renewal, teardown.
- web/src/components/ConversationComponent.tsx: RTC join, microphone, transcript, state and metrics listeners.
- web/src/components/TranslateOptions.tsx: language list, default language and echo toggle.
How the agent is configured
server/src/agent.py builds the agent with one GeminiLive provider and the SDK builder. The SDK routes the model by name, so do not set the URL, voice or headers.
mllm = GeminiLive(
api_key=self.google_api_key,
model=TRANSLATE_MODEL, # GeminiLiveModels.LIVE_4_TRANSLATE
translate_to=translate_to,
echo_target_language=bool(echo_target_language),
transcribe_agent=True,
transcribe_user=True,
)
agora_agent = AgoraAgent(
client=self.client,
advanced_features={"enable_rtm": True},
parameters={"data_channel": "rtm", "enable_error_message": True, "enable_metrics": True},
).with_mllm(mllm)
session = agora_agent.create_async_session(
channel=channel_name,
agent_uid=str(agent_uid),
remote_uids=[str(user_uid)],
expires_in=3600,
)
agent_id = await session.start()- Model: always
gemini-4-live-translate. translate_to: target language code, defaultes, restricted to an allow-list.echo_target_language: whether speech already in the target language is spoken back; defaultfalse.transcribe_userandtranscribe_agentfeed the transcript panel: the user line is the source speech, the agent line is the translation.- No prompt, greeting, tools or thinking level is sent.
API contract (all successful responses are { "code": 0, "msg": "success", "data": ... }):
| Endpoint | Request | Response |
|---|---|---|
GET /api/get_config | Query channel?, uid?. A missing, zero or negative uid is replaced by a generated one. | data.app_id, data.token, data.uid, data.channel_name, data.agent_uid |
POST /api/startAgent | { channelName, rtcUid, userUid, model?, translateTo?, echoTargetLanguage?, parameters? } | data.agent_id, data.channel_name, data.status |
POST /api/stopAgent | { agentId } | { code: 0, msg: "success" } |
startAgent validation returns 400 for a model other than gemini-4-live-translate, a translateTo off the allow-list, a non-boolean echoTargetLanguage, and any thinkingLevel. parameters.output_audio_codec is the only accepted parameters key.
Customize
| Change | Edit |
|---|---|
| Supported target languages | TRANSLATE_LANGUAGES in server/src/agent.py and TRANSLATE_LANGUAGES in web/src/components/TranslateOptions.tsx. Keep both lists identical and update server/tests/test_agent.py if it asserts the list. |
| Default language | DEFAULT_TRANSLATE_TO in server/src/agent.py and in web/src/components/TranslateOptions.tsx. |
| Echo default | useState(false) for echoTargetLanguage in web/src/components/LandingPage.tsx, and the bool(echo_target_language) fallback in server/src/agent.py. |
| Backend port | Launch with PORT=<n>; point AGENT_BACKEND_URL at it. bun run dev:parallel shows a second instance on 8110. |
| Agent options (RTM, metrics, transcription) | server/src/agent.py only. The browser must not invent agent parameters. |
| UI (pre-call card, transcript, metrics, status) | web/src/components/Quickstart*.tsx, ConnectionStatusPanel.tsx, MicrophoneSelector.tsx. |
| New API route | Add the FastAPI route in server/src/server.py, a rewrite in web/next.config.ts, a helper in web/src/services/api.ts, then extend web/scripts/verify-api-contracts.ts. |
Verify
bun run verify # doctor, API contract check, web build
bun run build # Next.js production build
(cd server && venv/bin/python3 -m pip install -r requirements-dev.txt && venv/bin/python3 -m pytest tests) # backend tests (pytest, httpx)With real credentials in server/.env.local, bun run verify:local adds a backend compile check, a fake-FastAPI smoke test and a proxy check. Success is every command exiting 0. In the running app, the transcript shows your speech and its translation, the agent speaks the translation, and the metrics panel shows latency values.
Deploy
Deploy web/ and server/ separately. Set AGENT_BACKEND_URL to the public FastAPI URL, and keep the Agora App Certificate and Google API key on the server.
Gotchas
- Only allow-listed language codes work:
es fr ja pt zh ko hi ar de pt-BR pt-PT zh-CN zh-Hans cmn. Codes such ases-ES,en-US,ja-JP,de-DE,ko-KR,es-MXandspamake the vendor close the session with an opaque 1007, so the backend returns 400 for them. - Do not add a prompt, greeting or tools. The translate model never speaks a greeting and ignores a prompt, and instructions, tools or
media_resolutioncan close the session. GOOGLE_API_KEY,AGORA_APP_IDandAGORA_APP_CERTIFICATEare all required. If any is missing the backend sets no agent and the routes return 500.- Do not set
mllm.enablein the agent. It stops the RTM metrics messages, and the metrics panel stays empty. AGENT_BACKEND_URLmust be set for the web process. Without it Next registers no rewrites and every/api/*call returns 404.- Do not add
web/app/api/**/route.tshandlers;verify:web:apifails on them. - The token must be issued for a concrete non-zero UID, because RTM rejects UID 0.
- CORS is open (
*) for local use. Restrict it before exposing the backend publicly.
Related docs
- README: setup and run steps.
- L0 repo card: identity and index of the L1 docs.
- L1/01_setup.md: setup, env and command reference.
- L1/02_architecture.md: request flow and topology.
- L1/05_workflows.md: common modification workflows.
- L1/06_interfaces.md: routes, rewrites, env and event contracts.
- L1/07_gotchas.md: detailed pitfalls.
- L1/L2/managed_agent_config.md: full agent config.
- L1/L2/session_lifecycle.md: RTC, RTM and session orchestration.
- L1/L2/verification_scripts.md: each verify script.
- L1/L2/from_scratch_bootstrap.md: recreating this recipe from scratch.
Recipe 元数据
| 字段 | 值 |
|---|---|
recipe_version | 0.1.0 |
recipe_slug | agora-gemini-4-live-translate-python |
recipe_name | Gemini 4 Live Translate Speech Translation for Python |
recipe_status | stable |
extension_points |
|
invariants |
|
stable_contracts |
|
---
recipe_version: 0.1.0
recipe_slug: agora-gemini-4-live-translate-python
recipe_name: Gemini 4 Live Translate Speech Translation for Python
recipe_status: stable
extension_points:
- id: api.routes
name: Browser-facing API routes
- id: agent.managed-config
name: Translation target language, echo toggle, and voice
- id: web.conversation-ui
name: Conversation UI panels and controls
- id: verification.contracts
name: Contract and local smoke verification
invariants:
- id: api.rewrite-boundary
summary: Browser calls stay on /api/* and Next rewrites to FastAPI.
- id: secrets.server-only
summary: Agora App Certificate and BYOK keys stay in the Python backend.
- id: token.uid-concrete
summary: Backend resolves missing, zero, or negative UIDs before issuing RTC+RTM tokens.
stable_contracts:
- id: env.required
summary: AGORA_APP_ID, AGORA_APP_CERTIFICATE, and GOOGLE_API_KEY are required by FastAPI; AGENT_BACKEND_URL is required by deployed web rewrites.
- id: api.core-routes
summary: GET /api/get_config, POST /api/startAgent, and POST /api/stopAgent remain the browser-facing contract.
- id: response.envelope
summary: Successful backend responses use { code, msg, data }.
---
# Gemini 4 Live Translate Speech Translation (Python)
## Goal
Build a live speech-to-speech translation app. The user speaks into the browser microphone, and an Agora Conversational AI agent running Gemini 4 Live Translate (`gemini-4-live-translate`) speaks the translation back in the chosen target language. The browser shows a live transcript (source speech and translation), agent state, latency metrics and connection status. A FastAPI backend issues Agora tokens and starts and stops the agent. A Next.js client handles audio and the UI.
## Stack and prerequisites
- Python 3.10 or newer (FastAPI, uvicorn) for `server/`.
- [bun](https://bun.sh) for the JS workspace; Next.js 16, React 19 for `web/`.
- SDK: `agora-agents==2.16.0` from PyPI (pinned in `server/requirements.txt` and `pyproject.toml`).
- An Agora project with an App ID and App Certificate (Conversational AI enabled).
- A Google API key with Gemini Live access.
## Quick start
```bash
git clone https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python.git
cd agora-gemini-4-live-translate-python
bun run setup
```
`bun run setup` creates `server/venv`, installs the Python and JS dependencies, and copies `server/.env.example` to `server/.env.local`. Fill in `server/.env.local`:
| Variable | Required | Purpose |
| -------- | -------- | ------- |
| `AGORA_APP_ID` | yes | Agora project App ID. |
| `AGORA_APP_CERTIFICATE` | yes | Agora App Certificate, used to sign tokens. Server-only. |
| `GOOGLE_API_KEY` | yes | Gemini Live API key. Server-only; the backend refuses to start without it. |
| `PORT` | no | FastAPI port, default `8000`. Set at launch only. |
If you use the Agora CLI, `agora project env write server/.env.local` writes the Agora values.
Run both processes:
```bash
bun run dev
```
Open the Next.js URL it prints (http://localhost:3000 by default), allow microphone access, pick a target language and start the call. `bun run dev` sets `AGENT_BACKEND_URL=http://localhost:8000` for the web process. A deployed web app needs `AGENT_BACKEND_URL` set to the FastAPI URL (see `web/.env.local.example`).
## Architecture
Two processes in one repo: `web/` (Next.js client) and `server/` (FastAPI). The browser only calls `/api/*`, and Next.js rewrites those paths to FastAPI.
1. The browser calls `GET /api/get_config`. FastAPI returns the App ID, a single RTC+RTM token for a concrete user UID, a channel name and the agent UID.
2. The browser joins the RTC channel, logs in to RTM and publishes the microphone.
3. The browser calls `POST /api/startAgent` with the channel, UIDs, `translateTo` and `echoTargetLanguage`.
4. FastAPI builds the agent with the Agora SDK and starts it in the channel. Gemini receives the user's audio from the channel.
5. The agent publishes the translated speech into the channel. Transcripts, agent state, metrics and errors arrive in the browser over RTM.
6. On hang-up the browser calls `POST /api/stopAgent` with the `agentId`.
Key files (links resolve from this file):
- [server/src/server.py](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/server/src/server.py): routes, request models, token generation, error mapping.
- [server/src/agent.py](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/server/src/agent.py): builds, starts and stops the agent; validates language and options.
- [web/next.config.ts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/web/next.config.ts): the `/api/*` rewrites driven by `AGENT_BACKEND_URL`.
- [web/src/services/api.ts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/web/src/services/api.ts): browser fetch helpers.
- [web/src/components/LandingPage.tsx](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/web/src/components/LandingPage.tsx): config fetch, agent start, RTM login, token renewal, teardown.
- [web/src/components/ConversationComponent.tsx](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/web/src/components/ConversationComponent.tsx): RTC join, microphone, transcript, state and metrics listeners.
- [web/src/components/TranslateOptions.tsx](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/web/src/components/TranslateOptions.tsx): language list, default language and echo toggle.
## How the agent is configured
`server/src/agent.py` builds the agent with one `GeminiLive` provider and the SDK builder. The SDK routes the model by name, so do not set the URL, voice or headers.
```python
mllm = GeminiLive(
api_key=self.google_api_key,
model=TRANSLATE_MODEL, # GeminiLiveModels.LIVE_4_TRANSLATE
translate_to=translate_to,
echo_target_language=bool(echo_target_language),
transcribe_agent=True,
transcribe_user=True,
)
agora_agent = AgoraAgent(
client=self.client,
advanced_features={"enable_rtm": True},
parameters={"data_channel": "rtm", "enable_error_message": True, "enable_metrics": True},
).with_mllm(mllm)
session = agora_agent.create_async_session(
channel=channel_name,
agent_uid=str(agent_uid),
remote_uids=[str(user_uid)],
expires_in=3600,
)
agent_id = await session.start()
```
- Model: always `gemini-4-live-translate`.
- `translate_to`: target language code, default `es`, restricted to an allow-list.
- `echo_target_language`: whether speech already in the target language is spoken back; default `false`.
- `transcribe_user` and `transcribe_agent` feed the transcript panel: the user line is the source speech, the agent line is the translation.
- No prompt, greeting, tools or thinking level is sent.
API contract (all successful responses are `{ "code": 0, "msg": "success", "data": ... }`):
| Endpoint | Request | Response |
| -------- | ------- | -------- |
| `GET /api/get_config` | Query `channel?`, `uid?`. A missing, zero or negative `uid` is replaced by a generated one. | `data.app_id`, `data.token`, `data.uid`, `data.channel_name`, `data.agent_uid` |
| `POST /api/startAgent` | `{ channelName, rtcUid, userUid, model?, translateTo?, echoTargetLanguage?, parameters? }` | `data.agent_id`, `data.channel_name`, `data.status` |
| `POST /api/stopAgent` | `{ agentId }` | `{ code: 0, msg: "success" }` |
`startAgent` validation returns 400 for a `model` other than `gemini-4-live-translate`, a `translateTo` off the allow-list, a non-boolean `echoTargetLanguage`, and any `thinkingLevel`. `parameters.output_audio_codec` is the only accepted `parameters` key.
## Customize
| Change | Edit |
| ------ | ---- |
| Supported target languages | `TRANSLATE_LANGUAGES` in `server/src/agent.py` and `TRANSLATE_LANGUAGES` in `web/src/components/TranslateOptions.tsx`. Keep both lists identical and update `server/tests/test_agent.py` if it asserts the list. |
| Default language | `DEFAULT_TRANSLATE_TO` in `server/src/agent.py` and in `web/src/components/TranslateOptions.tsx`. |
| Echo default | `useState(false)` for `echoTargetLanguage` in `web/src/components/LandingPage.tsx`, and the `bool(echo_target_language)` fallback in `server/src/agent.py`. |
| Backend port | Launch with `PORT=<n>`; point `AGENT_BACKEND_URL` at it. `bun run dev:parallel` shows a second instance on 8110. |
| Agent options (RTM, metrics, transcription) | `server/src/agent.py` only. The browser must not invent agent parameters. |
| UI (pre-call card, transcript, metrics, status) | `web/src/components/Quickstart*.tsx`, `ConnectionStatusPanel.tsx`, `MicrophoneSelector.tsx`. |
| New API route | Add the FastAPI route in `server/src/server.py`, a rewrite in `web/next.config.ts`, a helper in `web/src/services/api.ts`, then extend `web/scripts/verify-api-contracts.ts`. |
## Verify
```bash
bun run verify # doctor, API contract check, web build
bun run build # Next.js production build
(cd server && venv/bin/python3 -m pip install -r requirements-dev.txt && venv/bin/python3 -m pytest tests) # backend tests (pytest, httpx)
```
With real credentials in `server/.env.local`, `bun run verify:local` adds a backend compile check, a fake-FastAPI smoke test and a proxy check. Success is every command exiting 0. In the running app, the transcript shows your speech and its translation, the agent speaks the translation, and the metrics panel shows latency values.
## Deploy
Deploy `web/` and `server/` separately. Set `AGENT_BACKEND_URL` to the public FastAPI URL, and keep the Agora App Certificate and Google API key on the server.
## Gotchas
- Only allow-listed language codes work: `es fr ja pt zh ko hi ar de pt-BR pt-PT zh-CN zh-Hans cmn`. Codes such as `es-ES`, `en-US`, `ja-JP`, `de-DE`, `ko-KR`, `es-MX` and `spa` make the vendor close the session with an opaque 1007, so the backend returns 400 for them.
- Do not add a prompt, greeting or tools. The translate model never speaks a greeting and ignores a prompt, and instructions, tools or `media_resolution` can close the session.
- `GOOGLE_API_KEY`, `AGORA_APP_ID` and `AGORA_APP_CERTIFICATE` are all required. If any is missing the backend sets no agent and the routes return 500.
- Do not set `mllm.enable` in the agent. It stops the RTM metrics messages, and the metrics panel stays empty.
- `AGENT_BACKEND_URL` must be set for the web process. Without it Next registers no rewrites and every `/api/*` call returns 404.
- Do not add `web/app/api/**/route.ts` handlers; `verify:web:api` fails on them.
- The token must be issued for a concrete non-zero UID, because RTM rejects UID 0.
- CORS is open (`*`) for local use. Restrict it before exposing the backend publicly.
## Related docs
- [README](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/README.md): setup and run steps.
- [L0 repo card](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L0_repo_card.md): identity and index of the L1 docs.
- [L1/01_setup.md](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L1/01_setup.md): setup, env and command reference.
- [L1/02_architecture.md](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L1/02_architecture.md): request flow and topology.
- [L1/05_workflows.md](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L1/05_workflows.md): common modification workflows.
- [L1/06_interfaces.md](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L1/06_interfaces.md): routes, rewrites, env and event contracts.
- [L1/07_gotchas.md](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L1/07_gotchas.md): detailed pitfalls.
- [L1/L2/managed_agent_config.md](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L1/L2/managed_agent_config.md): full agent config.
- [L1/L2/session_lifecycle.md](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L1/L2/session_lifecycle.md): RTC, RTM and session orchestration.
- [L1/L2/verification_scripts.md](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L1/L2/verification_scripts.md): each verify script.
- [L1/L2/from_scratch_bootstrap.md](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-python/blob/main/docs/ai/L1/L2/from_scratch_bootstrap.md): recreating this recipe from scratch.