返回内容列表

Gemini 4 Live Translate for Python

Build live speech-to-speech translation with Gemini 4 Live Translate, Python and Agora.

Python / TypeScript进阶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.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:

VariableRequiredPurpose
AGORA_APP_IDyesAgora project App ID.
AGORA_APP_CERTIFICATEyesAgora App Certificate, used to sign tokens. Server-only.
GOOGLE_API_KEYyesGemini Live API key. Server-only; the backend refuses to start without it.
PORTnoFastAPI 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):

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": ... }):

EndpointRequestResponse
GET /api/get_configQuery 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

ChangeEdit
Supported target languagesTRANSLATE_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 languageDEFAULT_TRANSLATE_TO in server/src/agent.py and in web/src/components/TranslateOptions.tsx.
Echo defaultuseState(false) for echoTargetLanguage in web/src/components/LandingPage.tsx, and the bool(echo_target_language) fallback in server/src/agent.py.
Backend portLaunch 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 routeAdd 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.
Recipe 元数据
Recipe 元数据
字段值
recipe_version0.1.0
recipe_slugagora-gemini-4-live-translate-python
recipe_nameGemini 4 Live Translate Speech Translation for Python
recipe_statusstable
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 }.