---
title: "Gemini TTS, Transcribe and agent in Node.js | Micdrop"
description: "Run a voice agent on Google Gemini from your Node server: Gemini models as the agent, Gemini Transcribe and Gemini TTS, or Gemini Live for the whole call."
url: "https://micdrop.dev/docs/ai-integration/provided-integrations/gemini"
---

# Gemini TTS, Transcribe and agent in Node.js

# Gemini

Google Gemini implementation for [@micdrop/server](/docs/server).

This package provides an agent, a speech-to-text and a text-to-speech running on the Gemini API. Each one can be combined with any other provider. `GeminiLive` goes further: it is a [realtime model](/docs/server/realtime) that hears the user and answers with its own voice, in place of the three. `GeminiClassifier` reads each turn of the user and answers typed questions about it, next to any of them.

## Installation

```bash
npm install @micdrop/gemini
```

## Gemini Agent

`GeminiAgent` answers with Gemini models through the Interactions API. It sends the whole conversation on every turn, so the history stays on your server.

### Usage with MicdropServer

```typescript
import { GeminiAgent } from '@micdrop/gemini'
import { MicdropServer } from '@micdrop/server'

const agent = new GeminiAgent({
  apiKey: process.env.GEMINI_API_KEY || '',
  model: 'gemini-3.8-flash', // Default model
  thinkingLevel: 'low', // Optional, the lower the sooner the first word
  systemPrompt: 'You are a helpful assistant',

  // Advanced features (optional)
  autoEndCall: true, // Automatically end call when user requests
  autoSemanticTurn: true, // Handle incomplete sentences
  autoIgnoreUserNoise: true, // Filter out meaningless sounds
})

new MicdropServer(socket, {
  agent,
  // ... other options
})
```

### Usage without MicdropServer

```typescript
import { GeminiAgent } from '@micdrop/gemini'

const agent = new GeminiAgent({
  apiKey: process.env.GEMINI_API_KEY || '',
  systemPrompt: 'You are a helpful assistant',
})

agent.on('Message', (message) => console.log('Message:', message))

agent.addUserMessage('Hello, what can you do?')

// The answer is a text stream, written as the model generates it
agent.answer().on('data', (chunk) => process.stdout.write(chunk))
```

### Events

Event

Payload

Description

`Message`

`MicdropConversationItem`

A message, a tool call or a tool result was added to the conversation.

`ToolCall`

`MicdropToolCall`

A tool declared with `emitOutput` ran, with its parameters and output.

`CancelLastUserMessage`

none

The last user message was dropped because it carried no intent.

`SkipAnswer`

none

The agent stays silent and waits for the user to finish their sentence.

`EndCall`

none

The agent decided that the call is over.

`Failed`

none

The agent gave up generating an answer after its retries.

See the [Agent interface](/docs/ai-integration/custom-integrations/custom-agent) for the full contract.

### Options

Option

Type

Default

Description

`apiKey`

`string`

Required\*

Your Gemini API key (required if `genai` not provided)

`genai`

`GoogleGenAI`

Optional

Client of `@google/genai` (alternative to `apiKey`)

`model`

`string`

`'gemini-3.8-flash'`

Model to use (`gemini-3.8-flash`, `gemini-3.5-flash-lite`…)

`thinkingLevel`

`string`

Model default

How long the model thinks (`low`, `medium`, `high`)

`settings`

`Record<string, unknown>`

`undefined`

Other generation settings, such as `temperature`

`maxRetry`

`number`

`3`

Attempts after a failed request

`retryDelay`

`number`

`1000`

Delay between two attempts, in milliseconds

`maxSteps`

`number`

`5`

Requests in a row when the model keeps calling tools

A failed request is sent again while none of its answer has been spoken. Once part of it has been streamed, the agent keeps what was said in the conversation and stops there, so the user never hears the same words twice. Cancelling the answer also stops the attempts waiting for their delay.

For a voice call, the delay before the first word matters most. `gemini-3.5-flash-lite` answers in about a second, while `gemini-3.8-flash`, more capable, takes several seconds even with `thinkingLevel: 'low'`.

## Gemini STT (Speech-to-Text)

`GeminiSTT` streams the voice of the user to Gemini Transcribe over the Live API, and emits the transcript of each utterance a fraction of a second after it ends.

### Usage with MicdropServer

```typescript
import { GeminiSTT } from '@micdrop/gemini'
import { MicdropServer } from '@micdrop/server'

const stt = new GeminiSTT({
  apiKey: process.env.GEMINI_API_KEY || '',
  language: 'en-US', // Optional, detected when left out
  vocabulary: ['Micdrop'], // Optional, words to recognize
})

new MicdropServer(socket, {
  stt,
  // ... other options
})
```

