Python MIT License Open Source Project

Gemini Live API Python Tutorial: Hindi-English Voice Study Buddy and Live Translator (Free Code)

Gemini Live API Python tutorial: build a push-to-talk Hindi-English voice study buddy and live translator, tested offline with 158 tests. Free source code.

Project Specifications & Technical Summary

Difficulty Beginner
License MIT License

The Gemini Live API lets your Python program hold a real spoken conversation: you stream microphone audio in, and the model streams its voice back within a fraction of a second. In this tutorial you will build a complete Gemini Live API Python project: a push-to-talk voice study buddy that understands Hindi, English and Hinglish, plus a live translation mode that turns your Hindi sentences into spoken English (or the other way round).

It is written for BTech, MCA and MTech students who want a modern AI final-year or mini project that goes beyond a text chatbot. The best part is the design: the audio streaming layer sits behind a small interface, so the whole app (push-to-talk state machine, barge-in, reconnects and transcript logging) is tested offline with a fake transport. You can run the demo and all 158 pytest tests without an API key or a microphone. The complete source code is free on GitHub under the MIT License.

What You Will Build with the Gemini Live API in Python

The project is a command-line app called live-buddy with two modes and one shared engine:

Mode / commandWhat it does
tutor modeA study buddy on gemini-4-live. Ask in Hindi, English or Hinglish; it answers in simple English with Hindi hints in brackets and ends with a quick check question.
translate modeA live interpreter on gemini-4-live-translate. Speak Hindi and hear English, or swap the languages.
live-buddy chatReal push-to-talk with your microphone and speakers: press Enter to talk, Enter again to stop.
live-buddy ask --wav q.wavSends one recorded question and saves the spoken answer as a WAV file.
live-buddy demoRuns a full conversation offline through the fake transport. No key, no microphone.
live-buddy transcriptShows stats or Markdown revision notes from the JSONL transcript log.
Gemini Live API Python voice assistant architecture: input and output devices, VoiceSession with state machine and transcript logger, and the LiveTransport interface with Gemini and fake transports
The session talks to a small transport interface. The real Gemini transport and the offline fake transport both produce the same events.

Every turn is saved to a transcript log with what you said, what the buddy said, how many seconds you spoke and how quickly the first answer arrived. That gives you real numbers for your project report.

Why the Gemini Live API Matters Right Now

On 2 December 2026 Google announced Gemini 4 Live and Gemini 4 Live Translate. According to Google, Gemini 4 Live cuts time to first audio by more than 3x compared with Gemini 3.8 Live and adds optional thinking levels for harder requests. Gemini 4 Live Translate cuts the start time of live speech translation nearly in half across more than 70 languages. Both models are rolling out to developers in Google AI Studio and the Gemini Live API, together with more than 2,000 preset voices.

The Gemini API release notes for 2 December 2026 list both model codes, gemini-4-live and gemini-4-live-translate, and say the translate model covers more than 4,900 language pairs and starts in under two seconds. SiliconANGLE reported the same day that Google measured a first reply in about 0.39 seconds for Gemini 4 Live and a translation start time down from 3.2 to 1.83 seconds, and that new local accent options include India. Ars Technica noted that the models are also reaching the Gemini app, Search, Google Translate and Google Meet.

For students this means low-latency voice AI is now something you can call from a short Python script, and Hindi is on the official Live Translate language list. The hard part is no longer the model. It is the engineering around it: streaming audio in the right format, deciding when a turn starts and ends, handling interruptions and testing all of it without burning API quota. That is exactly what this project teaches.

Voice apps are mostly state management. If you can explain your turn state machine and show it passing 158 tests, your viva panel will see that you understand real-time systems, not just an API call.

How the Gemini Live API Works with Python

The Live API is a stateful, bidirectional WebSocket session. The Python SDK (google-genai) hides the socket, but the flow is the same:

  1. Setup: the first message picks the model and configuration (response modality, system instruction, transcription, voice, translation settings).
  2. Realtime input: you send raw audio chunks, plus optional activityStart / activityEnd signals when automatic voice activity detection (VAD) is disabled.
  3. Server content: the server streams audio chunks, input and output transcriptions, an interrupted flag when you talk over it, and turnComplete when an answer ends.
  4. Session messages: a goAway warning before the server closes the connection and session resumption handles so you can reconnect without losing context.
