Gemini Live API Web Console

repository·main·Indexed 23 days ago

https://github.com/google-gemini/live-api-web-console

A React-based starter application for interacting with the Gemini Multimodal Live API over WebSockets. It features built-in modules for audio streaming, media recording (microphone, webcam, screen), and development logging. The project includes the GenAILiveClient for WebSocket management, the useLiveAPI hook for React state management, and utility classes like AudioRecorder and AudioStreamer for handling PCM16 audio data.

Tokens
3.5K
Snippets
8
Records
24
Agent score
82%

What's inside live-api-web-console

  1. Handle tool calls with the Live API client

    main

    The client instance provided by useLiveAPIContext is an event emitter. To respond to model-generated tool calls (like function calling), listen for the toolcall event using client.on('toolcall', callback).

    In the callback, you can inspect toolCall.functionCalls to identify which function the model wants to execute and access its arguments.

    useEffect(() => {
      const onToolCall = (toolCall: ToolCall) => {
        const fc = toolCall.functionCalls.find(
          (fc) => fc.name === "your_function_name"
        );
        if (fc) {
          const args = fc.args as any;
          // Handle function logic here
        }
      };
    
      client.on("toolcall", onToolCall);
      return () => {
        client.off("toolcall", onToolCall);
      };
    }, [client]);
  2. Use the useLiveAPIContext hook to configure the Live API

    main

    The useLiveAPIContext hook provides access to the client (an event-emitting websocket client) and a setConfig function. Use setConfig to define the model, system instructions, and tools (such as Google Search or function declarations) for the session.

    Common configuration keys include:

    • model: The model identifier (e.g., models/gemini-2.0-flash-exp).
    • systemInstruction: An object containing parts with text instructions.
    • tools: An array of tool objects, such as { googleSearch: {} } or { functionDeclarations: [...] }.
    import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
    
    // Inside a component:
    const { client, setConfig } = useLiveAPIContext();
    
    useEffect(() => {
      setConfig({
        model: "models/gemini-2.0-flash-exp",
        systemInstruction: {
          parts: [{ text: 'Your instructions here' }],
        },
        tools: [{ googleSearch: {} }],
      });
    }, [setConfig]);
  3. Available npm scripts

    main

    The project provides the following scripts for development and production:

    • npm start: Runs the application in development mode at http://localhost:3000. The page reloads on edits.
    • npm run build: Builds the application for production, creating a minified and optimized bundle in the build folder.
    npm start
    npm run build
  4. Use AudioStreamer to stream PCM16 audio

    main

    The AudioStreamer class manages the playback of raw PCM16 audio data using the Web Audio API. It handles converting Uint8Array chunks of PCM16 data into Float32Array buffers, queuing them, and scheduling playback to ensure smooth streaming.

    Key Workflow

    1. Initialize: Create an instance by passing an existing AudioContext.
    2. Resume: Call resume() (typically in response to a user interaction) to unblock the AudioContext and prepare the stream.
    3. Feed Data: Use addPCM16(chunk) to push new Uint8Array chunks of PCM16 data into the playback queue.
    4. Stop: Call stop() to clear the queue and fade out the audio.

    PCM16 Conversion

    The class automatically converts 16-bit signed integer PCM data (normalized between -32768 and 32767) to the Float32 format expected by the Web Audio API.

  5. Send real-time media input with sendRealtimeInput

    main

    To stream real-time multimodal data (like audio or video frames) to the model, use sendRealtimeInput. This method accepts chunks of media data.

    Parameters:

    • chunks: An array of objects containing mimeType (e.g., audio/pcm or image/jpeg) and data (a base64 encoded string).

    This is typically used for continuous streaming of audio or video frames to maintain a live interaction.

  6. Use GenAILiveClient to interact with the Gemini Multimodal Live API

    main

    The GenAILiveClient class manages a WebSocket connection to the Gemini Multimodal Live API. It extends EventEmitter to provide a reactive interface for handling real-time audio, content, and tool calls. You can use this class in non-React environments by listening to its emitted events.

    Connection Lifecycle

    1. Initialize: Create an instance with LiveClientOptions (which wraps GoogleGenAI configuration).
    2. Connect: Call connect(model, config) with the target model string and a LiveConnectConfig object.
    3. Interact: Use send(), sendRealtimeInput(), or sendToolResponse() to communicate with the model.
    4. Disconnect: Call disconnect() to close the session.