### Usage without MicdropServer

```typescript
import { GeminiSTT } from '@micdrop/gemini'
import { createReadStream } from 'fs'

const stt = new GeminiSTT({ apiKey: process.env.GEMINI_API_KEY || '' })

stt.on('Transcript', (transcript) => console.log('Transcript:', transcript))

// Audio is raw PCM, 16 bits, 16 kHz, mono
stt.transcribe(createReadStream('speech.pcm'))
```

### Events

Event

Payload

Description

`Transcript`

`string`

The transcript of an utterance, empty when nothing was understood.

`Failed`

`Buffer[]`

The connection could not be restored, with the audio still untranscribed.

See the [STT interface](/docs/ai-integration/custom-integrations/custom-stt) for the full contract.

Each stream given to `transcribe()` is one utterance with a transcript of its own, and the transcripts come in the order of the streams. A stream can start while the previous one still waits for its transcript: Gemini names no utterance in what it sends, so it hears them one after the other, and the audio of the next one waits for the transcript of the previous.

### Options

Option

Type

Default

Description

`apiKey`

`string`

Required

Your Gemini API key

`model`

`string`

`'gemini-3.5-transcribe-live'`

Transcription model

`language`

`string`

`undefined`

Language of the user, as a BCP-47 code like `fr-FR`

`vocabulary`

`string[]`

`undefined`

Words to recognize, up to 1,000

`mode`

`'SMART' | 'VERBATIM'`

Model default

Cleans up hesitations, or keeps every word as said

`transcriptionTimeout`

`number`

`4000`

How long to wait for a transcript, in milliseconds

`connectionTimeout`

`number`

`5000`

Time to open the connection, in milliseconds

`retryDelay`

`number`

`1000`

Delay before reconnecting, in milliseconds

`maxRetry`

`number`

`3`

Reconnection attempts before giving up

## Gemini TTS (Text-to-Speech)