Audio detailValue used in this project
EncodingRaw 16-bit little-endian PCM, mono
Input rate16 kHz, MIME type audio/pcm;rate=16000
Output rate24 kHz
Chunk size100 ms (3,200 bytes at 16 kHz), as the Live Translate guide recommends
Push-to-talkAutomatic VAD disabled, manual activityStart / activityEnd (tutor mode)

The Live translation guide explains an important difference: a Live agent works in turns, while Live Translate is a continuous stream that translates as you speak and supports no tools. So in translate mode this project streams audio, sends audio_stream_end when you release the key, and closes the turn itself once the translated speech goes quiet.

Features, Tech Stack and Prerequisites

  • Two Live models: gemini-4-live for the tutor and gemini-4-live-translate for translation, both overridable with --model.
  • Hindi-English first: default Hindi to English, with 20 BCP-47 codes including Tamil, Telugu, Kannada, Malayalam, Marathi, Bengali, Gujarati, Punjabi and Urdu.
  • Push-to-talk turn state machine with barge-in, late-event handling, errors and reconnects.
  • Pure-Python audio: chunking, WAV read/write, resampling and stereo-to-mono with only the standard library.
  • Transcript logging to JSONL plus Markdown revision notes and session stats.
  • Offline fake transport that records the wire protocol for tests and demos.
ItemVersion / notes
Python3.10 or newer (CI runs 3.10, 3.11, 3.12 and 3.13)
Core dependenciesNone. The engine uses only the standard library.
Optional extrasgoogle-genai for the real API, sounddevice for microphone and speakers
Dev dependenciespytest, pytest-cov, ruff
API keyOnly for live use: a free Gemini API key from Google AI Studio
Prior knowledgeBasic Python, classes and a first look at async/await

Project File Structure

Gemini-Live-API-Voice-Assistant-Python/
├── gemini_live_buddy/
│   ├── audio.py          # PCM chunking, WAV, resample, RMS
│   ├── config.py         # modes, languages, Live API setup config
│   ├── events.py         # transport-neutral server events
│   ├── state.py          # push-to-talk turn state machine
│   ├── session.py        # VoiceSession: transport + state + sink + transcript
│   ├── transcript.py     # JSONL logger, stats, Markdown export
│   ├── devices.py        # sinks, optional microphone and speaker
│   ├── phrasebook.py     # tiny offline phrasebook for the fake transport
│   ├── cli.py            # live-buddy demo | ask | chat | transcript | config
│   └── transport/
│       ├── base.py       # LiveTransport interface
│       ├── fake.py       # offline scripted transport (tests, demos, CI)
│       └── gemini.py     # real Gemini Live API transport (google-genai)
├── examples/             # demo scripts
├── samples/              # sample transcripts, demo output, setup configs
├── tests/                # 158 pytest tests
├── .github/workflows/ci.yml
└── pyproject.toml

Step-by-Step: Build the Gemini Live API Python Voice Assistant

Step 1: Set up the project

Clone the repository, create a virtual environment and install it in editable mode. The offline Gemini Live API Python demo works immediately, which is a nice way to check your setup before you touch any API key.

git clone https://github.com/GetProjectsIdea/Gemini-Live-API-Voice-Assistant-Python.git
cd Gemini-Live-API-Voice-Assistant-Python
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -e ".[dev]"
live-buddy demo

Step 2: Prepare audio in the format the Live API expects

The Live API wants raw 16-bit PCM. audio.py splits a recording into 100 ms chunks and builds the MIME type that tells the server the sample rate. The same file reads any 16-bit WAV, converts stereo to mono and resamples 44.1 or 48 kHz recordings down to 16 kHz.

def mime_type(rate: int = INPUT_RATE) -> str:
    """MIME type the Live API expects for a raw PCM blob."""
    if rate <= 0:
        raise ValueError("sample rate must be positive")
    return f"audio/pcm;rate={rate}"


