Gemini 4 Live Translate for Go
Build live speech-to-speech translation with Gemini 4 Live Translate, Go and Agora.
実装ガイド
目次
ガイドの言語:言語情報なし
Build live speech translation with Agora and Gemini 4 Live Translate (Go)
Goal
Build and run a live speech-to-speech translation app. A Next.js browser client joins an Agora channel and publishes the microphone. A Go Gin backend issues Agora tokens and starts a gemini-4-live-translate agent in the same channel through the Agora Go Agent SDK. The user speaks in any language, and the agent speaks the translation in the language chosen with translate_to. The client shows the transcript, latency metrics and connection state.
Stack and prerequisites
- Go 1.23 or newer (
server/go.moddeclaresgo 1.23.0). - Node.js 22 or newer and pnpm (
packageManagerispnpm@10.23.0). - GNU Make.
- Next.js 16 and React 19 for the client (
client/package.json). - Go SDK:
github.com/AgoraIO/agora-agents-go/v2v2.16.0 (pinned inserver/go.mod). - An Agora project with an App ID and App Certificate from the Agora Console.
- A Google API key with access to the Gemini Live API.
Quick start
git clone https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go.git
cd agora-gemini-4-live-translate-go
make setupmake setup copies server/.env.example to server/.env.local, runs go mod tidy and runs pnpm install. Edit server/.env.local:
| Variable | Required | Description |
|---|---|---|
AGORA_APP_ID | yes | Agora App ID. |
AGORA_APP_CERTIFICATE | yes | Agora App Certificate. Server-side only. |
GOOGLE_API_KEY | yes | Google API key for Gemini. Server-side only. |
PORT | no | Go backend port. Defaults to 8000. |
The client needs AGENT_BACKEND_URL so Next can rewrite /api/* to the Go backend. make dev sets it to http://localhost:8000. For ad-hoc client runs, copy client/.env.local.example to client/.env.local.
Check the setup, then start both processes:
make doctor-local
make devGin listens on http://localhost:8000. Next.js picks a free port and prints it, usually http://localhost:3000. Open that URL, choose a target language, select Start Translating, allow the microphone and speak.
Architecture
server/main.go: Gin routesGET /get_config,POST /startAgent,POST /stopAgent, CORS, and.env.localloading.server/agent.go: token generation, request validation, the Gemini provider, and agent session start and stop.client/next.config.ts: rewrites/api/*toAGENT_BACKEND_URL.client/src/services/api.ts: browser calls to/api/*.client/src/components/LandingPage.tsx: bootstrap, language options and agent start.client/src/components/ConversationComponent.tsx: RTC join, RTM, transcript, metrics and microphone.client/src/components/TranslateOptions.tsx: the language list and echo toggle.
Flow:
- The browser calls
GET /api/get_config. Next proxies it to Go, which returnsapp_id, a token, the useruid, a channel name and anagent_uid. - The browser joins the Agora RTC channel, logs in to RTM, and publishes the microphone.
- The browser calls
POST /api/startAgentwith the channel, UIDs,translateToandechoTargetLanguage. - Go validates the request, builds the agent with the Go SDK and starts a session. The SDK routes Gemini Live Translate to the right Agora endpoint.
- The agent listens in the channel and publishes the translated speech. Transcripts, agent state, metrics and errors reach the client over RTM.
- On hangup the browser calls
POST /api/stopAgentwith theagentId. Go stops the session.
How the agent is configured
buildMllm in server/agent.go builds the only provider:
return vendors.NewGeminiLive(vendors.GeminiLiveOptions{
APIKey: apiKey,
Model: translateModel, // gemini-4-live-translate
TranslateTo: selected.TranslateTo,
EchoTargetLanguage: echo,
TranscribeAgent: boolPtr(true),
TranscribeUser: boolPtr(true),
})start attaches it to an agent with RTM, metrics and error messages enabled, then starts a session:
agent := agentkit.NewAgent(s.sessionClient,
agentkit.WithAdvancedFeatures(&agentkit.AdvancedFeatures{EnableRtm: &enableRTM}),
agentkit.WithParameters(&agentkit.SessionParams{
DataChannel: &dataChannel, // "rtm"
EnableErrorMessage: &enableErrorMessage,
EnableMetrics: &enableMetrics,
}),
).WithMllm(buildMllm(selected, s.googleAPIKey))
session := agent.CreateSession(agentkit.CreateSessionOptions{
Channel: channelName,
AgentUID: strconv.Itoa(agentUID),
RemoteUIDs: []string{strconv.Itoa(userUID)},
ExpiresIn: expiresIn,
})
agentID, err := session.Start(ctx)- Model: always
gemini-4-live-translate. Do not set the URL or headers; the SDK does it from the model name. translate_to: the language the agent speaks. Defaultes.echo_target_language: whentrue, speech that is already in the target language is spoken back too. Defaultfalse.transcribe_userandtranscribe_agentfeed the transcript panel: the user's speech is the source and the agent's speech is the translation.- No system prompt, greeting or thinking level is sent.
API contract
The browser calls these through Next at /api/*. Go serves them without the /api prefix.
| Endpoint | Request | Response |
|---|---|---|
GET /api/get_config?channel=&uid= | Both query values are optional. A missing channel gets a generated name; a uid of 0 or less gets a random UID. | { code, msg, data: { app_id, token, uid, channel_name, agent_uid } } |
POST /api/startAgent | { channelName, rtcUid, userUid, model?, translateTo?, echoTargetLanguage? } | { code, msg, data: { agent_id, channel_name, status } } |
POST /api/stopAgent | { agentId } | { code, msg } |
Validation errors return 400 with { "detail": "..." }: empty channelName, rtcUid or userUid at 0 or less, a model other than gemini-4-live-translate, any thinkingLevel, and a translateTo outside the allow-list. Other failures return 500.
Customize
| Change | Files |
|---|---|
| Allowed language codes | translateToAllowList in server/agent.go and TRANSLATE_TO_OPTIONS in client/src/components/TranslateOptions.tsx. Keep both lists identical. |
| Default target language | defaultTranslateTo in server/agent.go and DEFAULT_TRANSLATE_TO in TranslateOptions.tsx. |
| Echo default | The false fallback in buildMllm in server/agent.go and the initial echo state in LandingPage.tsx. |
| Backend port | Set PORT in server/.env.local, and set AGENT_BACKEND_URL for the client to match. make dev and make frontend hardcode http://localhost:8000, so edit the Makefile too. |
| Request or response fields | server/main.go, client/src/services/api.ts and client/scripts/verify-api-contracts.ts. Change all three together. |
| UI | client/src/components/, client/src/lib/conversation.ts, client/src/types/conversation.ts. |
Update server/main_test.go and server/wire_test.go when you change validation or the agent request body.
Verify
make verify # doctor, API contract checks, Next build
make test # Go backend tests (go test ./...)
make build # Go binary at server/bin/agora-gemini-4-live-translate-go and the Next build
make verify-local # also runs doctor-local, the Go-backed smoke test and the proxy checkmake verify needs pnpm install done and no credentials. make doctor-local and make verify-local need Go and a server/.env.local with non-empty AGORA_APP_ID and AGORA_APP_CERTIFICATE.
Success means each command exits 0. For a live check, run make dev, open the client and speak. The agent should answer in the target language, and the transcript shows your speech and the translation.
Gotchas
- Only allow-listed
translate_tocodes work:es,fr,ja,pt,zh,ko,hi,ar,de,pt-BR,pt-PT,zh-CN,zh-Hans,cmn. Codes such ases-ES,en-USorspamake the vendor close the session mid-stream with an opaque error, so the server rejects them with 400 first. - There is no greeting, system prompt or thinking level. The model ignores a prompt, never speaks a greeting, and a request with
thinkingLevelreturns 400. The agent waits for the user to speak. - Do not send instructions, tools or
media_resolution; they can close a translating session. GOOGLE_API_KEYis required. The server logs a warning at startup when a variable is missing, and every endpoint then returns 500 "Service not properly configured".make doctor-localchecks onlyAGORA_APP_IDandAGORA_APP_CERTIFICATE. ConfirmGOOGLE_API_KEYis set inserver/.env.localyourself, or runpnpm run doctor:local, which does check it.- Do not set
mllm.enable. With it the agent sent no RTM metrics and the latency panel stayed empty. AGENT_BACKEND_URLmust be set for the client. Without it every/api/*call returns 404.- Do not add
client/app/api/**/route.ts. Route handlers shadow the rewrites, andmake verifyfails. server/.env.localis read from the working directory. Run the server fromserver/, asmake backenddoes.- Keep
AGORA_APP_CERTIFICATEandGOOGLE_API_KEYout ofclient/andNEXT_PUBLIC_*variables. - CORS allows all origins. Restrict it before exposing the Go service publicly.
Related docs
- L0 repo card
- Setup and commands
- Architecture
- Code map
- Conventions
- Common workflows
- Interfaces and events
- Gotchas
- Security
- Managed agent config
- Session lifecycle
- Verification scripts
- From-scratch bootstrap
実装ガイドのメタデータ
| 項目 | 値 |
|---|---|
recipe_version | 1.0.0 |
recipe_status | stable |
recipe_slug | agora-gemini-4-live-translate-go |
recipe_name | Agora Gemini 4 Live Translate (Go) |
extension_points |
|
invariants |
|
stable_contracts |
|
---
recipe_version: 1.0.0
recipe_status: stable
recipe_slug: agora-gemini-4-live-translate-go
recipe_name: Agora Gemini 4 Live Translate (Go)
extension_points:
- id: agent.translate
name: gemini-4-live-translate session (translate_to, echo_target_language)
- id: api.routes
name: Go backend routes exposed through Next rewrites
- id: ui.conversation
name: pre-call, conversation, transcript, metrics, and microphone UI
- id: verification.contracts
name: API, proxy, local Go, and backend verification harnesses
invariants:
- id: api.browser-paths
summary: browser code calls /api/* and never the Go backend URL directly
- id: routing.rewrite-only
summary: Next rewrites proxy /api/* to Go; no client/app/api route handlers exist
- id: secrets.server-only
summary: AGORA_APP_CERTIFICATE and GOOGLE_API_KEY stay on the Go server
- id: uid.concrete-rtm
summary: RTM login and renewal use concrete non-zero UIDs
stable_contracts:
- id: env.required
summary: AGORA_APP_ID, AGORA_APP_CERTIFICATE, and GOOGLE_API_KEY are required by the Go server
- id: api.config
summary: GET /api/get_config returns app_id, token, uid, channel_name, and agent_uid
- id: api.lifecycle
summary: POST /api/startAgent starts a session; POST /api/stopAgent stops it by agentId
- id: verification.make
summary: root Make targets are the canonical setup, dev, build, test, and verification interface
---
# Build live speech translation with Agora and Gemini 4 Live Translate (Go)
## Goal
Build and run a live speech-to-speech translation app. A Next.js browser client joins an Agora channel and publishes the microphone. A Go Gin backend issues Agora tokens and starts a `gemini-4-live-translate` agent in the same channel through the Agora Go Agent SDK. The user speaks in any language, and the agent speaks the translation in the language chosen with `translate_to`. The client shows the transcript, latency metrics and connection state.
## Stack and prerequisites
- Go 1.23 or newer (`server/go.mod` declares `go 1.23.0`).
- Node.js 22 or newer and pnpm (`packageManager` is `pnpm@10.23.0`).
- GNU Make.
- Next.js 16 and React 19 for the client (`client/package.json`).
- Go SDK: `github.com/AgoraIO/agora-agents-go/v2` v2.16.0 (pinned in `server/go.mod`).
- An Agora project with an App ID and App Certificate from the [Agora Console](https://console.agora.io/).
- A Google API key with access to the Gemini Live API.
## Quick start
```bash
git clone https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go.git
cd agora-gemini-4-live-translate-go
make setup
```
`make setup` copies `server/.env.example` to `server/.env.local`, runs `go mod tidy` and runs `pnpm install`. Edit `server/.env.local`:
| Variable | Required | Description |
| -------- | -------- | ----------- |
| `AGORA_APP_ID` | yes | Agora App ID. |
| `AGORA_APP_CERTIFICATE` | yes | Agora App Certificate. Server-side only. |
| `GOOGLE_API_KEY` | yes | Google API key for Gemini. Server-side only. |
| `PORT` | no | Go backend port. Defaults to `8000`. |
The client needs `AGENT_BACKEND_URL` so Next can rewrite `/api/*` to the Go backend. `make dev` sets it to `http://localhost:8000`. For ad-hoc client runs, copy `client/.env.local.example` to `client/.env.local`.
Check the setup, then start both processes:
```bash
make doctor-local
make dev
```
Gin listens on `http://localhost:8000`. Next.js picks a free port and prints it, usually `http://localhost:3000`. Open that URL, choose a target language, select Start Translating, allow the microphone and speak.
## Architecture
- `server/main.go`: Gin routes `GET /get_config`, `POST /startAgent`, `POST /stopAgent`, CORS, and `.env.local` loading.
- [`server/agent.go`](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/server/agent.go): token generation, request validation, the Gemini provider, and agent session start and stop.
- [`client/next.config.ts`](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/client/next.config.ts): rewrites `/api/*` to `AGENT_BACKEND_URL`.
- [`client/src/services/api.ts`](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/client/src/services/api.ts): browser calls to `/api/*`.
- [`client/src/components/LandingPage.tsx`](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/client/src/components/LandingPage.tsx): bootstrap, language options and agent start.
- [`client/src/components/ConversationComponent.tsx`](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/client/src/components/ConversationComponent.tsx): RTC join, RTM, transcript, metrics and microphone.
- [`client/src/components/TranslateOptions.tsx`](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/client/src/components/TranslateOptions.tsx): the language list and echo toggle.
Flow:
1. The browser calls `GET /api/get_config`. Next proxies it to Go, which returns `app_id`, a token, the user `uid`, a channel name and an `agent_uid`.
2. The browser joins the Agora 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. Go validates the request, builds the agent with the Go SDK and starts a session. The SDK routes Gemini Live Translate to the right Agora endpoint.
5. The agent listens in the channel and publishes the translated speech. Transcripts, agent state, metrics and errors reach the client over RTM.
6. On hangup the browser calls `POST /api/stopAgent` with the `agentId`. Go stops the session.
## How the agent is configured
`buildMllm` in [`server/agent.go`](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/server/agent.go) builds the only provider:
```go
return vendors.NewGeminiLive(vendors.GeminiLiveOptions{
APIKey: apiKey,
Model: translateModel, // gemini-4-live-translate
TranslateTo: selected.TranslateTo,
EchoTargetLanguage: echo,
TranscribeAgent: boolPtr(true),
TranscribeUser: boolPtr(true),
})
```
`start` attaches it to an agent with RTM, metrics and error messages enabled, then starts a session:
```go
agent := agentkit.NewAgent(s.sessionClient,
agentkit.WithAdvancedFeatures(&agentkit.AdvancedFeatures{EnableRtm: &enableRTM}),
agentkit.WithParameters(&agentkit.SessionParams{
DataChannel: &dataChannel, // "rtm"
EnableErrorMessage: &enableErrorMessage,
EnableMetrics: &enableMetrics,
}),
).WithMllm(buildMllm(selected, s.googleAPIKey))
session := agent.CreateSession(agentkit.CreateSessionOptions{
Channel: channelName,
AgentUID: strconv.Itoa(agentUID),
RemoteUIDs: []string{strconv.Itoa(userUID)},
ExpiresIn: expiresIn,
})
agentID, err := session.Start(ctx)
```
- Model: always `gemini-4-live-translate`. Do not set the URL or headers; the SDK does it from the model name.
- `translate_to`: the language the agent speaks. Default `es`.
- `echo_target_language`: when `true`, speech that is already in the target language is spoken back too. Default `false`.
- `transcribe_user` and `transcribe_agent` feed the transcript panel: the user's speech is the source and the agent's speech is the translation.
- No system prompt, greeting or thinking level is sent.
### API contract
The browser calls these through Next at `/api/*`. Go serves them without the `/api` prefix.
| Endpoint | Request | Response |
| -------- | ------- | -------- |
| `GET /api/get_config?channel=&uid=` | Both query values are optional. A missing channel gets a generated name; a `uid` of 0 or less gets a random UID. | `{ code, msg, data: { app_id, token, uid, channel_name, agent_uid } }` |
| `POST /api/startAgent` | `{ channelName, rtcUid, userUid, model?, translateTo?, echoTargetLanguage? }` | `{ code, msg, data: { agent_id, channel_name, status } }` |
| `POST /api/stopAgent` | `{ agentId }` | `{ code, msg }` |
Validation errors return 400 with `{ "detail": "..." }`: empty `channelName`, `rtcUid` or `userUid` at 0 or less, a `model` other than `gemini-4-live-translate`, any `thinkingLevel`, and a `translateTo` outside the allow-list. Other failures return 500.
## Customize
| Change | Files |
| ------ | ----- |
| Allowed language codes | `translateToAllowList` in `server/agent.go` and `TRANSLATE_TO_OPTIONS` in `client/src/components/TranslateOptions.tsx`. Keep both lists identical. |
| Default target language | `defaultTranslateTo` in `server/agent.go` and `DEFAULT_TRANSLATE_TO` in `TranslateOptions.tsx`. |
| Echo default | The `false` fallback in `buildMllm` in `server/agent.go` and the initial echo state in `LandingPage.tsx`. |
| Backend port | Set `PORT` in `server/.env.local`, and set `AGENT_BACKEND_URL` for the client to match. `make dev` and `make frontend` hardcode `http://localhost:8000`, so edit the `Makefile` too. |
| Request or response fields | `server/main.go`, `client/src/services/api.ts` and `client/scripts/verify-api-contracts.ts`. Change all three together. |
| UI | `client/src/components/`, `client/src/lib/conversation.ts`, `client/src/types/conversation.ts`. |
Update `server/main_test.go` and `server/wire_test.go` when you change validation or the agent request body.
## Verify
```bash
make verify # doctor, API contract checks, Next build
make test # Go backend tests (go test ./...)
make build # Go binary at server/bin/agora-gemini-4-live-translate-go and the Next build
make verify-local # also runs doctor-local, the Go-backed smoke test and the proxy check
```
`make verify` needs `pnpm install` done and no credentials. `make doctor-local` and `make verify-local` need Go and a `server/.env.local` with non-empty `AGORA_APP_ID` and `AGORA_APP_CERTIFICATE`.
Success means each command exits 0. For a live check, run `make dev`, open the client and speak. The agent should answer in the target language, and the transcript shows your speech and the translation.
## Gotchas
- Only allow-listed `translate_to` 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` or `spa` make the vendor close the session mid-stream with an opaque error, so the server rejects them with 400 first.
- There is no greeting, system prompt or thinking level. The model ignores a prompt, never speaks a greeting, and a request with `thinkingLevel` returns 400. The agent waits for the user to speak.
- Do not send instructions, tools or `media_resolution`; they can close a translating session.
- `GOOGLE_API_KEY` is required. The server logs a warning at startup when a variable is missing, and every endpoint then returns 500 "Service not properly configured".
- `make doctor-local` checks only `AGORA_APP_ID` and `AGORA_APP_CERTIFICATE`. Confirm `GOOGLE_API_KEY` is set in `server/.env.local` yourself, or run `pnpm run doctor:local`, which does check it.
- Do not set `mllm.enable`. With it the agent sent no RTM metrics and the latency panel stayed empty.
- `AGENT_BACKEND_URL` must be set for the client. Without it every `/api/*` call returns 404.
- Do not add `client/app/api/**/route.ts`. Route handlers shadow the rewrites, and `make verify` fails.
- `server/.env.local` is read from the working directory. Run the server from `server/`, as `make backend` does.
- Keep `AGORA_APP_CERTIFICATE` and `GOOGLE_API_KEY` out of `client/` and `NEXT_PUBLIC_*` variables.
- CORS allows all origins. Restrict it before exposing the Go service publicly.
## Related docs
- [L0 repo card](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L0_repo_card.md)
- [Setup and commands](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/01_setup.md)
- [Architecture](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/02_architecture.md)
- [Code map](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/03_code_map.md)
- [Conventions](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/04_conventions.md)
- [Common workflows](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/05_workflows.md)
- [Interfaces and events](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/06_interfaces.md)
- [Gotchas](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/07_gotchas.md)
- [Security](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/08_security.md)
- [Managed agent config](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/L2/managed_agent_config.md)
- [Session lifecycle](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/L2/session_lifecycle.md)
- [Verification scripts](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/L2/verification_scripts.md)
- [From-scratch bootstrap](https://github.com/AgoraIO-Community/agora-gemini-4-live-translate-go/blob/main/docs/ai/L1/L2/from_scratch_bootstrap.md)