Volver a Recipes

Gemini 4 Live Translate for Go

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

Go / TypeScriptIntermedioAgora

Guía de implementación

En esta guía

Idioma del documento: Idioma sin especificar

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.
  • 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:

VariableRequiredDescription
AGORA_APP_IDyesAgora App ID.
AGORA_APP_CERTIFICATEyesAgora App Certificate. Server-side only.
GOOGLE_API_KEYyesGoogle API key for Gemini. Server-side only.
PORTnoGo 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

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

EndpointRequestResponse
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

ChangeFiles
Allowed language codestranslateToAllowList in server/agent.go and TRANSLATE_TO_OPTIONS in client/src/components/TranslateOptions.tsx. Keep both lists identical.
Default target languagedefaultTranslateTo in server/agent.go and DEFAULT_TRANSLATE_TO in TranslateOptions.tsx.
Echo defaultThe false fallback in buildMllm in server/agent.go and the initial echo state in LandingPage.tsx.
Backend portSet 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 fieldsserver/main.go, client/src/services/api.ts and client/scripts/verify-api-contracts.ts. Change all three together.
UIclient/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.
Metadatos de Recipe
Metadatos de Recipe
CampoValor
recipe_version1.0.0
recipe_statusstable
recipe_slugagora-gemini-4-live-translate-go
recipe_nameAgora 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