def bytes_per_ms(rate: int = INPUT_RATE) -> float:
    return rate * SAMPLE_WIDTH / 1000


def chunk_size(rate: int = INPUT_RATE, ms: int = CHUNK_MS) -> int:
    """Number of bytes in one chunk of ``ms`` milliseconds (always a whole number of samples)."""
    if ms <= 0:
        raise ValueError("chunk length must be positive")
    size = int(rate * ms / 1000) * SAMPLE_WIDTH
    return max(size, SAMPLE_WIDTH)


def chunk_pcm(pcm: bytes, rate: int = INPUT_RATE, ms: int = CHUNK_MS) -> Iterator[bytes]:
    """Split PCM bytes into ~``ms`` millisecond chunks. The last chunk may be shorter."""
    if len(pcm) % SAMPLE_WIDTH:
        raise ValueError("PCM length must be a multiple of 2 bytes (16-bit samples)")
    size = chunk_size(rate, ms)
    for start in range(0, len(pcm), size):
        yield pcm[start:start + size]

Step 3: Describe the session with a config object

SessionConfig validates the mode and languages and produces the exact config dictionary passed to client.aio.live.connect(). Notice the two shapes: the tutor disables automatic VAD for push-to-talk, while translate mode only needs a translation_config block with a BCP-47 target language such as hi or en.

def to_live_config(self) -> dict[str, Any]:
    """Build the ``config`` dict for ``client.aio.live.connect(model=..., config=...)``."""
    cfg: dict[str, Any] = {"response_modalities": ["AUDIO"]}
    if self.transcribe:
        cfg["input_audio_transcription"] = {}
        cfg["output_audio_transcription"] = {}
    if self.voice:
        cfg["speech_config"] = {"voice_config": {"prebuilt_voice_config": {"voice_name": self.voice}}}
    if self.mode == "translate":
        cfg["translation_config"] = {
            "target_language_code": self.target_language,
            "echo_target_language": self.echo_target_language,
        }
        if self.extra_instructions.strip():
            cfg["system_instruction"] = self.system_instruction()
    else:
        cfg["system_instruction"] = self.system_instruction()
        cfg["realtime_input_config"] = {"automatic_activity_detection": {"disabled": True}}
        cfg["session_resumption"] = {"handle": self.resumption_handle} if self.resumption_handle else {}
    return cfg

A test also feeds these dictionaries into the SDK’s own LiveConnectConfig model, so a typo in a field name fails CI instead of failing in front of your examiner.

Step 4: Hide streaming behind a transport interface

This is the key design decision in any Gemini Live API Python app. The session code only knows six async methods and one event stream. Anything that implements them can drive the app: the real Gemini Live API, a fake for tests, or in future a WebRTC bridge for a web page.

class LiveTransport(ABC):
    """Abstract bidirectional audio transport."""

    @abstractmethod
    async def connect(self, config: SessionConfig) -> None:
        """Open the session and send the setup message."""

    @abstractmethod
    async def start_activity(self) -> None:
        """The push-to-talk button went down: the user starts speaking."""

    @abstractmethod
    async def send_audio(self, chunk: bytes) -> None:
        """Send one chunk of 16-bit, 16 kHz mono PCM."""

    @abstractmethod
    async def end_activity(self) -> None:
        """The push-to-talk button came up: the user finished speaking."""

    @abstractmethod
    async def send_text(self, text: str) -> None:
        """Send a typed message as a complete user turn."""

    @abstractmethod
    def events(self) -> AsyncIterator[ServerEvent]:
        """Async iterator of server events. It ends when the connection closes."""

    @abstractmethod
    async def close(self) -> None:
        """Close the connection. Safe to call twice."""

Server messages are converted into tiny dataclasses (InputTranscript, OutputTranscript, AudioChunk, TurnComplete, Interrupted, GoAway, ResumptionHandle, ErrorEvent), so nothing outside the transport touches SDK objects.

Step 5: Talk to the real Gemini Live API