Gemini TTS is the text to speech of the Gemini API: a Gemini model reads the text in one of 30 prebuilt voices, in the tone your instructions ask for. Google’s newest models are Gemini 3.8 Flash TTS and Gemini 3.8 Flash-Lite TTS. Flash TTS speaks over 130 languages. Flash-Lite TTS speaks over 100 and costs a third less for audio. [Gemini TTS costs](https://ai.google.dev/gemini-api/docs/pricing) from $0.50 per million text tokens and $6 per million audio tokens in November 2026.

`GeminiTTS` reads the answers of your agent with Gemini TTS. The model needs a whole text before it speaks, so `GeminiTTS` cuts the answer into sentences and sends the audio of each one as the model streams it.

### Usage with MicdropServer

```typescript
import { GeminiTTS } from '@micdrop/gemini'
import { MicdropServer } from '@micdrop/server'

const tts = new GeminiTTS({
  apiKey: process.env.GEMINI_API_KEY || '',
  model: 'gemini-2.5-flash-preview-tts', // Default model
  voice: 'Kore', // Default voice

  // Direction put before each sentence (optional)
  instructions: 'Say in a calm and friendly tone',
})

new MicdropServer(socket, {
  tts,
  // ... other options
})
```

### Usage without MicdropServer

```typescript
import { GeminiTTS } from '@micdrop/gemini'
import { Readable } from 'stream'

const tts = new GeminiTTS({ apiKey: process.env.GEMINI_API_KEY || '' })

// Audio is raw PCM, 16 bits, 16 kHz, mono
tts.on('Audio', (chunk) => console.log('Audio:', chunk.length, 'bytes'))
tts.on('Failed', (texts) => console.error('Failed:', texts))

tts.speak(Readable.from(['Hello! ', 'What can I do for you?']))
```

### Events

Event

Payload

Description

`Audio`

`Buffer`

A chunk of audio, PCM 16 bits, 16 kHz, mono, ready to be played.

`Failed`

`string[]`

Synthesis gave up after an error, with the text that stayed unspoken.

See the [TTS interface](/docs/ai-integration/custom-integrations/custom-tts) for the full contract.

### Options

Option

Type

Default

Description

`apiKey`

`string`

Required\*

Your Gemini API key (required if `genai` not provided)

`genai`

`GoogleGenAI`

Optional

Client of `@google/genai` (alternative to `apiKey`)

`model`

`string`

`'gemini-2.5-flash-preview-tts'`

Speech model to use

`voice`

`string`

`'Kore'`

One of the 30 prebuilt voices, such as `Puck` or `Aoede`

`instructions`

`string`

`undefined`

How to say the text, such as `Say cheerfully`

`maxRetry`

`number`

`2`

Attempts after Gemini blocked a sentence by mistake

The voice speaks the language of the text. Gemini 3.8 Flash TTS speaks over 130 languages, and Gemini 3.8 Flash-Lite TTS over 100.

Gemini now and then blocks an ordinary sentence as if its content were forbidden, then accepts the very same sentence on the next request. `GeminiTTS` asks again, up to `maxRetry` times, as long as no audio of that sentence has been played.

### Models

Set the `model` option to one of the Gemini TTS models. Prices are those of the Gemini API per million tokens, text in and audio out, on November 7, 2026. Both prices of the 3.8 models double on January 1, 2027.

Model

First audio of a sentence

Free tier

Paid, text / audio

`gemini-3.8-flash-tts`

Not measured

Yes

$0.50 / $9

`gemini-3.8-flash-lite-tts`

Not measured

Yes

$0.50 / $6

`gemini-2.5-flash-preview-tts`

About three seconds

Yes

$0.50 / $10

`gemini-2.5-pro-preview-tts`

Not measured

No

$1 / $20

`gemini-3.1-flash-tts-preview`

About one second

Yes

$1 / $20

`gemini-2.5-flash-preview-tts` is the default, because it sends each sentence whole and the call plays without a gap. `gemini-3.1-flash-tts-preview` starts speaking sooner, then streams the rest slower than it is spoken, which leaves gaps in a long sentence. `gemini-2.5-pro-preview-tts`, the larger model, is open to paid accounts only.

Google may shut the 2.5 and 3.1 preview models down from November 17, 2026. It names `gemini-3.8-flash-tts` and `gemini-3.8-flash-lite-tts` to replace them. Both 3.8 models can also create a voice from a written description, while the `voice` option of `GeminiTTS` takes one of the 30 prebuilt names.

### Voices

Gemini TTS has 30 prebuilt voices. Pass the name as `voice`. Google describes each voice by its tone:

Voice

Tone

Voice

Tone

Voice

Tone

Zephyr

Bright

Autonoe

Bright

Alnilam

Firm

Puck

Upbeat

Enceladus

Breathy

Schedar

Even

Charon

Informative

Iapetus

Clear

Gacrux

Mature

Kore

Firm

Umbriel

Easy-going

Pulcherrima

Forward

Fenrir

Excitable

Algieba

Smooth

Achird

Friendly

Leda

Youthful

Despina

Smooth

Zubenelgenubi

Casual

Orus

Firm

Erinome

Clear

Vindemiatrix

Gentle

Aoede

Breezy

Algenib

Gravelly

Sadachbia

Lively

Callirrhoe

Easy-going

Rasalgethi

Informative

Sadaltager

Knowledgeable

Laomedeia

Upbeat

Achernar

Soft

Sulafat

Warm

Write in `instructions`, in plain language, how the model should say the text. `GeminiTTS` puts it before each sentence, as in `Say in a calm and friendly tone: Your order has shipped.`, so the model reads the sentence in that tone. An instruction can set the emotion, the pace or an accent, such as `Speak slowly and warmly` or `Say it with a British accent`. It applies to the whole call, so keep it short and give the agent the personality through its prompt.

Gemini TTS is one of the [ElevenLabs alternatives for a TypeScript voice agent](/blog/elevenlabs-alternatives-typescript), next to Cartesia, OpenAI and the models that run locally.

## Gemini Live

`GeminiLive` is a [realtime model](/docs/server/realtime) running on the Gemini Live API. It hears the user and answers with its own voice, in place of a speech to text, an agent and a text to speech.

Gemini 3.8 Live costs about a quarter of GPT-Realtime-2.1 per minute. It also [differs from OpenAI’s realtime models in session length and reasoning](/blog/gpt-live-vs-gpt-realtime-vs-gemini-live).

### Usage with MicdropServer

```typescript
import { GeminiLive } from '@micdrop/gemini'
import { MicdropServer } from '@micdrop/server'

const realtime = new GeminiLive({
  apiKey: process.env.GEMINI_API_KEY || '',
  model: 'gemini-3.8-live', // Default model
  systemPrompt: 'You are a helpful assistant',
  voice: 'Kore', // Optional, a prebuilt voice

  // Advanced features (optional)
  autoEndCall: true, // Automatically end call when user requests
})

new MicdropServer(socket, {
  realtime,
  generateFirstMessage: true,
})
```

The Micdrop client detects when the user speaks, so `GeminiLive` turns off the automatic activity detection of Gemini. Each turn is sent between an `activityStart` and an `activityEnd`, and the model answers once the turn ends.

### Tools

Tools are added as with any agent, and run on your server:

```typescript
import { z } from 'zod'

realtime.addTool({
  name: 'get_weather',
  description: 'Get the current weather in a city',
  inputSchema: z.object({ city: z.string() }),
  execute: async ({ city }) => fetchWeather(city),
})
```

Gemini ends its turn when it calls a tool, then speaks about the result once it has it. The client keeps waiting for the answer in between. A tool declared with `skipAnswer` gives its result to the model silently.

When the user interrupts the answer while a tool runs, its result still goes in the conversation and reaches the model silently, so the model knows it without speaking about it. A tool that finishes after a dropped connection, when the new session starts over, only goes in the conversation, since that session never heard of the call.

Gemini reads the tools when the session opens, so add them right after creating the model, before the connection is established.

### Events

`GeminiLive` emits the events of an agent, and two of its own.

Event

Payload

Description

`Audio`

`Buffer`

A chunk of the voice of the model, PCM 16 bits, 16 kHz, mono.

`PartialMessage`

`string`

The transcript of the answer so far.

`Message`

`MicdropConversationItem`

A message, a tool call or a tool result was added to the conversation.

`ToolCall`

`MicdropToolCall`

A tool declared with `emitOutput` ran, with its parameters and output.

`CancelLastUserMessage`

none

The last user message was dropped because it carried no intent.

`SkipAnswer`

none

The model gave no spoken answer.

`EndCall`

none

The model decided that the call is over.

`Failed`

none

The connection could not be restored after its retries.

### Options

Option

Type

Default

Description

`apiKey`

`string`

Required

Your Gemini API key

`systemPrompt`

`string`

Required

Instructions of the model

`model`

`string`

`'gemini-3.8-live'`

Live model to use

`voice`

`string`

`undefined`

Name of a prebuilt voice, such as `Kore` or `Puck`

`thinkingLevel`

`string`

`undefined`

Reasoning level, required by `gemini-3.8-live-extended-thinking`

`autoEndCall`

`boolean | string`

`false`

Ends the call when the user asks for it

`autoSemanticTurn`

`boolean | string`

`false`

Lets the model wait silently when the user did not finish their sentence

`autoIgnoreUserNoise`

`boolean | string`

`false`

Drops the turn when it carries no meaning

`connectionTimeout`

`number`

`5000`

Time to open the connection, in milliseconds

`retryDelay`

`number`

`1000`

Delay before reconnecting, in milliseconds

`maxRetry`

`number`

`3`

Reconnection attempts before giving up

`gemini-3.8-live-extended-thinking` reasons before answering, for questions that take several steps. It refuses to start without a `thinkingLevel`, such as `'low'`, while `gemini-3.8-live` refuses any.

### Long calls

A Gemini connection lasts a few minutes. `GeminiLive` keeps the handle Gemini sends to resume the session, and moves to a new connection at the first silence once Gemini announces the end of the current one. `GeminiLive` also turns on context window compression, which lifts the fifteen minute limit of an audio session.

## Gemini Classifier

`GeminiClassifier` is a [classifier](/docs/server/classifier) running the [Decisions API](https://aistudio.google.com/docs/decisions-api) of Gemini. It answers a set of typed questions in a single forward pass, without writing a token: the probability that a condition is true, a choice out of several values, or a score on ordered levels. Adding questions barely changes the latency, up to 1,000 per request.

Gemini Decision 1 is its only model, on the `v1beta` Gemini Developer API. It asks the same three kinds of questions as [Jev](/docs/ai-integration/provided-integrations/typesafe), with the same helpers and the same shape of answers, so code reading `answers.wantsHuman.noul` works with both.

### Usage with MicdropServer

```typescript
import { choice, GeminiClassifier, noul, score } from '@micdrop/gemini'
import { MicdropServer } from '@micdrop/server'

const classifier = new GeminiClassifier({
  apiKey: process.env.GEMINI_API_KEY || '',
  questions: {
    intent: choice(
      'What does the user in `turn` want? Read `history` for context.',
      {
        billing: 'A charge, an invoice, a refund',
        outage: 'The service is down or slow',
        cancel: 'Cancel the subscription or switch provider',
        other: 'Anything else',
      }
    ),
    frustration: score('How frustrated is the user in `turn`?', [
      'Calm',
      'Annoyed',
      'Angry',
    ]),
    wantsHuman: noul('Does the user in `turn` ask for a human?'),
  },
})

new MicdropServer(socket, {
  stt,
  agent,
  tts,
  classifier,
  classifierOptions: { sendToClient: true, waitBeforeAnswer: true },
})
```

The server classifies each turn of the user when it ends, and sends it the `MicdropTurnInput` as JSON, with the `turn` and its `history`. The model never sees the keys of the questions, so each instruction holds the whole question and points at these fields by name, between backticks. See [Classifier](/docs/server/classifier) for the server options and routing the answer in `onBeforeAnswer`.

### Usage without MicdropServer

```typescript
import { GeminiClassifier, noul } from '@micdrop/gemini'

const classifier = new GeminiClassifier({
  apiKey: process.env.GEMINI_API_KEY || '',
  questions: { urgent: noul('Does this message sound urgent?') },
})

const classification = await classifier.classify('My internet is down!')
console.log(classification?.result.answers.urgent.noul)
```

### Questions

Three helpers build the questions. The key of each question names its answer.

Helper

Answers

Example

`noul(instructions, criteria?)`

The probability that the condition is true

Asks for a human, wants to cancel

`choice(instructions, criteria)`

One value out of several, without order

The intent, the topic, the language

`score(instructions, levels)`

A position on ordered levels, from the lowest

Frustration, urgency, severity

`noul()` can take `{ true, false }`, a description of each outcome. `choice()` takes an object of 2 to 255 values, each with a short description of when it applies. Its probabilities always add up to 1, even when no value fits, so add a fallback such as `other`. `score()` takes the description of each level from the lowest up. Keep the levels evenly spaced, since the score averages their indices.

Every question goes in the same request. To pick them per input, pass a function of the input as `questions`.

### Reading the answers

The answers are typed from your questions:

```typescript
const { answers, usage } = getTurnClassification(this.conversation)!.result

answers.intent.choice // 'billing', typed as one of your values
answers.intent.confidence // 0.93
answers.intent.probabilities // { billing: 0.93, outage: 0.02, cancel: 0.03, other: 0.02 }

answers.frustration.score // 1.1, the weighted average of the level indices
answers.frustration.probabilities // { 0: 0.1, 1: 0.7, 2: 0.2 }

answers.wantsHuman.noul // 0.07
answers.wantsHuman.confidence // 0.93

usage?.total_input_tokens // 412
```

A `noul` probability stays between 0.01 and 0.99, so a threshold such as `> 0.99` never matches. Set your thresholds on labeled turns of your own application, and send the turns with a low `confidence` to a fallback.

When the safety filters of Gemini block an input, the request fails and the classification resolves to `undefined`, as on a timeout.

### Images, audio and video

The model reads text, images, audio, video and PDF. The `input` option builds what it reads from the input of the classifier, to add a picture the user sent for instance:

```typescript
const classifier = new GeminiClassifier({
  apiKey: process.env.GEMINI_API_KEY || '',
  questions: { damaged: noul('Does the photo show a damaged item?') },
  input: (input) => [
    { type: 'text', text: JSON.stringify(input) },
    { type: 'image', uri: lastPhotoUrl, mime_type: 'image/jpeg' },
  ],
})
```

### Options

Option

Type

Default

Description

`apiKey`

`string`

Required

Your Gemini API key, or pass a `genai` client instead

`model`

`string`

`'gemini-decision-1'`

Model answering the questions

`questions`

`Questions | (input) => Questions`

Required

Questions built with `noul()`, `choice()` and `score()`, or a function of them

`input`

`(input) => string | Content[]`

The input as JSON

Builds what the model reads, a text or blocks of text, image, audio, video, PDF

`timeout`

`number`

`3000`

Timeout of each request in ms

### Price

Input costs $0.10 per million tokens, and output is free. A request of a thousand tokens costs about $0.0001, so classifying every turn of a call stays well under a cent.

## FAQ

### Can Gemini do text to voice?

Yes. The Gemini API turns a text into speech with its TTS models, such as Gemini 3.8 Flash TTS, in 30 prebuilt voices and over 130 languages. `GeminiTTS`, from the `@micdrop/gemini` package for Node.js, reads the answers of a voice agent with these models, sentence by sentence, while the agent writes them.

### Can I generate native speech using Gemini?

Yes, Gemini generates speech in two ways. The Gemini TTS models read a text in the tone a plain instruction such as `Say cheerfully` asks for. Gemini Live goes from the voice of the user straight to its own spoken answer. Micdrop runs Gemini Live as a [realtime model](/docs/server/realtime), through `GeminiLive`.
