返回内容列表

Gemini 4 Live Translate for Next.js

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

TypeScript进阶Agora

实践教程

本教程目录

文档语言:作者未标注语言

Build live speech translation with Gemini Live Translate and Next.js

Goal

Build or run a Next.js app that translates speech live. The browser joins an Agora channel and publishes microphone audio. A server route starts an Agora Conversational AI agent backed by the Gemini Live Translate model (gemini-4-live-translate). The agent speaks the translation into the channel, and the page shows a Source transcript (what the user said) next to a Translation transcript (what the agent said), plus latency chips and connection status. The user picks one target language before the call and can turn on echo of speech already in that language.

ItemValue
Slugagora-gemini-4-live-translate-nextjs
Repositoryhttps://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs
Agent SDKagora-agents 2.16.1 (npm, pinned)
Modelgemini-4-live-translate
Data channelRTM (transcripts, state, metrics, errors)

Prerequisites

  • Node.js 22 or newer (.nvmrc says 24) and pnpm 10 or newer. The scripts refuse to run under npm or yarn.
  • Next.js 16 (App Router), React 19, TypeScript 5.
  • Browser SDKs: agora-rtc-sdk-ng, agora-rtc-react, agora-rtm, agora-agent-client-toolkit 2.10.0, agora-agent-uikit 1.1.0.
  • Server packages: agora-agents 2.16.1 and agora-token.
  • An Agora project with an App ID and App Certificate (Agora Console).
  • A Google API key with Gemini Live access.

Quick start

bash
git clone https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs.git
cd agora-gemini-4-live-translate-nextjs
pnpm install
cp .env.local.example .env.local

Set these in .env.local:

VariableScopeValue
NEXT_PUBLIC_AGORA_APP_IDclient and serverAgora App ID
NEXT_AGORA_APP_CERTIFICATEserver onlyAgora App Certificate
GOOGLE_API_KEYserver onlyGoogle API key with Gemini Live access

Run it:

bash
pnpm run doctor
pnpm dev