In Gemini Live API Python code, GeminiTransport opens the session with api_version="v1beta", which the Live API needs, and maps push-to-talk onto realtime input messages. In tutor mode the talk key sends activity_start and activity_end; in translate mode releasing the key sends audio_stream_end.

async def start_activity(self) -> None:
    s = self._need_session()
    assert self.config is not None
    self._awaiting_quiet_end, self._got_output = False, False
    if self.config.push_to_talk_signals:
        await s.send_realtime_input(activity_start={})

async def send_audio(self, chunk: bytes) -> None:
    await self._need_session().send_realtime_input(audio={"data": chunk, "mime_type": audio.mime_type(audio.INPUT_RATE)})

async def end_activity(self) -> None:
    s = self._need_session()
    assert self.config is not None
    if self.config.push_to_talk_signals:
        await s.send_realtime_input(activity_end={})
    else:
        # Live Translate is a continuous stream with no turnComplete; we end the "turn" ourselves
        # once the translated speech has gone quiet for quiet_after_s seconds.
        await s.send_realtime_input(audio_stream_end=True)
        self._awaiting_quiet_end = True

Incoming messages are translated by a pure function, which makes it easy to unit-test with simple stand-in objects:

sc = getattr(msg, "server_content", None)
if sc is not None:
    it = getattr(sc, "input_transcription", None)
    if it is not None and (getattr(it, "text", None) or getattr(it, "finished", False)):
        out.append(InputTranscript(it.text or "", bool(getattr(it, "finished", False)),
                                   getattr(it, "language_code", None)))
    ot = getattr(sc, "output_transcription", None)
    if ot is not None and (getattr(ot, "text", None) or getattr(ot, "finished", False)):
        out.append(OutputTranscript(ot.text or "", bool(getattr(ot, "finished", False))))
    turn = getattr(sc, "model_turn", None)
    for part in getattr(turn, "parts", None) or []:
        blob = getattr(part, "inline_data", None)
        if blob is not None and getattr(blob, "data", None):
            out.append(AudioChunk(blob.data, _rate_from_mime(getattr(blob, "mime_type", None))))
    if getattr(sc, "interrupted", False):
        out.append(Interrupted())
    if getattr(sc, "turn_complete", False):
        reason = getattr(sc, "turn_complete_reason", None)
        out.append(TurnComplete(str(getattr(reason, "value", reason)) if reason else None))

Step 6: Build a fake transport so tests need no API key

FakeTransport behaves like a tiny Live API server, so every Gemini Live API Python test runs offline. It records every message the session sends (so tests can check the protocol order), and when you release the talk key it replies with an input transcript, streamed output text, 24 kHz audio chunks, TurnComplete and a resumption handle. It can also simulate a barge-in, a GoAway or a server error on demand.

async def _produce(self, turn: ScriptedTurn, echo_input: bool = True) -> None:
    assert self.config is not None
    cfg = self.config
    if echo_input:
        await self._queue.put(InputTranscript(turn.heard, True, turn.language or cfg.native_language))
    if self.error_after is not None and self.turns_answered >= self.error_after:
        await self._queue.put(ErrorEvent("fake server error"))
        await self._queue.put(_CLOSE)
        self._connected = False
        return
    reply = turn.reply if turn.reply is not None else self.responder(turn.heard, cfg)
    words = reply.split()
    for i in range(0, len(words), self.words_per_chunk):
        piece = words[i:i + self.words_per_chunk]
        await self._queue.put(OutputTranscript((" " if i else "") + " ".join(piece)))
        await self._queue.put(AudioChunk(audio.tone(330 + 20 * (i % 7), self.ms_per_word * len(piece),
                                                     audio.OUTPUT_RATE, 0.2), audio.OUTPUT_RATE))
        await asyncio.sleep(self.chunk_delay)

The replies come from a small offline phrasebook (“Kal mera exam hai” becomes “I have an exam tomorrow.”). It exists only for tests and demos; real understanding and translation come from the model.

Step 7: Model push-to-talk as a state machine

