Tool use with Live API

टूल इस्तेमाल करने की सुविधा की मदद से, Live API सिर्फ़ बातचीत करने के अलावा और भी काम कर सकता है. जैसे, रीयल-टाइम में बातचीत करते हुए, बाहरी कॉन्टेक्स्ट को शामिल करना और रीयल-टाइम में कार्रवाई करना. लाइव एपीआई की मदद से, फ़ंक्शन कॉलिंग, कोड एक्ज़ीक्यूशन, और Google Search जैसे टूल तय किए जा सकते हैं.

इस्तेमाल किए जा सकने वाले टूल के बारे में खास जानकारी

यहां हर मॉडल के लिए उपलब्ध टूल के बारे में खास जानकारी दी गई है:

टूल कैस्केड किए गए मॉडल
gemini-live-2.5-flash-preview
gemini-2.0-flash-live-001
gemini-2.5-flash-preview-native-audio-dialog gemini-2.5-flash-exp-native-audio-thinking-dialog
खोजें हां हां हां
फ़ंक्शन कॉलिंग हां हां नहीं
कोड चलाने की सुविधा हां नहीं नहीं
यूआरएल का कॉन्टेक्स्ट हां नहीं नहीं

फ़ंक्शन कॉल करने की सुविधा

लाइव एपीआई, फ़ंक्शन कॉलिंग की सुविधा के साथ काम करता है. यह सुविधा, कॉन्टेंट जनरेट करने के सामान्य अनुरोधों की तरह ही काम करती है. फ़ंक्शन कॉलिंग की सुविधा की मदद से, Live API बाहरी डेटा और प्रोग्राम के साथ इंटरैक्ट कर सकता है. इससे आपके ऐप्लिकेशन की क्षमताओं में काफ़ी बढ़ोतरी होती है.

सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर, फ़ंक्शन के एलान तय किए जा सकते हैं. टूल कॉल मिलने के बाद, क्लाइंट को session.send_tool_response तरीके का इस्तेमाल करके, FunctionResponse ऑब्जेक्ट की सूची के साथ जवाब देना चाहिए.

ज़्यादा जानने के लिए, फ़ंक्शन कॉलिंग ट्यूटोरियल देखें.

Python

import asyncio
from google import genai
from google.genai import types

client = genai.Client()
model = "gemini-live-2.5-flash-preview"

# Simple function definitions
turn_on_the_lights = {"name": "turn_on_the_lights"}
turn_off_the_lights = {"name": "turn_off_the_lights"}