pnpm dev runs next dev --webpack. Open the Local URL it prints (normally http://localhost:3000), allow microphone access, pick a target language, click Start Translating, and speak. For a production-style run, use pnpm build then pnpm start; pnpm start serves the standalone build on PORT (default 3000) and moves to the next free port if that one is busy.

Architecture

Components:

  • Browser: components/LandingPage.tsx fetches the token, logs in to RTM and calls the invite and stop routes. components/ConversationComponent.tsx joins RTC, publishes the microphone and subscribes to transcript, state, metrics and error events through AgoraVoiceAI.
  • Next.js server routes under app/api/: token, invite-agent, stop-conversation.
  • Agora: RTC carries audio, RTM carries events, and Conversational AI Engine runs the agent.
  • Gemini Live Translate: the model the agent streams audio to.

Flow:

  1. The browser calls GET /api/generate-agora-token and gets { token, uid, channel }. The token covers RTC and RTM.
  2. The browser logs in to RTM, joins the RTC channel and publishes the microphone.
  3. The browser calls POST /api/invite-agent with the channel, its UID and the language options.
  4. The route validates the request and starts a GeminiLive agent with the agora-agents SDK. The agent only listens to the requesting UID.
  5. The agent streams the user's audio to Gemini and plays the translated speech into the channel.
  6. Transcript, state, metrics and error events arrive in the browser over RTM and render in the transcript panel and metric chips.
  7. On end, the browser calls POST /api/stop-conversation with the agent_id.

Key files:

How the agent is configured

app/api/invite-agent/route.ts builds the agent from the SDK. The model is GeminiLiveModels.Live4Translate; the SDK picks the endpoint and request headers from the model name, so the route sets no URL, voice or header.

typescript
const MODEL = GeminiLiveModels.Live4Translate;

const agent = new Agent({
  client,
  parameters: {
    data_channel: 'rtm',
    enable_error_message: true, // emits AGENT_ERROR payloads
    enable_metrics: true, // emits AGENT_METRICS latency payloads
  },
})
  .withAdvancedFeatures({ enable_rtm: true })
  .withMllm(
    new GeminiLive({
      apiKey: requireEnv('GOOGLE_API_KEY'),
      model: MODEL,
      translateTo: translate_to ?? DEFAULT_TRANSLATE_TO,
      echoTargetLanguage: echo_target_language ?? false,
      transcribeAgent: true,
      transcribeUser: true,
    }),
  );

const session = agent.createSession({
  channel: channel_name,
  agentUid,
  remoteUids: [requester_id],
});
const agentId = await session.start();
  • translateTo is the target language. Default es, restricted to the allow-list in lib/gemini-translate.ts.
  • echoTargetLanguage makes the agent speak back input that is already in the target language. Default false.
  • transcribeAgent and transcribeUser are the only source of transcript events for the browser.
  • The client is created with Area.US. Change it to Area.EU or Area.AP for other regions.
  • There is no system prompt, greeting or thinking level.

Server API contract:

  • GET /api/generate-agora-token?uid=<int>&channel=<name> returns { token, uid, channel }. Both query parameters are optional; a random UID and channel name are generated when they are missing.
  • POST /api/invite-agent takes { requester_id, channel_name, translate_to?, echo_target_language?, model? } and returns { agent_id, create_ts, state: "RUNNING" }.
    • requester_id and channel_name are required (400 if missing).
    • translate_to must be on the allow-list (400 otherwise).
    • echo_target_language must be a boolean (400 otherwise).
    • model, if sent, must be gemini-4-live-translate (400 otherwise).
    • Any thinking_level returns 400.
    • Missing server env vars or SDK errors return 500 with an error message.
  • POST /api/stop-conversation takes { agent_id } and returns { success: true }, or { success: true, state: "already-stopping" } when the agent is already shutting down or gone. A missing agent_id returns 400.

Customize

  • Target languages: edit TRANSLATE_TO_CODES and TRANSLATE_TO_LABELS in lib/gemini-translate.ts. The UI select and the route validation both read this list. Only add codes the vendor accepts.
  • Default language: edit DEFAULT_TRANSLATE_TO in lib/gemini-translate.ts; components/LandingPage.tsx uses it as the initial selection.
  • Echo default: change echo_target_language ?? false in app/api/invite-agent/route.ts, and the initial echoTargetLanguage state in components/LandingPage.tsx so the UI matches.
  • Region: change Area.US in app/api/invite-agent/route.ts and app/api/stop-conversation/route.ts together.
  • Port: pnpm dev takes Next.js defaults (for example pnpm dev -p 4000). pnpm start reads PORT.
  • UI: edit components/QuickstartPreCallCard.tsx, components/TranslateOptions.tsx, components/QuickstartTranscriptPanel.tsx, components/QuickstartPipelineMetrics.tsx and components/QuickstartConversationLayout.tsx.
  • Anything in the agent request body: edit app/api/invite-agent/route.ts, then update the exact key-set assertions in scripts/verify-api-contracts.ts.

After any change to routes or contracts, update the matching files in docs/ai/ and run the checks below.

Verify

bash
pnpm run lint
pnpm run typecheck
pnpm run verify:api
pnpm run build

pnpm run verify runs doctor, lint, typecheck, verify:api and build in order. doctor needs all three values set in .env.local. verify:api mocks the session start and makes no calls to Agora or Google. It checks request validation, the allow-list, the translate fields, the join URL and agora-feature header on both routes, and the SDK default Gemini URL and voice.

Success: every command exits 0. In the running app, the transcript shows a Source turn when you speak, a Translation turn follows, and you hear the translation in the target language.

Optional live check: node --import tsx scripts/live-gemini-smoke.ts starts and stops real translate agents using your credentials. It incurs usage.

Gotchas

  • Only codes in TRANSLATE_TO_CODES work (see lib/gemini-translate.ts). Codes such as es-ES, en-US or es-MX start fine, then the vendor closes the session mid-stream with an opaque 1007. The route rejects them up front.
  • Do not add a prompt, greeting, tools or media_resolution. The model ignores a prompt (it translates it) and speaks no greeting. A translating session can close with 1007 on instructions, tools or media_resolution. The agent stays silent until the user speaks.
  • There is no thinking level, so thinking_level returns 400.
  • GOOGLE_API_KEY is required. Without it the invite route returns 500. Without the Agora variables, all three routes return 500.
  • Metrics only arrive because the request enables MLLM through advanced_features.enable_mllm (set by the SDK) and does not send mllm.enable. Do not add mllm.enable, or the latency chips stay empty. The chips show the latest mllm and llm metrics.
  • Keep RtcTokenBuilder.buildTokenWithRtm. An RTC-only token breaks RTM login and transcripts.
  • Keep DEFAULT_AGENT_UID the same in the invite route and the browser.
  • Keep the isReady guard in components/ConversationComponent.tsx. Removing it double-initializes join and microphone under React StrictMode. Do not call client.leave() or close the microphone track manually; the hooks own that cleanup.
  • Keep the remap of toolkit uid="0" to the local UID and keep INTERRUPTED turns in the message list. Otherwise user turns render as agent turns and the transcript may not open on the first interrupted turn.
  • Stop must go through the stop route's SDK helper. The client-level stopAgent does not reach these agents, so do not hand-roll the host or agora-feature header. Use createPreviewRoute(client, [PreviewFeatures.Gemini]).agents.stop.
  • Keep TRANSLATE_MODEL in lib/gemini-translate.ts equal to GeminiLiveModels.Live4Translate; verify:api asserts this.
Recipe 元数据
Recipe 元数据
字段值
recipe_version0.1.0
recipe_statusstable
extension_points
  • api.routes
  • pipeline.providers
  • ui.conversation
invariants
  • baseline.sample-derived
  • tokens.rtc-rtm
  • lifecycle.strict-mode
  • transcript.uid-remap
  • translate.allow-list
stable_contracts
  • env.required
  • api.token
  • api.invite-agent
  • api.stop-conversation