Open History to see the last commit
1{
2 "markdown": "<br />\n\n> [!WARNING]\n> **Preview:** The Live API is in preview.\n\nThis is a comprehensive guide that covers capabilities and configurations\navailable with the Live API.\nSee [Get started with Live API](https://ai.google.dev/gemini-api/docs/live) page for a\noverview and sample code for common use cases.\n\n## Before you begin\n\n- **Familiarize yourself with core concepts:** If you haven't already done so, read the [Get started with Live API](https://ai.google.dev/gemini-api/docs/live) page first. This will introduce you to the fundamental principles of the Live API, how it works, and the different [implementation approaches](https://ai.google.dev/gemini-api/docs/live#implementation-approach).\n- **Try the Live API in AI Studio:** You may find it useful to try the Live API in [Google AI Studio](https://aistudio.google.com/app/live) before you start building. To use the Live API in Google AI Studio, select **Stream**.\n\n## Establishing a connection\n\nThe following example shows how to create a connection with an API key:\n\n### Python\n\n import asyncio\n from google import genai\n\n client = genai.Client()\n\n model = \"gemini-2.5-flash-native-audio-preview-12-2025\"\n config = {\"response_modalities\": [\"AUDIO\"]}\n\n async def main():\n async with client.aio.live.connect(model=model, config=config) as session:\n print(\"Session started\")\n # Send content...\n\n if __name__ == \"__main__\":\n asyncio.run(main())\n\n### JavaScript\n\n import { GoogleGenAI, Modality } from '@google/genai';\n\n const ai = new GoogleGenAI({});\n const model = 'gemini-2.5-flash-native-audio-preview-12-2025';\n const config = { responseModalities: [Modality.AUDIO] };\n\n async function main() {\n\n const session = await ai.live.connect({\n model: model,\n callbacks: {\n onopen: function () {\n console.debug('Opened');\n },\n onmessage: function (message) {\n console.debug(message);\n },\n onerror: function (e) {\n console.debug('Error:', e.message);\n },\n onclose: function (e) {\n console.debug('Close:', e.reason);\n },\n },\n config: config,\n });\n\n console.debug(\"Session started\");\n // Send content...\n\n session.close();\n }\n\n main();\n\n## Interaction modalities\n\nThe following sections provide examples and supporting context for the different\ninput and output modalities available in Live API.\n\n### Sending and receiving audio\n\nThe most common audio example, **audio-to-audio** , is covered in the\n[Getting started](https://ai.google.dev/gemini-api/docs/live#audio-to-audio) guide.\n\n### Audio formats\n\nAudio data in the Live API is always raw, little-endian,\n16-bit PCM. Audio output always uses a sample rate of 24kHz. Input audio\nis natively 16kHz, but the Live API will resample if needed\nso any sample rate can be sent. To convey the sample rate of input audio, set\nthe MIME type of each audio-containing [Blob](https://ai.google.dev/api/caching#Blob) to a value\nlike `audio/pcm;rate=16000`.\n\n### Sending text\n\nHere's how you can send text:\n\n### Python\n\n message = \"Hello, how are you?\"\n await session.send_client_content(turns=message, turn_complete=True)\n\n### JavaScript\n\n const message = 'Hello, how are you?';\n session.sendClientContent({ turns: message, turnComplete: true });\n\n#### Incremental content updates\n\nUse incremental updates to send text input, establish session context, or\nrestore session context. For short contexts you can send turn-by-turn\ninteractions to represent the exact sequence of events:\n\n### Python\n\n turns = [\n {\"role\": \"user\", \"parts\": [{\"text\": \"What is the capital of France?\"}]},\n {\"role\": \"model\", \"parts\": [{\"text\": \"Paris\"}]},\n ]\n\n await session.send_client_content(turns=turns, turn_complete=False)\n\n turns = [{\"role\": \"user\", \"parts\": [{\"text\": \"What is the capital of Germany?\"}]}]\n\n await session.send_client_content(turns=turns, turn_complete=True)\n\n### JavaScript\n\n let inputTurns = [\n { \"role\": \"user\", \"parts\": [{ \"text\": \"What is the capital of France?\" }] },\n { \"role\": \"model\", \"parts\": [{ \"text\": \"Paris\" }] },\n ]\n\n session.sendClientContent({ turns: inputTurns, turnComplete: false })\n\n inputTurns = [{ \"role\": \"user\", \"parts\": [{ \"text\": \"What is the capital of Germany?\" }] }]\n\n session.sendClientContent({ turns: inputTurns, turnComplete: true })\n\nFor longer contexts it's recommended to provide a single message summary to free\nup the context window for subsequent interactions. See [Session Resumption](https://ai.google.dev/gemini-api/docs/live-session#session-resumption) for another method for\nloading session context.\n\n### Audio transcriptions\n\nIn addition to the model response, you can also receive transcriptions of\nboth the audio output and the audio input.\n\nTo enable transcription of the model's audio output, send\n`output_audio_transcription` in the setup config. The transcription language is\ninferred from the model's response.\n\n### Python\n\n import asyncio\n from google import genai\n from google.genai import types\n\n client = genai.Client()\n model = \"gemini-2.5-flash-native-audio-preview-12-2025\"\n\n config = {\n \"response_modalities\": [\"AUDIO\"],\n \"output_audio_transcription\": {}\n }\n\n async def main():\n async with client.aio.live.connect(model=model, config=config) as session:\n message = \"Hello? Gemini are you there?\"\n\n await session.send_client_content(\n turns={\"role\": \"user\", \"parts\": [{\"text\": message}]}, turn_complete=True\n )\n\n async for response in session.receive():\n if response.server_content.model_turn:\n print(\"Model turn:\", response.server_content.model_turn)\n if response.server_content.output_transcription:\n print(\"Transcript:\", response.server_content.output_transcription.text)\n\n if __name__ == \"__main__\":\n asyncio.run(main())\n\n### JavaScript\n\n import { GoogleGenAI, Modality } from '@google/genai';\n\n const ai = new GoogleGenAI({});\n const model = 'gemini-2.5-flash-native-audio-preview-12-2025';\n\n const config = {\n responseModalities: [Modality.AUDIO],\n outputAudioTranscription: {}\n };\n\n async function live() {\n const responseQueue = [];\n\n async function waitMessage() {\n let done = false;\n let message = undefined;\n while (!done) {\n message = responseQueue.shift();\n if (message) {\n done = true;\n } else {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n return message;\n }\n\n async function handleTurn() {\n const turns = [];\n let done = false;\n while (!done) {\n const message = await waitMessage();\n turns.push(message);\n if (message.serverContent && message.serverContent.turnComplete) {\n done = true;\n }\n }\n return turns;\n }\n\n const session = await ai.live.connect({\n model: model,\n callbacks: {\n onopen: function () {\n console.debug('Opened');\n },\n onmessage: function (message) {\n responseQueue.push(message);\n },\n onerror: function (e) {\n console.debug('Error:', e.message);\n },\n onclose: function (e) {\n console.debug('Close:', e.reason);\n },\n },\n config: config,\n });\n\n const inputTurns = 'Hello how are you?';\n session.sendClientContent({ turns: inputTurns });\n\n const turns = await handleTurn();\n\n for (const turn of turns) {\n if (turn.serverContent && turn.serverContent.outputTranscription) {\n console.debug('Received output transcription: %s\\n', turn.serverContent.outputTranscription.text);\n }\n }\n\n session.close();\n }\n\n async function main() {\n await live().catch((e) => console.error('got error', e));\n }\n\n main();\n\nTo enable transcription of the model's audio input, send\n`input_audio_transcription` in setup config.\n\n### Python\n\n import asyncio\n from pathlib import Path\n from google import genai\n from google.genai import types\n\n client = genai.Client()\n model = \"gemini-2.5-flash-native-audio-preview-12-2025\"\n\n config = {\n \"response_modalities\": [\"AUDIO\"],\n \"input_audio_transcription\": {},\n }\n\n async def main():\n async with client.aio.live.connect(model=model, config=config) as session:\n audio_data = Path(\"16000.pcm\").read_bytes()\n\n await session.send_realtime_input(\n audio=types.Blob(data=audio_data, mime_type='audio/pcm;rate=16000')\n )\n\n async for msg in session.receive():\n if msg.server_content.input_transcription:\n print('Transcript:', msg.server_content.input_transcription.text)\n\n if __name__ == \"__main__\":\n asyncio.run(main())\n\n### JavaScript\n\n import { GoogleGenAI, Modality } from '@google/genai';\n import * as fs from \"node:fs\";\n import pkg from 'wavefile';\n const { WaveFile } = pkg;\n\n const ai = new GoogleGenAI({});\n const model = 'gemini-2.5-flash-native-audio-preview-12-2025';\n\n const config = {\n responseModalities: [Modality.AUDIO],\n inputAudioTranscription: {}\n };\n\n async function live() {\n const responseQueue = [];\n\n async function waitMessage() {\n let done = false;\n let message = undefined;\n while (!done) {\n message = responseQueue.shift();\n if (message) {\n done = true;\n } else {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n return message;\n }\n\n async function handleTurn() {\n const turns = [];\n let done = false;\n while (!done) {\n const message = await waitMessage();\n turns.push(message);\n if (message.serverContent && message.serverContent.turnComplete) {\n done = true;\n }\n }\n return turns;\n }\n\n const session = await ai.live.connect({\n model: model,\n callbacks: {\n onopen: function () {\n console.debug('Opened');\n },\n onmessage: function (message) {\n responseQueue.push(message);\n },\n onerror: function (e) {\n console.debug('Error:', e.message);\n },\n onclose: function (e) {\n console.debug('Close:', e.reason);\n },\n },\n config: config,\n });\n\n // Send Audio Chunk\n const fileBuffer = fs.readFileSync(\"16000.wav\");\n\n // Ensure audio conforms to API requirements (16-bit PCM, 16kHz, mono)\n const wav = new WaveFile();\n wav.fromBuffer(fileBuffer);\n wav.toSampleRate(16000);\n wav.toBitDepth(\"16\");\n const base64Audio = wav.toBase64();\n\n // If already in correct format, you can use this:\n // const fileBuffer = fs.readFileSync(\"sample.pcm\");\n // const base64Audio = Buffer.from(fileBuffer).toString('base64');\n\n session.sendRealtimeInput(\n {\n audio: {\n data: base64Audio,\n mimeType: \"audio/pcm;rate=16000\"\n }\n }\n );\n\n const turns = await handleTurn();\n for (const turn of turns) {\n if (turn.text) {\n console.debug('Received text: %s\\n', turn.text);\n }\n else if (turn.data) {\n console.debug('Received inline data: %s\\n', turn.data);\n }\n else if (turn.serverContent && turn.serverContent.inputTranscription) {\n console.debug('Received input transcription: %s\\n', turn.serverContent.inputTranscription.text);\n }\n }\n\n session.close();\n }\n\n async function main() {\n await live().catch((e) => console.error('got error', e));\n }\n\n main();\n\n### Stream audio and video\n\n> [!NOTE]\n> To see an example of how to use\n> the Live API in a streaming audio and video format,\n> run the \"Live API - Get Started\" file in the cookbooks repository:\n>\n>\n> [View\n> on Colab](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Get_started_LiveAPI.py)\n\n### Change voice and language\n\n[Native audio output](https://ai.google.dev/gemini-api/docs/live-guide#native-audio-output) models support any of the voices\navailable for our [Text-to-Speech (TTS)](https://ai.google.dev/gemini-api/docs/speech-generation#voices)\nmodels. You can listen to all the voices in [AI Studio](https://aistudio.google.com/app/live).\n\nTo specify a voice, set the voice name within the `speechConfig` object as part\nof the session configuration:\n\n### Python\n\n config = {\n \"response_modalities\": [\"AUDIO\"],\n \"speech_config\": {\n \"voice_config\": {\"prebuilt_voice_config\": {\"voice_name\": \"Kore\"}}\n },\n }\n\n### JavaScript\n\n const config = {\n responseModalities: [Modality.AUDIO],\n speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: \"Kore\" } } }\n };\n\n> [!NOTE]\n> **Note:** If you're using the `generateContent` API, the set of available voices is slightly different. See the [audio generation guide](https://ai.google.dev/gemini-api/docs/audio-generation#voices) for `generateContent` audio generation voices.\n\nThe Live API supports [multiple languages](https://ai.google.dev/gemini-api/docs/live-guide#supported-languages).\n[Native audio output](https://ai.google.dev/gemini-api/docs/live-guide#native-audio-output) models automatically choose\nthe appropriate language and don't support explicitly setting the language\ncode.\n\n## Native audio capabilities\n\nOur latest models feature [native audio output](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-native-audio-preview-12-2025),\nwhich provides natural, realistic-sounding speech and improved multilingual\nperformance. Native audio also enables advanced features like [affective\n(emotion-aware) dialogue](https://ai.google.dev/gemini-api/docs/live-guide#affective-dialog), [proactive audio](https://ai.google.dev/gemini-api/docs/live-guide#proactive-audio)\n(where the model intelligently decides when to respond to input),\nand [\"thinking\"](https://ai.google.dev/gemini-api/docs/live-guide#native-audio-output-thinking).\n\n### Affective dialog\n\nThis feature lets Gemini adapt its response style to the input expression and\ntone.\n\nTo use affective dialog, set the api version to `v1alpha` and set\n`enable_affective_dialog` to `true`in the setup message:\n\n### Python\n\n client = genai.Client(http_options={\"api_version\": \"v1alpha\"})\n\n config = types.LiveConnectConfig(\n response_modalities=[\"AUDIO\"],\n enable_affective_dialog=True\n )\n\n### JavaScript\n\n const ai = new GoogleGenAI({ httpOptions: {\"apiVersion\": \"v1alpha\"} });\n\n const config = {\n responseModalities: [Modality.AUDIO],\n enableAffectiveDialog: true\n };\n\n### Proactive audio\n\nWhen this feature is enabled, Gemini can proactively decide not to respond\nif the content is not relevant.\n\nTo use it, set the api version to `v1alpha` and configure the `proactivity`\nfield in the setup message and set `proactive_audio` to `true`:\n\n### Python\n\n client = genai.Client(http_options={\"api_version\": \"v1alpha\"})\n\n config = types.LiveConnectConfig(\n response_modalities=[\"AUDIO\"],\n proactivity={'proactive_audio': True}\n )\n\n### JavaScript\n\n const ai = new GoogleGenAI({ httpOptions: {\"apiVersion\": \"v1alpha\"} });\n\n const config = {\n responseModalities: [Modality.AUDIO],\n proactivity: { proactiveAudio: true }\n }\n\n### Thinking\n\nThe latest native audio output model `gemini-2.5-flash-native-audio-preview-12-2025`\nsupports [thinking capabilities](https://ai.google.dev/gemini-api/docs/thinking), with dynamic\nthinking enabled by default.\n\nThe `thinkingBudget` parameter guides the model on the number of thinking tokens\nto use when generating a response. You can disable thinking by setting\n`thinkingBudget` to `0`. For more info on the `thinkingBudget` configuration\ndetails of the model, see the [thinking budgets documentation](https://ai.google.dev/gemini-api/docs/thinking#set-budget).\n\n### Python\n\n model = \"gemini-2.5-flash-native-audio-preview-12-2025\"\n\n config = types.LiveConnectConfig(\n response_modalities=[\"AUDIO\"]\n thinking_config=types.ThinkingConfig(\n thinking_budget=1024,\n )\n )\n\n async with client.aio.live.connect(model=model, config=config) as session:\n # Send audio input and receive audio\n\n### JavaScript\n\n const model = 'gemini-2.5-flash-native-audio-preview-12-2025';\n const config = {\n responseModalities: [Modality.AUDIO],\n thinkingConfig: {\n thinkingBudget: 1024,\n },\n };\n\n async function main() {\n\n const session = await ai.live.connect({\n model: model,\n config: config,\n callbacks: ...,\n });\n\n // Send audio input and receive audio\n\n session.close();\n }\n\n main();\n\nAdditionally, you can enable thought summaries by setting `includeThoughts` to\n`true` in your configuration. See [thought summaries](https://ai.google.dev/gemini-api/docs/thinking#summaries)\nfor more info:\n\n### Python\n\n model = \"gemini-2.5-flash-native-audio-preview-12-2025\"\n\n config = types.LiveConnectConfig(\n response_modalities=[\"AUDIO\"]\n thinking_config=types.ThinkingConfig(\n thinking_budget=1024,\n include_thoughts=True\n )\n )\n\n### JavaScript\n\n const model = 'gemini-2.5-flash-native-audio-preview-12-2025';\n const config = {\n responseModalities: [Modality.AUDIO],\n thinkingConfig: {\n thinkingBudget: 1024,\n includeThoughts: true,\n },\n };\n\n## Voice Activity Detection (VAD)\n\nVoice Activity Detection (VAD) allows the model to recognize when a person is\nspeaking. This is essential for creating natural conversations, as it allows a\nuser to interrupt the model at any time.\n\nWhen VAD detects an interruption, the ongoing generation is canceled and\ndiscarded. Only the information already sent to the client is retained in the\nsession history. The server then sends a [`BidiGenerateContentServerContent`](https://ai.google.dev/api/live#bidigeneratecontentservercontent) message to report the interruption.\n\nThe Gemini server then discards any pending function calls and sends a\n`BidiGenerateContentServerContent` message with the IDs of the canceled calls.\n\n### Python\n\n async for response in session.receive():\n if response.server_content.interrupted is True:\n # The generation was interrupted\n\n # If realtime playback is implemented in your application,\n # you should stop playing audio and clear queued playback here.\n\n### JavaScript\n\n const turns = await handleTurn();\n\n for (const turn of turns) {\n if (turn.serverContent && turn.serverContent.interrupted) {\n // The generation was interrupted\n\n // If realtime playback is implemented in your application,\n // you should stop playing audio and clear queued playback here.\n }\n }\n\n### Automatic VAD\n\nBy default, the model automatically performs VAD on\na continuous audio input stream. VAD can be configured with the\n[`realtimeInputConfig.automaticActivityDetection`](https://ai.google.dev/api/live#RealtimeInputConfig.AutomaticActivityDetection)\nfield of the [setup configuration](https://ai.google.dev/api/live#BidiGenerateContentSetup).\n\nWhen the audio stream is paused for more than a second (for example,\nbecause the user switched off the microphone), an\n[`audioStreamEnd`](https://ai.google.dev/api/live#BidiGenerateContentRealtimeInput.FIELDS.bool.BidiGenerateContentRealtimeInput.audio_stream_end)\nevent should be sent to flush any cached audio. The client can resume sending\naudio data at any time.\n\n### Python\n\n # example audio file to try:\n # URL = \"https://storage.googleapis.com/generativeai-downloads/data/hello_are_you_there.pcm\"\n # !wget -q $URL -O sample.pcm\n import asyncio\n from pathlib import Path\n from google import genai\n from google.genai import types\n\n client = genai.Client()\n model = \"gemini-live-2.5-flash-preview\"\n\n config = {\"response_modalities\": [\"TEXT\"]}\n\n async def main():\n async with client.aio.live.connect(model=model, config=config) as session:\n audio_bytes = Path(\"sample.pcm\").read_bytes()\n\n await session.send_realtime_input(\n audio=types.Blob(data=audio_bytes, mime_type=\"audio/pcm;rate=16000\")\n )\n\n # if stream gets paused, send:\n # await session.send_realtime_input(audio_stream_end=True)\n\n async for response in session.receive():\n if response.text is not None:\n print(response.text)\n\n if __name__ == \"__main__\":\n asyncio.run(main())\n\n### JavaScript\n\n // example audio file to try:\n // URL = \"https://storage.googleapis.com/generativeai-downloads/data/hello_are_you_there.pcm\"\n // !wget -q $URL -O sample.pcm\n import { GoogleGenAI, Modality } from '@google/genai';\n import * as fs from \"node:fs\";\n\n const ai = new GoogleGenAI({});\n const model = 'gemini-live-2.5-flash-preview';\n const config = { responseModalities: [Modality.TEXT] };\n\n async function live() {\n const responseQueue = [];\n\n async function waitMessage() {\n let done = false;\n let message = undefined;\n while (!done) {\n message = responseQueue.shift();\n if (message) {\n done = true;\n } else {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n return message;\n }\n\n async function handleTurn() {\n const turns = [];\n let done = false;\n while (!done) {\n const message = await waitMessage();\n turns.push(message);\n if (message.serverContent && message.serverContent.turnComplete) {\n done = true;\n }\n }\n return turns;\n }\n\n const session = await ai.live.connect({\n model: model,\n callbacks: {\n onopen: function () {\n console.debug('Opened');\n },\n onmessage: function (message) {\n responseQueue.push(message);\n },\n onerror: function (e) {\n console.debug('Error:', e.message);\n },\n onclose: function (e) {\n console.debug('Close:', e.reason);\n },\n },\n config: config,\n });\n\n // Send Audio Chunk\n const fileBuffer = fs.readFileSync(\"sample.pcm\");\n const base64Audio = Buffer.from(fileBuffer).toString('base64');\n\n session.sendRealtimeInput(\n {\n audio: {\n data: base64Audio,\n mimeType: \"audio/pcm;rate=16000\"\n }\n }\n\n );\n\n // if stream gets paused, send:\n // session.sendRealtimeInput({ audioStreamEnd: true })\n\n const turns = await handleTurn();\n for (const turn of turns) {\n if (turn.text) {\n console.debug('Received text: %s\\n', turn.text);\n }\n else if (turn.data) {\n console.debug('Received inline data: %s\\n', turn.data);\n }\n }\n\n session.close();\n }\n\n async function main() {\n await live().catch((e) => console.error('got error', e));\n }\n\n main();\n\nWith `send_realtime_input`, the API will respond to audio automatically based\non VAD. While `send_client_content` adds messages to the model context in\norder, `send_realtime_input` is optimized for responsiveness at the expense of\ndeterministic ordering.\n\n### Automatic VAD configuration\n\nFor more control over the VAD activity, you can configure the following\nparameters. See [API reference](https://ai.google.dev/api/live#automaticactivitydetection) for more\ninfo.\n\n### Python\n\n from google.genai import types\n\n config = {\n \"response_modalities\": [\"TEXT\"],\n \"realtime_input_config\": {\n \"automatic_activity_detection\": {\n \"disabled\": False, # default\n \"start_of_speech_sensitivity\": types.StartSensitivity.START_SENSITIVITY_LOW,\n \"end_of_speech_sensitivity\": types.EndSensitivity.END_SENSITIVITY_LOW,\n \"prefix_padding_ms\": 20,\n \"silence_duration_ms\": 100,\n }\n }\n }\n\n### JavaScript\n\n import { GoogleGenAI, Modality, StartSensitivity, EndSensitivity } from '@google/genai';\n\n const config = {\n responseModalities: [Modality.TEXT],\n realtimeInputConfig: {\n automaticActivityDetection: {\n disabled: false, // default\n startOfSpeechSensitivity: StartSensitivity.START_SENSITIVITY_LOW,\n endOfSpeechSensitivity: EndSensitivity.END_SENSITIVITY_LOW,\n prefixPaddingMs: 20,\n silenceDurationMs: 100,\n }\n }\n };\n\n### Disable automatic VAD\n\nAlternatively, the automatic VAD can be disabled by setting\n`realtimeInputConfig.automaticActivityDetection.disabled` to `true` in the setup\nmessage. In this configuration the client is responsible for detecting user\nspeech and sending\n[`activityStart`](https://ai.google.dev/api/live#BidiGenerateContentRealtimeInput.FIELDS.BidiGenerateContentRealtimeInput.ActivityStart.BidiGenerateContentRealtimeInput.activity_start)\nand [`activityEnd`](https://ai.google.dev/api/live#BidiGenerateContentRealtimeInput.FIELDS.BidiGenerateContentRealtimeInput.ActivityEnd.BidiGenerateContentRealtimeInput.activity_end)\nmessages at the appropriate times. An `audioStreamEnd` isn't sent in\nthis configuration. Instead, any interruption of the stream is marked by\nan `activityEnd` message.\n\n### Python\n\n config = {\n \"response_modalities\": [\"TEXT\"],\n \"realtime_input_config\": {\"automatic_activity_detection\": {\"disabled\": True}},\n }\n\n async with client.aio.live.connect(model=model, config=config) as session:\n # ...\n await session.send_realtime_input(activity_start=types.ActivityStart())\n await session.send_realtime_input(\n audio=types.Blob(data=audio_bytes, mime_type=\"audio/pcm;rate=16000\")\n )\n await session.send_realtime_input(activity_end=types.ActivityEnd())\n # ...\n\n### JavaScript\n\n const config = {\n responseModalities: [Modality.TEXT],\n realtimeInputConfig: {\n automaticActivityDetection: {\n disabled: true,\n }\n }\n };\n\n session.sendRealtimeInput({ activityStart: {} })\n\n session.sendRealtimeInput(\n {\n audio: {\n data: base64Audio,\n mimeType: \"audio/pcm;rate=16000\"\n }\n }\n\n );\n\n session.sendRealtimeInput({ activityEnd: {} })\n\n## Token count\n\nYou can find the total number of consumed tokens in the\n[usageMetadata](https://ai.google.dev/api/live#usagemetadata) field of the returned server message.\n\n### Python\n\n async for message in session.receive():\n # The server will periodically send messages that include UsageMetadata.\n if message.usage_metadata:\n usage = message.usage_metadata\n print(\n f\"Used {usage.total_token_count} tokens in total. Response token breakdown:\"\n )\n for detail in usage.response_tokens_details:\n match detail:\n case types.ModalityTokenCount(modality=modality, token_count=count):\n print(f\"{modality}: {count}\")\n\n### JavaScript\n\n const turns = await handleTurn();\n\n for (const turn of turns) {\n if (turn.usageMetadata) {\n console.debug('Used %s tokens in total. Response token breakdown:\\n', turn.usageMetadata.totalTokenCount);\n\n for (const detail of turn.usageMetadata.responseTokensDetails) {\n console.debug('%s\\n', detail);\n }\n }\n }\n\n## Media resolution\n\nYou can specify the media resolution for the input media by setting the\n`mediaResolution` field as part of the session configuration:\n\n### Python\n\n from google.genai import types\n\n config = {\n \"response_modalities\": [\"AUDIO\"],\n \"media_resolution\": types.MediaResolution.MEDIA_RESOLUTION_LOW,\n }\n\n### JavaScript\n\n import { GoogleGenAI, Modality, MediaResolution } from '@google/genai';\n\n const config = {\n responseModalities: [Modality.TEXT],\n mediaResolution: MediaResolution.MEDIA_RESOLUTION_LOW,\n };\n\n## Limitations\n\nConsider the following limitations of the Live API\nwhen you plan your project.\n\n### Response modalities\n\nYou can only set one response modality (`TEXT` or `AUDIO`) per session in the\nsession configuration. Setting both results in a config error message. This\nmeans that you can configure the model to respond with either text or audio,\nbut not both in the same session.\n\n### Client authentication\n\nThe Live API only provides server-to-server authentication\nby default. If you're implementing your Live API application\nusing a [client-to-server approach](https://ai.google.dev/gemini-api/docs/live#implementation-approach), you need to use\n[ephemeral tokens](https://ai.google.dev/gemini-api/docs/ephemeral-tokens) to mitigate security\nrisks.\n\n### Session duration\n\nAudio-only sessions are limited to 15 minutes,\nand audio plus video sessions are limited to 2 minutes.\nHowever, you can configure different [session management techniques](https://ai.google.dev/gemini-api/docs/live-session) for unlimited extensions on session duration.\n\n### Context window\n\nA session has a context window limit of:\n\n- 128k tokens for [native audio output](https://ai.google.dev/gemini-api/docs/live-guide#native-audio-output) models\n- 32k tokens for other Live API models\n\n## Supported languages\n\nLive API supports the following 70 languages.\n\n> [!NOTE]\n> **Note:** [Native audio output](https://ai.google.dev/gemini-api/docs/live-guide#native-audio-output) models can switch between languages naturally during conversation. You can also restrict the languages it speaks in by specifying it in the system instructions.\n\n| Language | BCP-47 Code | Language | BCP-47 Code |\n|---|---|---|---|\n| Afrikaans | `af` | Kannada | `kn` |\n| Albanian | `sq` | Kazakh | `kk` |\n| Amharic | `am` | Khmer | `km` |\n| Arabic | `ar` | Korean | `ko` |\n| Armenian | `hy` | Lao | `lo` |\n| Assamese | `as` | Latvian | `lv` |\n| Azerbaijani | `az` | Lithuanian | `lt` |\n| Basque | `eu` | Macedonian | `mk` |\n| Belarusian | `be` | Malay | `ms` |\n| Bengali | `bn` | Malayalam | `ml` |\n| Bosnian | `bs` | Marathi | `mr` |\n| Bulgarian | `bg` | Mongolian | `mn` |\n| Catalan | `ca` | Nepali | `ne` |\n| Chinese | `zh` | Norwegian | `no` |\n| Croatian | `hr` | Odia | `or` |\n| Czech | `cs` | Polish | `pl` |\n| Danish | `da` | Portuguese | `pt` |\n| Dutch | `nl` | Punjabi | `pa` |\n| English | `en` | Romanian | `ro` |\n| Estonian | `et` | Russian | `ru` |\n| Filipino | `fil` | Serbian | `sr` |\n| Finnish | `fi` | Slovak | `sk` |\n| French | `fr` | Slovenian | `sl` |\n| Galician | `gl` | Spanish | `es` |\n| Georgian | `ka` | Swahili | `sw` |\n| German | `de` | Swedish | `sv` |\n| Greek | `el` | Tamil | `ta` |\n| Gujarati | `gu` | Telugu | `te` |\n| Hebrew | `iw` | Thai | `th` |\n| Hindi | `hi` | Turkish | `tr` |\n| Hungarian | `hu` | Ukrainian | `uk` |\n| Icelandic | `is` | Urdu | `ur` |\n| Indonesian | `id` | Uzbek | `uz` |\n| Italian | `it` | Vietnamese | `vi` |\n| Japanese | `ja` | Zulu | `zu` |\n\n## What's next\n\n- Read the [Tool Use](https://ai.google.dev/gemini-api/docs/live-tools) and [Session Management](https://ai.google.dev/gemini-api/docs/live-session) guides for essential information on using the Live API effectively.\n- Try the Live API in [Google AI Studio](https://aistudio.google.com/app/live).\n- For more info about the Live API models, see [Gemini 2.5 Flash Native Audio](https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-live) on the Models page.\n- Try more examples in the [Live API cookbook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started_LiveAPI.ipynb), the [Live API Tools cookbook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started_LiveAPI_tools.ipynb), and the [Live API Get Started script](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Get_started_LiveAPI.py)."
3}