A Gemini Live API Python voice app breaks in strange ways if you track turns with scattered booleans. Here every allowed move is one entry in a table, and every other move raises InvalidTransition. Late events from an interrupted answer are listed separately and ignored, because real networks deliver them.

TRANSITIONS: dict[tuple[State, str], State] = {
    (S.DISCONNECTED, "connect"): S.CONNECTING,
    (S.ERROR, "connect"): S.CONNECTING,
    (S.CONNECTING, "connected"): S.READY,
    (S.READY, "press"): S.LISTENING,
    (S.LISTENING, "release"): S.THINKING,
    (S.THINKING, "response"): S.SPEAKING,
    (S.THINKING, "turn_complete"): S.READY,
    (S.SPEAKING, "response"): S.SPEAKING,
    (S.SPEAKING, "turn_complete"): S.READY,
    (S.SPEAKING, "interrupted"): S.READY,
    (S.THINKING, "interrupted"): S.READY,
    (S.THINKING, "press"): S.LISTENING,
    (S.SPEAKING, "press"): S.LISTENING,
}

# Harmless late or duplicate events: keep the current state.
IGNORED: set[tuple[State, str]] = {
    (S.READY, "response"), (S.READY, "turn_complete"), (S.READY, "interrupted"),
    (S.LISTENING, "response"), (S.LISTENING, "turn_complete"), (S.LISTENING, "interrupted"),
    (S.CLOSED, "close"), (S.CLOSED, "response"), (S.CLOSED, "turn_complete"),
    (S.CLOSED, "interrupted"), (S.CLOSED, "error"), (S.CLOSED, "go_away"),
    (S.ERROR, "error"), (S.ERROR, "response"), (S.ERROR, "turn_complete"),
}
Gemini Live API Python push-to-talk state machine: ready, listening, thinking, speaking, error and closed states with barge-in
The push-to-talk state machine. Pressing the talk key while the buddy is answering is a barge-in.

Pressing the talk key while the buddy is thinking or speaking is a barge-in. The machine counts it, the session clears buffered playback, and the old turn is saved as interrupted.

Step 8: Tie it together in VoiceSession

VoiceSession owns the transport, the state machine, an audio sink and the transcript logger. Its public API is exactly what a push-to-talk button needs: press(), send_audio() and release(), plus a convenience ask() that streams a whole recording in 100 ms chunks.

async def press(self) -> None:
    barge_in = self.state in (State.THINKING, State.SPEAKING)
    self.machine.fire("press")
    if barge_in:
        self.sink.clear()
        self.logger.end_turn(interrupted=True)
        # The server confirms a barge-in with an "interrupted" message that may arrive late,
        # even after the new turn was released. It belongs to the old answer, not the new one.
        self._expect_interrupt_ack = True
    self.logger.start_turn()
    self._released_at = None
    await self.transport.start_activity()

async def send_audio(self, chunk: bytes) -> None:
    if self.state is not State.LISTENING:
        raise NotListening(f"press the talk button first (state: {self.state.value})")
    await self.transport.send_audio(chunk)
    self.logger.add_audio(inbound_ms=audio.duration_ms(chunk, audio.INPUT_RATE))

async def release(self) -> None:
    self.machine.fire("release")
    self._released_at = self.clock()
    await self.transport.end_activity()

The receive loop sends each event through handle_event(). Audio for the current answer goes to the speaker, and stale audio that arrives after a barge-in is dropped. When the server sends GoAway and then closes the stream, the session reconnects with the latest resumption handle.

elif isinstance(ev, (OutputTranscript, AudioChunk)):
    if not answering:
        return  # stale audio from an interrupted answer: drop it
    if self._released_at is not None:
        self.logger.mark_first_response(self.clock() - self._released_at)
    if isinstance(ev, AudioChunk):
        if not ev.data:
            return
        self.machine.fire("response")
        self.sink.write(ev)
        self.logger.add_audio(outbound_ms=audio.duration_ms(ev.data, ev.rate))
    elif ev.text:
        self.machine.fire("response")
        self.logger.add_model(ev.text)
