# Gemini 4 Live Translate for Next.js

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

Create a browser app with a Next.js server that translates speech live with the gemini-4-live-translate model: pick a target language, speak in any language, and hear the translation, with an optional echo of input already in the target language, over Agora RTC and RTM.

- Author: Agora
- Updated: 2026-12-02T23:50:32.440Z
- Guide language: unspecified
- Guide status: available
- Difficulty: Intermediate
- Categories: voice-ai
- Platforms: TypeScript
- Use cases: Quickstart, Voice AI, Translation, Multimodal
- Capabilities: Conversational AI, Voice Agent, Speech Translation, Gemini, Gemini Live, Multimodal, Next.js
- [Recipe page](https://recipes.agora.io/recipes/agora-gemini-4-live-translate-nextjs)
- [Implementation repository](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs)
- [Source recipe](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/RECIPE.md)
- [Raw source Markdown](https://raw.githubusercontent.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/main/docs/ai/RECIPE.md)
- [All recipes](https://recipes.agora.io/llms.txt)

## Implementation guide

---
recipe_version: 0.1.0
recipe_status: stable
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
---

# 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.

| Item | Value |
| --- | --- |
| Slug | `agora-gemini-4-live-translate-nextjs` |
| Repository | https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs |
| Agent SDK | `agora-agents` 2.16.1 (npm, pinned) |
| Model | `gemini-4-live-translate` |
| Data channel | RTM (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`:

| Variable | Scope | Value |
| --- | --- | --- |
| `NEXT_PUBLIC_AGORA_APP_ID` | client and server | Agora App ID |
| `NEXT_AGORA_APP_CERTIFICATE` | server only | Agora App Certificate |
| `GOOGLE_API_KEY` | server only | Google 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:

- [app/api/generate-agora-token/route.ts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/app/api/generate-agora-token/route.ts): RTC and RTM token (`RtcTokenBuilder.buildTokenWithRtm`, 1 hour).
- [app/api/invite-agent/route.ts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/app/api/invite-agent/route.ts): validation and agent construction.
- [app/api/stop-conversation/route.ts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/app/api/stop-conversation/route.ts): stops the agent; an agent that is already stopping or gone counts as success.
- [lib/gemini-translate.ts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/lib/gemini-translate.ts): model ID, language allow-list, default language and labels. Client-safe, so it must not import `agora-agents`.
- [lib/agora.ts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/lib/agora.ts): `DEFAULT_AGENT_UID` (123456), shared by the invite route and the browser.
- [lib/conversation.ts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/lib/conversation.ts): transcript normalization and the `uid="0"` remap.
- [types/conversation.ts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/types/conversation.ts): request and response types.
- [components/TranslateOptions.tsx](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/components/TranslateOptions.tsx): language select and echo toggle.
- [components/QuickstartTranscriptPanel.tsx](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/components/QuickstartTranscriptPanel.tsx) and [components/QuickstartPipelineMetrics.tsx](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/components/QuickstartPipelineMetrics.tsx): transcript and latency UI.

## 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.

## Related docs

- [L0 repo card](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L0_repo_card.md)
- [L1 setup](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/01_setup.md)
- [L1 architecture](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/02_architecture.md)
- [L1 code map](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/03_code_map.md)
- [L1 conventions](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/04_conventions.md)
- [L1 workflows](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/05_workflows.md)
- [L1 interfaces](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/06_interfaces.md)
- [L1 gotchas](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/07_gotchas.md)
- [L1 security](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/08_security.md)
- [Rebuild from scratch](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/L2/from_scratch_bootstrap.md)
- [Invite agent config](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/L2/invite_agent_config.md)
- [Token model](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/L2/token_model.md)
- [Transcript pipeline](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/blob/main/docs/ai/L1/L2/transcript_pipeline.md)


## Recipe prompt

You are implementing the "Gemini 4 Live Translate for Next.js" recipe in this project.

Read the recipe markdown first:
https://raw.githubusercontent.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs/main/docs/ai/RECIPE.md

Use the source repository for cross-reference:
https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-nextjs

Build this recipe into the user's app using the markdown as the implementation guide. Inspect related source files through the repository links when the recipe points to them. Ask before installing new dependencies.