tools = [{"function_declarations": [turn_on_the_lights, turn_off_the_lights]}]
config = {"response_modalities": ["TEXT"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "Turn on the lights please"
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        async for chunk in session.receive():
            if chunk.server_content:
                if chunk.text is not None:
                    print(chunk.text)
            elif chunk.tool_call:
                function_responses = []
                for fc in chunk.tool_call.function_calls:
                    function_response = types.FunctionResponse(
                        id=fc.id,
                        name=fc.name,
                        response={ "result": "ok" } # simple, hard-coded function response
                    )
                    function_responses.append(function_response)

                await session.send_tool_response(function_responses=function_responses)

if __name__ == "__main__":
    asyncio.run(main())

JavaScript

import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';

// Simple function definitions
const turn_on_the_lights = { name: "turn_on_the_lights" } // , description: '...', parameters: { ... }
const turn_off_the_lights = { name: "turn_off_the_lights" }

const tools = [{ functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }]

const config = {
  responseModalities: [Modality.TEXT],
  tools: tools
}

async function live() {
  const responseQueue = [];

  async function waitMessage() {
    let done = false;
    let message = undefined;
    while (!done) {
      message = responseQueue.shift();
      if (message) {
        done = true;
      } else {
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
    }
    return message;
  }

  async function handleTurn() {
    const turns = [];
    let done = false;
    while (!done) {
      const message = await waitMessage();
      turns.push(message);
      if (message.serverContent && message.serverContent.turnComplete) {
        done = true;
      } else if (message.toolCall) {
        done = true;
      }
    }
    return turns;
  }

  const session = await ai.live.connect({
    model: model,
    callbacks: {
      onopen: function () {
        console.debug('Opened');
      },
      onmessage: function (message) {
        responseQueue.push(message);
      },
      onerror: function (e) {
        console.debug('Error:', e.message);
      },
      onclose: function (e) {
        console.debug('Close:', e.reason);
      },
    },
    config: config,
  });

  const inputTurns = 'Turn on the lights please';
  session.sendClientContent({ turns: inputTurns });

  let turns = await handleTurn();

  for (const turn of turns) {
    if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
      for (const part of turn.serverContent.modelTurn.parts) {
        if (part.text) {
          console.debug('Received text: %s\n', part.text);
        }
      }
    }
    else if (turn.toolCall) {
      const functionResponses = [];
      for (const fc of turn.toolCall.functionCalls) {
        functionResponses.push({
          id: fc.id,
          name: fc.name,
          response: { result: "ok" } // simple, hard-coded function response
        });
      }

      console.debug('Sending tool response...\n');
      session.sendToolResponse({ functionResponses: functionResponses });
    }
  }

  // Check again for new messages
  turns = await handleTurn();

  for (const turn of turns) {
    if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
      for (const part of turn.serverContent.modelTurn.parts) {
        if (part.text) {
          console.debug('Received text: %s\n', part.text);
        }
      }
    }
  }

  session.close();
}

async function main() {
  await live().catch((e) => console.error('got error', e));
}

main();

एक ही प्रॉम्प्ट से, मॉडल कई फ़ंक्शन कॉल जनरेट कर सकता है. साथ ही, उनके आउटपुट को एक साथ जोड़ने के लिए ज़रूरी कोड भी जनरेट कर सकता है. यह कोड, सैंडबॉक्स एनवायरमेंट में काम करता है. इससे BidiGenerateContentToolCall मैसेज जनरेट होते हैं.

एसिंक्रोनस फ़ंक्शन कॉलिंग

फ़ंक्शन कॉलिंग डिफ़ॉल्ट रूप से क्रम से काम करती है. इसका मतलब है कि हर फ़ंक्शन कॉल के नतीजे उपलब्ध होने तक, एक्ज़ीक्यूशन रुक जाता है. इससे यह पक्का होता है कि फ़ंक्शन को क्रम से प्रोसेस किया जाए. इसका मतलब है कि फ़ंक्शन के चालू रहने के दौरान, मॉडल के साथ इंटरैक्ट नहीं किया जा सकेगा.

अगर आपको बातचीत को ब्लॉक नहीं करना है, तो मॉडल को एसिंक्रोनस तरीके से फ़ंक्शन चलाने के लिए कहा जा सकता है. इसके लिए, आपको फ़ंक्शन की परिभाषाओं में behavior जोड़ना होगा:

Python

  # Non-blocking function definitions
  turn_on_the_lights = {"name": "turn_on_the_lights", "behavior": "NON_BLOCKING"} # turn_on_the_lights will run asynchronously
  turn_off_the_lights = {"name": "turn_off_the_lights"} # turn_off_the_lights will still pause all interactions with the model

JavaScript

import { GoogleGenAI, Modality, Behavior } from '@google/genai';

// Non-blocking function definitions
const turn_on_the_lights = {name: "turn_on_the_lights", behavior: Behavior.NON_BLOCKING}

// Blocking function definitions
const turn_off_the_lights = {name: "turn_off_the_lights"}

const tools = [{ functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }]

NON-BLOCKING यह पक्का करता है कि फ़ंक्शन एसिंक्रोनस तरीके से काम करे, ताकि मॉडल के साथ इंटरैक्ट किया जा सके.

इसके बाद, आपको मॉडल को यह बताना होगा कि scheduling पैरामीटर का इस्तेमाल करके, FunctionResponse मिलने पर उसे कैसा व्यवहार करना चाहिए. यह इनमें से कोई एक काम कर सकता है:

  • यह जो भी काम कर रहा है उसे रोककर, आपको तुरंत जवाब दे सकता है (scheduling="INTERRUPT"),
  • scheduling="WHEN_IDLE" के अभी चल रहे प्रोग्राम के खत्म होने का इंतज़ार करें,
  • या कुछ न करें और उस जानकारी का इस्तेमाल बाद में बातचीत में करें (scheduling="SILENT")

Python

# for a non-blocking function definition, apply scheduling in the function response:
  function_response = types.FunctionResponse(
      id=fc.id,
      name=fc.name,
      response={
          "result": "ok",
          "scheduling": "INTERRUPT" # Can also be WHEN_IDLE or SILENT
      }
  )

JavaScript

import { GoogleGenAI, Modality, Behavior, FunctionResponseScheduling } from '@google/genai';

// for a non-blocking function definition, apply scheduling in the function response:
const functionResponse = {
  id: fc.id,
  name: fc.name,
  response: {
    result: "ok",
    scheduling: FunctionResponseScheduling.INTERRUPT  // Can also be WHEN_IDLE or SILENT
  }
}

कोड को एक्ज़ीक्यूट करना

सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर, कोड को लागू करने की प्रोसेस तय की जा सकती है. इससे Live API, Python कोड जनरेट और एक्ज़ीक्यूट कर पाता है. साथ ही, आपके नतीजों को बेहतर बनाने के लिए, डाइनैमिक तरीके से कैलकुलेशन कर पाता है. ज़्यादा जानने के लिए, कोड एक्ज़ीक्यूट करने का ट्यूटोरियल देखें.

Python

import asyncio
from google import genai
from google.genai import types

client = genai.Client()
model = "gemini-live-2.5-flash-preview"

tools = [{'code_execution': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "Compute the largest prime palindrome under 100000."
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        async for chunk in session.receive():
            if chunk.server_content:
                if chunk.text is not None:
                    print(chunk.text)

                model_turn = chunk.server_content.model_turn
                if model_turn:
                    for part in model_turn.parts:
                      if part.executable_code is not None:
                        print(part.executable_code.code)

                      if part.code_execution_result is not None:
                        print(part.code_execution_result.output)

if __name__ == "__main__":
    asyncio.run(main())

JavaScript

import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';

const tools = [{codeExecution: {}}]
const config = {
  responseModalities: [Modality.TEXT],
  tools: tools
}

async function live() {
  const responseQueue = [];

  async function waitMessage() {
    let done = false;
    let message = undefined;
    while (!done) {
      message = responseQueue.shift();
      if (message) {
        done = true;
      } else {
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
    }
    return message;
  }

  async function handleTurn() {
    const turns = [];
    let done = false;
    while (!done) {
      const message = await waitMessage();
      turns.push(message);
      if (message.serverContent && message.serverContent.turnComplete) {
        done = true;
      } else if (message.toolCall) {
        done = true;
      }
    }
    return turns;
  }

  const session = await ai.live.connect({
    model: model,
    callbacks: {
      onopen: function () {
        console.debug('Opened');
      },
      onmessage: function (message) {
        responseQueue.push(message);
      },
      onerror: function (e) {
        console.debug('Error:', e.message);
      },
      onclose: function (e) {
        console.debug('Close:', e.reason);
      },
    },
    config: config,
  });

  const inputTurns = 'Compute the largest prime palindrome under 100000.';
  session.sendClientContent({ turns: inputTurns });

  const turns = await handleTurn();

  for (const turn of turns) {
    if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
      for (const part of turn.serverContent.modelTurn.parts) {
        if (part.text) {
          console.debug('Received text: %s\n', part.text);
        }
        else if (part.executableCode) {
          console.debug('executableCode: %s\n', part.executableCode.code);
        }
        else if (part.codeExecutionResult) {
          console.debug('codeExecutionResult: %s\n', part.codeExecutionResult.output);
        }
      }
    }
  }

  session.close();
}

async function main() {
  await live().catch((e) => console.error('got error', e));
}

main();

सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर, Google Search की मदद से जानकारी पाने की सुविधा चालू की जा सकती है. इससे Live API के जवाब ज़्यादा सटीक होते हैं और वह गलत जानकारी नहीं देता. ज़्यादा जानने के लिए, ग्राउंडिंग ट्यूटोरियल देखें.

Python

import asyncio
from google import genai
from google.genai import types

client = genai.Client()
model = "gemini-live-2.5-flash-preview"

tools = [{'google_search': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "When did the last Brazil vs. Argentina soccer match happen?"
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        async for chunk in session.receive():
            if chunk.server_content:
                if chunk.text is not None:
                    print(chunk.text)

                # The model might generate and execute Python code to use Search
                model_turn = chunk.server_content.model_turn
                if model_turn:
                    for part in model_turn.parts:
                      if part.executable_code is not None:
                        print(part.executable_code.code)

                      if part.code_execution_result is not None:
                        print(part.code_execution_result.output)

if __name__ == "__main__":
    asyncio.run(main())

JavaScript

import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';

const tools = [{googleSearch: {}}]
const config = {
  responseModalities: [Modality.TEXT],
  tools: tools
}

async function live() {
  const responseQueue = [];

  async function waitMessage() {
    let done = false;
    let message = undefined;
    while (!done) {
      message = responseQueue.shift();
      if (message) {
        done = true;
      } else {
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
    }
    return message;
  }

  async function handleTurn() {
    const turns = [];
    let done = false;
    while (!done) {
      const message = await waitMessage();
      turns.push(message);
      if (message.serverContent && message.serverContent.turnComplete) {
        done = true;
      } else if (message.toolCall) {
        done = true;
      }
    }
    return turns;
  }

  const session = await ai.live.connect({
    model: model,
    callbacks: {
      onopen: function () {
        console.debug('Opened');
      },
      onmessage: function (message) {
        responseQueue.push(message);
      },
      onerror: function (e) {
        console.debug('Error:', e.message);
      },
      onclose: function (e) {
        console.debug('Close:', e.reason);
      },
    },
    config: config,
  });

  const inputTurns = 'When did the last Brazil vs. Argentina soccer match happen?';
  session.sendClientContent({ turns: inputTurns });

  const turns = await handleTurn();

  for (const turn of turns) {
    if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
      for (const part of turn.serverContent.modelTurn.parts) {
        if (part.text) {
          console.debug('Received text: %s\n', part.text);
        }
        else if (part.executableCode) {
          console.debug('executableCode: %s\n', part.executableCode.code);
        }
        else if (part.codeExecutionResult) {
          console.debug('codeExecutionResult: %s\n', part.codeExecutionResult.output);
        }
      }
    }
  }

  session.close();
}

async function main() {
  await live().catch((e) => console.error('got error', e));
}

main();

एक से ज़्यादा टूल का इस्तेमाल करना

लाइव एपीआई में एक से ज़्यादा टूल इस्तेमाल किए जा सकते हैं. इससे आपके ऐप्लिकेशन की क्षमताओं को और भी बढ़ाया जा सकता है:

Python

prompt = """
Hey, I need you to do three things for me.

1. Compute the largest prime palindrome under 100000.
2. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024?
3. Turn on the lights

Thanks!
"""

tools = [
    {"google_search": {}},
    {"code_execution": {}},
    {"function_declarations": [turn_on_the_lights, turn_off_the_lights]},
]

config = {"response_modalities": ["TEXT"], "tools": tools}

# ... remaining model call

JavaScript

const prompt = `Hey, I need you to do three things for me.

1. Compute the largest prime palindrome under 100000.
2. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024?
3. Turn on the lights

Thanks!
`

const tools = [
  { googleSearch: {} },
  { codeExecution: {} },
  { functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }
]

const config = {
  responseModalities: [Modality.TEXT],
  tools: tools
}

// ... remaining model call

आगे क्या करना है