elif isinstance(ev, TurnComplete):
    self.machine.fire("turn_complete")
    if answering:
        self._expect_interrupt_ack = False
        self.logger.end_turn()
elif isinstance(ev, Interrupted):
    if self._expect_interrupt_ack:
        self._expect_interrupt_ack = False
        return
    self.machine.fire("interrupted")
    if answering:
        self.sink.clear()
        self.logger.end_turn(interrupted=True)

Step 9: Log transcripts for revision and your report

For your Gemini Live API Python report, the transcript logger joins streamed fragments into clean sentences and appends one JSON line per finished turn. Hindi text is stored as readable UTF-8, not escape codes.

{"index": 1, "mode": "tutor", "source_language": "hi", "target_language": "en", "audio_in_ms": 1200.0, "audio_out_ms": 2220.0, "interrupted": false, "first_response_s": 0.001, "user_text": "Namaste! Mujhe recursion samajh nahi aaya", "model_text": "Recursion means a function calls itself on a smaller problem (chhota hissa) until it reaches a base case. ..."}

live-buddy transcript stats prints turns, words, speaking seconds and the average first-response time, and live-buddy transcript markdown turns a session into neat revision notes.

Step 10: Add the command line and the microphone loop

The chat command records 16 kHz audio with sounddevice while you hold the conversation open: press Enter to start talking, press Enter again to stop. The answer plays through a speaker sink that can be cleared instantly on barge-in.

async with VoiceSession(GeminiTransport(), cfg, sink=speaker, logger=logger, on_event=pr.event) as session:
    while True:
        cmd = await loop.run_in_executor(None, input, "\n[Enter = talk] ")
        if cmd.strip().lower() == "q":
            break
        await session.press()
        mic.start()
        stop = loop.run_in_executor(None, input, "  listening... [Enter = stop] ")
        while not stop.done():
            chunk = await loop.run_in_executor(None, mic.read, 0.1)
            if chunk:
                await session.send_audio(chunk)
        mic.stop()
        await session.release()

Run and Test the Gemini Live API Python Project

Run the offline demo in both modes, then the test suite:

live-buddy demo
live-buddy demo --mode translate --states
live-buddy demo --log logs/session.jsonl --markdown logs/notes.md
live-buddy config --mode translate --source en --target hi
pytest -v
Gemini Live API Python study buddy demo in the terminal: Hindi questions about recursion and Big O with English answers
The offline demo: three Hinglish questions, streamed English answers and the exact protocol messages sent.

The last line of the demo is the protocol the session actually sent: connect activity_start activity_end ... close. Tests assert this order, so if you refactor the session and accidentally send audio before activity_start, CI goes red.

def test_protocol_order(speech):
    async def go():
        fake, _, s = make([ScriptedTurn("a"), ScriptedTurn("b")])
        async with s:
            await s.ask(speech)
            await s.ask(speech)
        assert [k for k in fake.kinds if k != "audio"] == [
            "connect", "activity_start", "activity_end", "activity_start", "activity_end", "close"]
    run(go())

The Gemini Live API Python test suite has 158 tests across audio helpers, config validation, the state machine, the fake transport, the session (barge-in, latency, reconnect, errors), the real transport with a stub SDK client, the transcript logger and the CLI. GitHub Actions runs it on Python 3.10 to 3.13 with no secrets configured.

158 pytest tests passing for the Gemini Live API Python voice assistant without an API key or microphone
All 158 tests pass offline. The fake transport and a stub SDK client stand in for the network.

Connect the Gemini Live API Python App to Your Real Key

  1. Create a key in Google AI Studio and set it as GEMINI_API_KEY in your terminal. Never commit it to Git.
  2. Install the extras: pip install -e ".[gemini,audio]" (on Linux also sudo apt install libportaudio2).
  3. Ask from a file: live-buddy ask --wav question.wav --out answer.wav --log logs/session.jsonl.
  4. Translate: live-buddy ask --mode translate --source hi --target en --wav hindi.wav --out english.wav.
  5. Talk live: live-buddy chat, then press Enter to start and stop speaking.

The Gemini 4 Live model page lists a free tier and paid per-token prices, so check current limits before a long demo. The Live API capabilities guide also limits audio-only sessions to 15 minutes unless you use session management, which is why this project tracks resumption handles. If you later build a web or mobile front end, use the Live API’s ephemeral tokens instead of putting your key in client code.

Learning Outcomes for Your Viva

Building this Gemini Live API Python project gives you plenty to discuss in a viva or interview:

  • How a bidirectional streaming API differs from request-response REST calls.
  • Audio fundamentals: PCM, sample rate, sample width, chunk size and resampling.
  • Designing to an interface (dependency inversion) so I/O-heavy code is testable.
  • Finite state machines for user interaction, including races such as barge-in and late events.
  • Async Python: tasks, events, timeouts, producer-consumer buffers and clean cancellation.
  • Measuring latency (first response time) and logging experiments for a report.
  • Safe handling of API keys and graceful errors when a key or device is missing.

Future Scope and Extension Ideas

Once the basic Gemini Live API Python assistant works, pick one or two of these to make your project stand out:

  • A Flask or FastAPI web page with a big push-to-talk button, using ephemeral tokens.
  • Viva practice mode: the buddy asks five questions on a syllabus topic and scores your answers.
  • Pronunciation and vocabulary tracking from the transcript log across a whole semester.
  • Function calling: let the tutor fetch your timetable or notes (see the related Gemini student assistant below).
  • Compare Live Translate latency for Hindi, Tamil and Bengali and publish the results as a mini research study.
  • A Raspberry Pi desk device with a physical talk button.

Gemini Live API Python: Frequently Asked Questions

Do I need an API key to run this Gemini Live API Python project?

No, not for the demo and tests. live-buddy demo and all 158 tests use the offline fake transport. You only need a free Gemini API key from Google AI Studio when you want to talk to the real model with ask or chat.

Which models does it use?

Tutor mode defaults to gemini-4-live and translate mode to gemini-4-live-translate, the model codes listed in the Gemini API release notes for 2 December 2026. You can override either with --model or the LIVE_BUDDY_MODEL environment variable if Google renames them.

Does the Gemini Live API understand Hindi and Hinglish?

Hindi (hi) is on the official Live Translate language list, and the tutor’s system instruction tells the model that the student may mix Hindi and English. Test your own accent and topic. The transcript log makes it easy to measure how well it works.

Why push-to-talk instead of always-on listening?

In a hostel room or classroom, background voices can trigger automatic voice activity detection. Push-to-talk disables automatic VAD and sends explicit start and end signals, so you control exactly when a turn begins and ends. It also makes the state machine easy to test.

What happens if I interrupt the buddy while it is speaking?

That is a barge-in. The state machine moves back to listening, buffered audio is cleared so you do not hear the old answer, and the previous turn is saved as interrupted. A late interrupted message from the server is recognised and ignored.

Can I submit this as my final-year project?

Yes. The code is MIT licensed. Add one feature from the future scope list, explain the transport interface and the state machine in your report, and show the demo plus the 158 passing tests in your viva. The source is on GitHub.

Download the Source Code

The complete project (audio helpers, config, transports, state machine, session, transcript logger, CLI, examples, sample transcripts, 158 tests and CI) is on GitHub: GetProjectsIdea/Gemini-Live-API-Voice-Assistant-Python. It is released under the MIT License, so you can use this Gemini Live API Python project for coursework, college projects and your own experiments.

References

Conclusion

You have built a complete Gemini Live API Python voice assistant: a push-to-talk Hindi-English study buddy and live translator with clean audio handling, a tested turn state machine, barge-in, reconnects and transcript logging. Because streaming sits behind an interface, you can demo and test everything offline and switch to the real model with one API key. Clone the repository, run the demo, then ask your first real question out loud. Happy coding!

Team Get Projects

Contributor & Author
View All Projects →

Contributor at GetProjects.org, sharing open-source codebases, tutorials, and practical software architectures.

0 Discussion Comments

Markdown Supported

Join the Discussion & Code Review

Share architectural feedback, benchmark results, or troubleshooting notes.