Gemini API की मदद से फ़ंक्शन कॉल करना

फ़ंक्शन कॉल करने की सुविधा की मदद से, मॉडल को बाहरी टूल और एपीआई से कनेक्ट किया जा सकता है. टेक्स्ट के जवाब जनरेट करने के बजाय, मॉडल यह तय करता है कि किसी खास फ़ंक्शन को कब कॉल करना है. साथ ही, असल दुनिया में होने वाली कार्रवाइयों को पूरा करने के लिए ज़रूरी पैरामीटर भी उपलब्ध कराता है. इससे मॉडल, सामान्य भाषा और असल दुनिया की कार्रवाइयों और डेटा के बीच एक ब्रिज के तौर पर काम कर पाता है. फ़ंक्शन कॉल करने के तीन मुख्य इस्तेमाल के उदाहरण हैं:

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

फ़ंक्शन कॉलिंग की सुविधा कैसे काम करती है

फ़ंक्शन कॉल करने के बारे में खास जानकारी

फ़ंक्शन कॉल करने में, आपके ऐप्लिकेशन, मॉडल, और बाहरी फ़ंक्शन के बीच स्ट्रक्चर्ड इंटरैक्शन शामिल होता है. इस प्रोसेस के बारे में यहां बताया गया है:

  1. फ़ंक्शन का एलान करना: अपने ऐप्लिकेशन कोड में फ़ंक्शन का एलान करें. फ़ंक्शन के एलान से, मॉडल के लिए फ़ंक्शन का नाम, पैरामीटर, और मकसद के बारे में पता चलता है.
  2. फ़ंक्शन के एलान के साथ एलएलएम को कॉल करना: मॉडल को फ़ंक्शन के एलान के साथ उपयोगकर्ता प्रॉम्प्ट भेजें. यह अनुरोध का विश्लेषण करता है और यह तय करता है कि फ़ंक्शन कॉल मददगार होगा या नहीं. अगर ऐसा है, तो यह स्ट्रक्चर्ड JSON ऑब्जेक्ट के साथ जवाब देता है.
  3. फ़ंक्शन कोड को लागू करना (आपकी ज़िम्मेदारी): मॉडल, फ़ंक्शन को खुद नहीं लागू करता. जवाब को प्रोसेस करने और फ़ंक्शन कॉल की जांच करने की ज़िम्मेदारी आपके ऐप्लिकेशन की है. ऐसा तब करना होगा, जब
    • हां: फ़ंक्शन का नाम और आर्ग्युमेंट निकालें और अपने ऐप्लिकेशन में उससे जुड़े फ़ंक्शन को चलाएं.
    • नहीं: मॉडल ने प्रॉम्प्ट के लिए सीधे टेक्स्ट का जवाब दिया है (उदाहरण में इस फ़्लो पर ज़्यादा ध्यान नहीं दिया गया है, लेकिन यह एक संभावित नतीजा है).
  4. उपयोगकर्ता के हिसाब से जवाब दें: अगर कोई फ़ंक्शन लागू किया गया है, तो नतीजे को कैप्चर करें और बातचीत के अगले चरण में, उसे मॉडल को वापस भेजें. यह नतीजे का इस्तेमाल करके, उपयोगकर्ता के हिसाब से जवाब जनरेट करेगा. इसमें फ़ंक्शन कॉल की जानकारी शामिल होगी.

इस प्रोसेस को कई बार दोहराया जा सकता है. इससे जटिल इंटरैक्शन और वर्कफ़्लो की सुविधा मिलती है. यह मॉडल, एक ही बार में कई फ़ंक्शन (एक साथ कई फ़ंक्शन कॉल करना) और क्रम से (कई फ़ंक्शन कॉल करना) कॉल करने की सुविधा भी देता है.

पहला चरण: फ़ंक्शन का एलान करना

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

Python

# Define a function that the model can call to control smart lights
set_light_values_declaration = {
    "name": "set_light_values",
    "description": "Sets the brightness and color temperature of a light.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "integer",
                "description": "Light level from 0 to 100. Zero is off and 100 is full brightness",
            },
            "color_temp": {
                "type": "string",
                "enum": ["daylight", "cool", "warm"],
                "description": "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
            },
        },
        "required": ["brightness", "color_temp"],
    },
}

# This is the actual function that would be called based on the model's suggestion
def set_light_values(brightness: int, color_temp: str) -> dict[str, int | str]:
    """Set the brightness and color temperature of a room light. (mock API).

    Args:
        brightness: Light level from 0 to 100. Zero is off and 100 is full brightness
        color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.

    Returns:
        A dictionary containing the set brightness and color temperature.
    """
    return {"brightness": brightness, "colorTemperature": color_temp}

JavaScript

import { Type } from '@google/genai';

// Define a function that the model can call to control smart lights
const setLightValuesFunctionDeclaration = {
  name: 'set_light_values',
  description: 'Sets the brightness and color temperature of a light.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      brightness: {
        type: Type.NUMBER,
        description: 'Light level from 0 to 100. Zero is off and 100 is full brightness',
      },
      color_temp: {
        type: Type.STRING,
        enum: ['daylight', 'cool', 'warm'],
        description: 'Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.',
      },
    },
    required: ['brightness', 'color_temp'],
  },
};

/**

*   Set the brightness and color temperature of a room light. (mock API)
*   @param {number} brightness - Light level from 0 to 100. Zero is off and 100 is full brightness
*   @param {string} color_temp - Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
*   @return {Object} A dictionary containing the set brightness and color temperature.
*/
function setLightValues(brightness, color_temp) {
  return {
    brightness: brightness,
    colorTemperature: color_temp
  };
}

दूसरा चरण: फ़ंक्शन के एलान के साथ मॉडल को कॉल करना

फ़ंक्शन के एलान तय करने के बाद, मॉडल को उनका इस्तेमाल करने के लिए कहा जा सकता है. यह प्रॉम्प्ट और फ़ंक्शन के एलान का विश्लेषण करता है और यह तय करता है कि सीधे जवाब दिया जाए या किसी फ़ंक्शन को कॉल किया जाए. अगर किसी फ़ंक्शन को कॉल किया जाता है, तो रिस्पॉन्स ऑब्जेक्ट में फ़ंक्शन कॉल का सुझाव शामिल होगा.

Python

from google import genai
from google.genai import types

# Configure the client and tools
client = genai.Client(api_key="GOOGLE_API_KEY")
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])

# Define user prompt
contents = [
    types.Content(
        role="user", parts=[types.Part(text="Turn the lights down to a romantic level")]
    )
]

# Send request with function declarations
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=contents
    config=config,
)

print(response.candidates[0].content.parts[0].function_call)

JavaScript

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

// Generation Config with Function Declaration
const config = {
  tools: [{
    functionDeclarations: [setLightValuesFunctionDeclaration]
  }]
};

// Configure the client
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Define user prompt
const contents = [
  {
    role: 'user',
    parts: [{ text: 'Turn the lights down to a romantic level' }]
  }
];

// Send request with function declarations
const response = await ai.models.generateContent({
  model: 'gemini-2.0-flash',
  contents: contents,
  config: config
});

console.log(response.functionCalls[0]);

इसके बाद, मॉडल OpenAPI के साथ काम करने वाले स्कीमा में functionCall ऑब्जेक्ट दिखाता है. इसमें, उपयोगकर्ता के सवाल का जवाब देने के लिए, एलान किए गए एक या उससे ज़्यादा फ़ंक्शन को कॉल करने का तरीका बताया जाता है.

Python

id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'

JavaScript

{
  name: 'set_light_values',
  args: { brightness: 25, color_temp: 'warm' }
}

तीसरा चरण: set_light_values फ़ंक्शन कोड को लागू करना

मॉडल के रिस्पॉन्स से फ़ंक्शन कॉल की जानकारी निकालें, आर्ग्युमेंट को पार्स करें, और set_light_values फ़ंक्शन को लागू करें.

Python

# Extract tool call details, it may not be in the first part.
tool_call = response.candidates[0].content.parts[0].function_call

if tool_call.name == "set_light_values":
    result = set_light_values(**tool_call.args)
    print(f"Function execution result: {result}")

JavaScript

// Extract tool call details
const tool_call = response.functionCalls[0]

let result;
if (tool_call.name === 'set_light_values') {
  result = setLightValues(tool_call.args.brightness, tool_call.args.color_temp);
  console.log(`Function execution result: ${JSON.stringify(result)}`);
}

चौथा चरण: फ़ंक्शन के नतीजे के साथ उपयोगकर्ता के हिसाब से जवाब बनाएं और मॉडल को फिर से कॉल करें

आखिर में, फ़ंक्शन के इस्तेमाल का नतीजा मॉडल को भेजें, ताकि वह उपयोगकर्ता को दिए जाने वाले अपने आखिरी जवाब में इस जानकारी को शामिल कर सके.

Python

# Create a function response part
function_response_part = types.Part.from_function_response(
    name=tool_call.name,
    response={"result": result},
)

# Append function call and result of the function execution to contents
contents.append(response.candidates[0].content) # Append the content from the model's response.
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response

final_response = client.models.generate_content(
    model="gemini-2.0-flash",
    config=config,
    contents=contents,
)

print(final_response.text)

JavaScript

// Create a function response part
const function_response_part = {
  name: tool_call.name,
  response: { result }
}

// Append function call and result of the function execution to contents
contents.push(response.candidates[0].content);
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });

// Get the final response from the model
const final_response = await ai.models.generateContent({
  model: 'gemini-2.0-flash',
  contents: contents,
  config: config
});

console.log(final_response.text);

इससे, फ़ंक्शन को कॉल करने की प्रोसेस पूरी हो जाती है. उपयोगकर्ता के अनुरोध की कार्रवाई करने के लिए, मॉडल ने set_light_values फ़ंक्शन का इस्तेमाल किया.

फ़ंक्शन के एलान

प्रॉम्प्ट में फ़ंक्शन कॉल करने की सुविधा लागू करने पर, एक tools ऑब्जेक्ट बनता है. इसमें एक या उससे ज़्यादा function declarations होते हैं. आपने JSON का इस्तेमाल करके फ़ंक्शन तय किए हैं. खास तौर पर, OpenAPI स्कीमा फ़ॉर्मैट के चुने गए सबसेट के साथ. किसी एक फ़ंक्शन के एलान में ये पैरामीटर शामिल किए जा सकते हैं:

  • name (स्ट्रिंग): फ़ंक्शन (get_weather_forecast, send_email) का यूनीक नाम. जानकारी देने वाले नामों में स्पेस या खास वर्णों का इस्तेमाल न करें. इसके लिए, अंडरस्कोर या कैमलकेस का इस्तेमाल करें.
  • description (स्ट्रिंग): फ़ंक्शन के मकसद और सुविधाओं के बारे में साफ़ तौर पर और पूरी जानकारी. मॉडल के लिए यह समझना ज़रूरी है कि फ़ंक्शन का इस्तेमाल कब करना है. साफ़ तौर पर बताएं और अगर ज़रूरी हो, तो उदाहरण दें ("जगह के हिसाब से थिएटर ढूंढता है. इसके अलावा, फ़िलहाल थिएटर में चल रही फ़िल्म का टाइटल भी ढूंढ सकता है.").
  • parameters (ऑब्जेक्ट): उन इनपुट पैरामीटर के बारे में बताता है जिनकी ज़रूरत फ़ंक्शन को होती है.
    • type (स्ट्रिंग): यह पूरे डेटा टाइप के बारे में बताता है, जैसे कि object.
    • properties (ऑब्जेक्ट): अलग-अलग पैरामीटर की सूची बनाता है. हर पैरामीटर में ये चीज़ें होती हैं:
      • type (स्ट्रिंग): पैरामीटर का डेटा टाइप, जैसे कि string, integer, boolean, array.
      • description (स्ट्रिंग): पैरामीटर के मकसद और फ़ॉर्मैट की जानकारी. उदाहरण और पाबंदियां दें ("शहर और राज्य, उदाहरण के लिए, 'सैन फ़्रांसिस्को, कैलिफ़ोर्निया' या पिन कोड, जैसे कि '95616'.").
      • enum (कलेक्शन, ज़रूरी नहीं): अगर पैरामीटर की वैल्यू किसी तय सेट से हैं, तो "enum" का इस्तेमाल करके, वैल्यू की सूची बनाएं. इसके बजाय, ब्यौरे में सिर्फ़ वैल्यू के बारे में बताएं. इससे सटीक जानकारी मिलती है ("enum": ["daylight", "cool", "warm"]).
    • required (कलेक्शन): यह पैरामीटर के नामों की सूची वाली स्ट्रिंग का कलेक्शन होता है. फ़ंक्शन के काम करने के लिए, इन नामों की वैल्यू देना ज़रूरी होता है.

पैरलल फ़ंक्शन कॉलिंग

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

Python

power_disco_ball = {
    "name": "power_disco_ball",
    "description": "Powers the spinning disco ball.",
    "parameters": {
        "type": "object",
        "properties": {
            "power": {
                "type": "boolean",
                "description": "Whether to turn the disco ball on or off.",
            }
        },
        "required": ["power"],
    },
}

start_music = {
    "name": "start_music",
    "description": "Play some music matching the specified parameters.",
    "parameters": {
        "type": "object",
        "properties": {
            "energetic": {
                "type": "boolean",
                "description": "Whether the music is energetic or not.",
            },
            "loud": {
                "type": "boolean",
                "description": "Whether the music is loud or not.",
            },
        },
        "required": ["energetic", "loud"],
    },
}

dim_lights = {
    "name": "dim_lights",
    "description": "Dim the lights.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "number",
                "description": "The brightness of the lights, 0.0 is off, 1.0 is full.",
            }
        },
        "required": ["brightness"],
    },
}

JavaScript

import { Type } from '@google/genai';

const powerDiscoBall = {
  name: 'power_disco_ball',
  description: 'Powers the spinning disco ball.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      power: {
        type: Type.BOOLEAN,
        description: 'Whether to turn the disco ball on or off.'
      }
    },
    required: ['power']
  }
};

const startMusic = {
  name: 'start_music',
  description: 'Play some music matching the specified parameters.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      energetic: {
        type: Type.BOOLEAN,
        description: 'Whether the music is energetic or not.'
      },
      loud: {
        type: Type.BOOLEAN,
        description: 'Whether the music is loud or not.'
      }
    },
    required: ['energetic', 'loud']
  }
};

const dimLights = {
  name: 'dim_lights',
  description: 'Dim the lights.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      brightness: {
        type: Type.NUMBER,
        description: 'The brightness of the lights, 0.0 is off, 1.0 is full.'
      }
    },
    required: ['brightness']
  }
};

फ़ंक्शन कॉलिंग मोड को कॉन्फ़िगर करें, ताकि बताए गए सभी टूल इस्तेमाल किए जा सकें. ज़्यादा जानने के लिए, फ़ंक्शन कॉल करने की सुविधा को कॉन्फ़िगर करने के बारे में पढ़ें.

Python

from google import genai
from google.genai import types

# Configure the client and tools
client = genai.Client(api_key="GOOGLE_API_KEY")
house_tools = [
    types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]
config = types.GenerateContentConfig(
    tools=house_tools,
    automatic_function_calling=types.AutomaticFunctionCallingConfig(
        disable=True
    ),
    # Force the model to call 'any' function, instead of chatting.
    tool_config=types.ToolConfig(
        function_calling_config=types.FunctionCallingConfig(mode='ANY')
    ),
)

chat = client.chats.create(model="gemini-2.0-flash", config=config)
response = chat.send_message("Turn this place into a party!")

# Print out each of the function calls requested from this single call
print("Example 1: Forced function calling")
for fn in response.function_calls:
    args = ", ".join(f"{key}={val}" for key, val in fn.args.items())
    print(f"{fn.name}({args})")

JavaScript

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

// Set up function declarations
const houseFns = [powerDiscoBall, startMusic, dimLights];

const config = {
    tools: [{
        functionDeclarations: houseFns
    }],
    // Force the model to call 'any' function, instead of chatting.
    toolConfig: {
        functionCallingConfig: {
            mode: 'any'
        }
    }
};

// Configure the client
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Create a chat session
const chat = ai.chats.create({
    model: 'gemini-2.0-flash',
    config: config
});
const response = await chat.sendMessage({message: 'Turn this place into a party!'});

// Print out each of the function calls requested from this single call
console.log("Example 1: Forced function calling");
for (const fn of response.functionCalls) {
    const args = Object.entries(fn.args)
        .map(([key, val]) => `${key}=${val}`)
        .join(', ');
    console.log(`${fn.name}(${args})`);
}

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

Python SDK, फ़ंक्शन को अपने-आप कॉल करने की सुविधा देता है. यह सुविधा, Python फ़ंक्शन को अपने-आप एलान में बदल देती है. साथ ही, आपके लिए फ़ंक्शन कॉल को लागू करने और रिस्पॉन्स साइकल को मैनेज करती है. डिस्को के इस्तेमाल का उदाहरण यहां दिया गया है.

Python

from google import genai
from google.genai import types

# Actual function implementations
def power_disco_ball_impl(power: bool) -> dict:
    """Powers the spinning disco ball.

    Args:
        power: Whether to turn the disco ball on or off.

    Returns:
        A status dictionary indicating the current state.
    """
    return {"status": f"Disco ball powered {'on' if power else 'off'}"}

def start_music_impl(energetic: bool, loud: bool) -> dict:
    """Play some music matching the specified parameters.

    Args:
        energetic: Whether the music is energetic or not.
        loud: Whether the music is loud or not.

    Returns:
        A dictionary containing the music settings.
    """
    music_type = "energetic" if energetic else "chill"
    volume = "loud" if loud else "quiet"
    return {"music_type": music_type, "volume": volume}

def dim_lights_impl(brightness: float) -> dict:
    """Dim the lights.

    Args:
        brightness: The brightness of the lights, 0.0 is off, 1.0 is full.

    Returns:
        A dictionary containing the new brightness setting.
    """
    return {"brightness": brightness}

# Configure the client
client = genai.Client(api_key="GOOGLE_API_KEY")
config = types.GenerateContentConfig(
    tools=[power_disco_ball_impl, start_music_impl, dim_lights_impl]
)

# Make the request
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Do everything you need to this place into party!",
    config=config,
)

print("\nExample 2: Automatic function calling")
print(response.text)
# I've turned on the disco ball, started playing loud and energetic music, and dimmed the lights to 50% brightness. Let's get this party started!

कॉम्पोज़िशनल फ़ंक्शन कॉलिंग

कंपज़िशनल या क्रम से फ़ंक्शन कॉल करने की सुविधा की मदद से, Gemini किसी जटिल अनुरोध को पूरा करने के लिए, एक साथ कई फ़ंक्शन कॉल को चेन कर सकता है. उदाहरण के लिए, "मेरी मौजूदा जगह का तापमान बताएं" के जवाब में, Gemini API पहले get_current_location() फ़ंक्शन को और फिर get_weather() फ़ंक्शन को कॉल कर सकता है. get_weather() फ़ंक्शन, जगह की जानकारी को पैरामीटर के तौर पर लेता है.

नीचे दिए गए उदाहरण में, Python SDK और फ़ंक्शन को अपने-आप कॉल करने की सुविधा का इस्तेमाल करके, कॉम्पोज़िशनल फ़ंक्शन कॉल करने का तरीका बताया गया है.

Python

इस उदाहरण में, google-genai Python SDK टूल की, फ़ंक्शन को अपने-आप कॉल करने की सुविधा का इस्तेमाल किया गया है. SDK, Python फ़ंक्शन को ज़रूरी स्कीमा में अपने-आप बदल देता है. साथ ही, मॉडल के अनुरोध करने पर फ़ंक्शन कॉल को लागू करता है और टास्क पूरा करने के लिए नतीजे वापस मॉडल को भेजता है.

import os
from google import genai
from google.genai import types

# Example Functions
def get_weather_forecast(location: str) -> dict:
    """Gets the current weather temperature for a given location."""
    print(f"Tool Call: get_weather_forecast(location={location})")
    # TODO: Make API call
    print("Tool Response: {'temperature': 25, 'unit': 'celsius'}")
    return {"temperature": 25, "unit": "celsius"}  # Dummy response

def set_thermostat_temperature(temperature: int) -> dict:
    """Sets the thermostat to a desired temperature."""
    print(f"Tool Call: set_thermostat_temperature(temperature={temperature})")
    # TODO: Interact with a thermostat API
    print("Tool Response: {'status': 'success'}")
    return {"status": "success"}

# Configure the client and model
client = genai.Client(
    api_key=os.getenv("GEMINI_API_KEY")
)  # Replace with your actual API key setup
config = types.GenerateContentConfig(
    tools=[get_weather_forecast, set_thermostat_temperature]
)

# Make the request
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
    config=config,
)

# Print the final, user-facing response
print(response.text)

अनुमानित आउटपुट

कोड चलाने पर, आपको SDK फ़ंक्शन कॉल को ऑर्केस्ट्रेट करते हुए दिखेगा. मॉडल पहले get_weather_forecast को कॉल करता है, तापमान पाता है, और फिर प्रॉम्प्ट में दिए गए लॉजिक के आधार पर सही वैल्यू के साथ set_thermostat_temperature को कॉल करता है.

Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. I've set the thermostat to 20°C.

JavaScript

इस उदाहरण में, मैन्युअल तरीके से फ़ंक्शन को लागू करने वाले लूप का इस्तेमाल करके, कॉम्पोज़िशनल फ़ंक्शन को कॉल करने के लिए, JavaScript/TypeScript SDK टूल का इस्तेमाल करने का तरीका बताया गया है.

import { GoogleGenAI, Type } from "@google/genai";

// Configure the client
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Example Functions
function get_weather_forecast({ location }) {
  console.log(`Tool Call: get_weather_forecast(location=${location})`);
  // TODO: Make API call
  console.log("Tool Response: {'temperature': 25, 'unit': 'celsius'}");
  return { temperature: 25, unit: "celsius" };
}

function set_thermostat_temperature({ temperature }) {
  console.log(
    `Tool Call: set_thermostat_temperature(temperature=${temperature})`,
  );
  // TODO: Make API call
  console.log("Tool Response: {'status': 'success'}");
  return { status: "success" };
}

const toolFunctions = {
  get_weather_forecast,
  set_thermostat_temperature,
};

const tools = [
  {
    functionDeclarations: [
      {
        name: "get_weather_forecast",
        description:
          "Gets the current weather temperature for a given location.",
        parameters: {
          type: Type.OBJECT,
          properties: {
            location: {
              type: Type.STRING,
            },
          },
          required: ["location"],
        },
      },
      {
        name: "set_thermostat_temperature",
        description: "Sets the thermostat to a desired temperature.",
        parameters: {
          type: Type.OBJECT,
          properties: {
            temperature: {
              type: Type.NUMBER,
            },
          },
          required: ["temperature"],
        },
      },
    ],
  },
];

// Prompt for the model
let contents = [
  {
    role: "user",
    parts: [
      {
        text: "If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
      },
    ],
  },
];

// Loop until the model has no more function calls to make
while (true) {
  const result = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents,
    config: { tools },
  });

  if (result.functionCalls && result.functionCalls.length > 0) {
    const functionCall = result.functionCalls[0];

    const { name, args } = functionCall;

    if (!toolFunctions[name]) {
      throw new Error(`Unknown function call: ${name}`);
    }

    // Call the function and get the response.
    const toolResponse = toolFunctions[name](args);

    const functionResponsePart = {
      name: functionCall.name,
      response: {
        result: toolResponse,
      },
    };

    // Send the function response back to the model.
    contents.push({
      role: "model",
      parts: [
        {
          functionCall: functionCall,
        },
      ],
    });
    contents.push({
      role: "user",
      parts: [
        {
          functionResponse: functionResponsePart,
        },
      ],
    });
  } else {
    // No more function calls, break the loop.
    console.log(result.text);
    break;
  }
}

अनुमानित आउटपुट

कोड चलाने पर, आपको SDK फ़ंक्शन कॉल को ऑर्केस्ट्रेट करते हुए दिखेगा. मॉडल पहले get_weather_forecast को कॉल करता है, तापमान पाता है, और फिर प्रॉम्प्ट में दिए गए लॉजिक के आधार पर सही वैल्यू के साथ set_thermostat_temperature को कॉल करता है.

Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. It's 25°C in London, so I've set the thermostat to 20°C.

कॉम्पोज़िशनल फ़ंक्शन कॉलिंग, Live API की नेटिव सुविधा है. इसका मतलब है कि Live API, Python SDK की तरह ही फ़ंक्शन कॉलिंग को मैनेज कर सकता है.

Python

# Light control schemas
turn_on_the_lights_schema = {'name': 'turn_on_the_lights'}
turn_off_the_lights_schema = {'name': 'turn_off_the_lights'}

prompt = """
  Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
  """

tools = [
    {'code_execution': {}},
    {'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]}
]

await run(prompt, tools=tools, modality="AUDIO")

JavaScript

// Light control schemas
const turnOnTheLightsSchema = { name: 'turn_on_the_lights' };
const turnOffTheLightsSchema = { name: 'turn_off_the_lights' };

const prompt = `
  Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
`;

const tools = [
  { codeExecution: {} },
  { functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] }
];

await run(prompt, tools=tools, modality="AUDIO")

फ़ंक्शन कॉल करने के मोड

Gemini API की मदद से, यह कंट्रोल किया जा सकता है कि मॉडल, दिए गए टूल (फ़ंक्शन के एलान) का इस्तेमाल कैसे करे. खास तौर पर, आपके पास function_calling_config में जाकर मोड सेट करने का विकल्प है.

  • AUTO (Default): मॉडल यह तय करता है कि प्रॉम्प्ट और कॉन्टेक्स्ट के आधार पर, नैचुरल लैंग्वेज में जवाब जनरेट करना है या फ़ंक्शन कॉल का सुझाव देना है. यह सबसे ज़्यादा सुविधाजनक मोड है. ज़्यादातर मामलों में इसका सुझाव दिया जाता है.
  • ANY: मॉडल को हमेशा फ़ंक्शन कॉल का अनुमान लगाने के लिए बाध्य किया जाता है और यह फ़ंक्शन स्कीमा का पालन करने की गारंटी देता है. अगर allowed_function_names की जानकारी नहीं दी गई है, तो मॉडल, दिए गए किसी भी फ़ंक्शन के एलान में से किसी एक को चुन सकता है. अगर allowed_function_names को सूची के तौर पर दिया जाता है, तो मॉडल सिर्फ़ उस सूची में मौजूद फ़ंक्शन चुन सकता है. इस मोड का इस्तेमाल तब करें, जब आपको हर प्रॉम्प्ट (अगर लागू हो) के लिए फ़ंक्शन कॉल रिस्पॉन्स की ज़रूरत हो.
  • NONE: मॉडल को फ़ंक्शन कॉल करने से पाबंदी है. यह किसी फ़ंक्शन के एलान के बिना अनुरोध भेजने जैसा है. टूल की परिभाषाएं हटाए बिना, फ़ंक्शन कॉल करने की सुविधा को कुछ समय के लिए बंद करने के लिए, इसका इस्तेमाल करें.

Python

from google.genai import types

# Configure function calling mode
tool_config = types.ToolConfig(
    function_calling_config=types.FunctionCallingConfig(
        mode="ANY", allowed_function_names=["get_current_temperature"]
    )
)

# Create the generation config
config = types.GenerateContentConfig(
    tools=[tools],  # not defined here.
    tool_config=tool_config,
)

JavaScript

import { FunctionCallingConfigMode } from '@google/genai';

// Configure function calling mode
const toolConfig = {
  functionCallingConfig: {
    mode: FunctionCallingConfigMode.ANY,
    allowedFunctionNames: ['get_current_temperature']
  }
};

// Create the generation config
const config = {
  tools: tools, // not defined here.
  toolConfig: toolConfig,
};

फ़ंक्शन को अपने-आप कॉल करना (सिर्फ़ Python के लिए)

Python SDK का इस्तेमाल करते समय, Python फ़ंक्शन को सीधे टूल के तौर पर उपलब्ध कराया जा सकता है. SDK, Python फ़ंक्शन को अपने-आप एलान में बदल देता है. साथ ही, आपके लिए फ़ंक्शन कॉल को लागू करने और रिस्पॉन्स साइकल को मैनेज करता है. इसके बाद, Python SDK टूल अपने-आप:

  1. मॉडल से फ़ंक्शन कॉल के रिस्पॉन्स का पता लगाता है.
  2. अपने कोड में उससे जुड़े Python फ़ंक्शन को कॉल करें.
  3. फ़ंक्शन के जवाब को मॉडल को वापस भेजता है.
  4. यह मॉडल का आखिरी टेक्स्ट जवाब दिखाता है.

इसका इस्तेमाल करने के लिए, टाइप हिंट और दस्तावेज़ के ब्यौरे के साथ अपना फ़ंक्शन तय करें. इसके बाद, टूल के तौर पर फ़ंक्शन को ही पास करें, न कि JSON एलान को:

Python

from google import genai
from google.genai import types

# Define the function with type hints and docstring
def get_current_temperature(location: str) -> dict:
    """Gets the current temperature for a given location.

    Args:
        location: The city and state, e.g. San Francisco, CA

    Returns:
        A dictionary containing the temperature and unit.
    """
    # ... (implementation) ...
    return {"temperature": 25, "unit": "Celsius"}

# Configure the client
client = genai.Client(api_key="GOOGLE_API_KEY")
config = types.GenerateContentConfig(
    tools=[get_current_temperature]
)  # Pass the function itself

# Make the request
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="What's the temperature in Boston?",
    config=config,
)

print(response.text)  # The SDK handles the function call and returns the final text

अपने-आप कॉल करने की सुविधा को इन तरीकों से बंद किया जा सकता है:

Python

config = types.GenerateContentConfig(
    tools=[get_current_temperature],
    automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)

फ़ंक्शन के स्कीमा का अपने-आप एलान होना

Python फ़ंक्शन से अपने-आप स्कीमा निकालने की सुविधा, सभी मामलों में काम नहीं करती. उदाहरण के लिए: यह उन मामलों को हैंडल नहीं करता जहां नेस्ट किए गए डिक्शनरी-ऑब्जेक्ट के फ़ील्ड के बारे में बताया जाता है. एपीआई, इनमें से किसी भी तरह की जानकारी दे सकता है:

Python

AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])

यह देखने के लिए कि अनुमानित स्कीमा कैसा दिखता है, from_callable का इस्तेमाल करके इसे बदला जा सकता है:

Python

def multiply(a: float, b: float):
    """Returns a * b."""
    return a * b

fn_decl = types.FunctionDeclaration.from_callable(callable=multiply, client=client)

# to_json_dict() provides a clean JSON representation.
print(fn_decl.to_json_dict())

एक से ज़्यादा टूल का इस्तेमाल: फ़ंक्शन कॉलिंग के साथ नेटिव टूल का इस्तेमाल करना

Gemini 2.0 की मदद से, एक ही समय पर कई टूल चालू किए जा सकते हैं. इनमें, नेटिव टूल और फ़ंक्शन कॉलिंग को एक साथ जोड़ा जा सकता है. यहां एक उदाहरण दिया गया है, जिसमें लाइव एपीआई का इस्तेमाल करके, Google Search की मदद से ग्राउंडिंग और कोड को लागू करने वाले दो टूल चालू किए गए हैं.

Python

# Multiple tasks example - combining lights, code execution, and search
prompt = """
  Hey, I need you to do three things for me.

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

  Thanks!
  """

tools = [
    {'google_search': {}},
    {'code_execution': {}},
    {'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]} # not defined here.
]

# Execute the prompt with specified tools in audio modality
await run(prompt, tools=tools, modality="AUDIO")

JavaScript

// Multiple tasks example - combining lights, code execution, and search
const prompt = `
  Hey, I need you to do three things for me.

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

  Thanks!
`;

const tools = [
  { googleSearch: {} },
  { codeExecution: {} },
  { functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] } // not defined here.
];

// Execute the prompt with specified tools in audio modality
await run(prompt, {tools: tools, modality: "AUDIO"});

Python डेवलपर, लाइव एपीआई टूल के इस्तेमाल से जुड़ी नोटबुक में इसे आज़मा सकते हैं.

मॉडल कॉन्टेक्स्ट प्रोटोकॉल (एमसीपी)

मॉडल कॉन्टेक्स्ट प्रोटोकॉल (एमसीपी), एआई ऐप्लिकेशन को बाहरी टूल और डेटा से कनेक्ट करने के लिए एक ओपन स्टैंडर्ड है. एमसीपी, मॉडल के लिए एक सामान्य प्रोटोकॉल उपलब्ध कराता है, ताकि वे फ़ंक्शन (टूल), डेटा सोर्स (संसाधन) या पहले से तय किए गए प्रॉम्प्ट जैसे कॉन्टेक्स्ट को ऐक्सेस कर सकें.

Gemini SDK में एमसीपी के लिए पहले से सहायता मौजूद होती है. इससे, बोइलरप्लेट कोड कम हो जाता है और एमसीपी टूल के लिए टूल को अपने-आप कॉल करने की सुविधा मिलती है. जब मॉडल कोई एमसीपी टूल कॉल जनरेट करता है, तो Python और JavaScript क्लाइंट SDK, एमसीपी टूल को अपने-आप लागू कर सकता है और अगले अनुरोध में जवाब को मॉडल को वापस भेज सकता है. यह लूप तब तक जारी रहता है, जब तक मॉडल कोई और टूल कॉल नहीं करता.

यहां, Gemini और mcp SDK के साथ स्थानीय एमसीपी सर्वर का इस्तेमाल करने का उदाहरण दिया गया है.

Python

पक्का करें कि आपके चुने गए प्लैटफ़ॉर्म पर, mcp SDK टूल का सबसे नया वर्शन इंस्टॉल हो.

pip install mcp
import os
import asyncio
from datetime import datetime
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai

client = genai.Client(api_key="GOOGLE_API_KEY")

# Create server parameters for stdio connection
server_params = StdioServerParameters(
    command="npx",  # Executable
    args=["-y", "@philschmid/weather-mcp"],  # MCP Server
    env=None,  # Optional environment variables
)

async def run():
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Prompt to get the weather for the current day in London.
            prompt = f"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?"

            # Initialize the connection between client and server
            await session.initialize()

            # Send request to the model with MCP function declarations
            response = await client.aio.models.generate_content(
                model="gemini-2.0-flash",
                contents=prompt,
                config=genai.types.GenerateContentConfig(
                    temperature=0,
                    tools=[session],  # uses the session, will automatically call the tool
                    # Uncomment if you **don't** want the SDK to automatically call the tool
                    # automatic_function_calling=genai.types.AutomaticFunctionCallingConfig(
                    #     disable=True
                    # ),
                ),
            )
            print(response.text)

# Start the asyncio event loop and run the main function
asyncio.run(run())

JavaScript

पक्का करें कि आपके पसंदीदा प्लैटफ़ॉर्म पर, mcp SDK टूल का नया वर्शन इंस्टॉल हो.

npm install @modelcontextprotocol/sdk
import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai';
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

// Create server parameters for stdio connection
const serverParams = new StdioClientTransport({
  command: "npx", // Executable
  args: ["-y", "@philschmid/weather-mcp"] // MCP Server
});

const client = new Client(
  {
    name: "example-client",
    version: "1.0.0"
  }
);

// Configure the client
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Initialize the connection between client and server
await client.connect(serverParams);

// Send request to the model with MCP tools
const response = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`,
  config: {
    tools: [mcpToTool(client)],  // uses the session, will automatically call the tool
    // Uncomment if you **don't** want the sdk to automatically call the tool
    // automaticFunctionCalling: {
    //   disable: true,
    // },
  },
});
console.log(response.text)

// Close the connection
await client.close();

एमसीपी के लिए पहले से मौजूद सहायता की सीमाएं

हमारे एसडीके में, पहले से मौजूद एमसीपी सहायता एक प्रयोग के तौर पर उपलब्ध सुविधा है. इसमें ये सीमाएं हैं:

  • सिर्फ़ टूल इस्तेमाल किए जा सकते हैं, न कि संसाधन या प्रॉम्प्ट
  • यह Python और JavaScript/TypeScript SDK के लिए उपलब्ध है.
  • आने वाले समय में, रिलीज़ में कुछ बदलाव हो सकते हैं.

अगर एमसीपी सर्वर, आपके ऐप्लिकेशन के काम करने में रुकावट डालते हैं, तो मैन्युअल तरीके से इंटिग्रेशन किया जा सकता है.

काम करने वाले मॉडल

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

मॉडल फ़ंक्शन कॉल करना पैरलल फ़ंक्शन कॉलिंग कॉम्पोज़िशनल फ़ंक्शन कॉलिंग
Gemini 2.0 Flash ✔️ ✔️ ✔️
Gemini 2.0 Flash-Lite X X X
Gemini 1.5 Flash ✔️ ✔️ ✔️
Gemini 1.5 Pro ✔️ ✔️ ✔️

सबसे सही तरीके

  • फ़ंक्शन और पैरामीटर के ब्यौरे: अपने ब्यौरे में साफ़ और सटीक जानकारी दें. सही फ़ंक्शन चुनने और सही आर्ग्युमेंट देने के लिए, मॉडल इन पर निर्भर करता है.
  • नाम देना: फ़ंक्शन के नाम ऐसे रखें जिनसे उनके काम के बारे में पता चलता हो. इन नामों में स्पेस, पीरियड या डैश का इस्तेमाल न करें.
  • स्ट्रॉन्ग टाइपिंग: गड़बड़ियों को कम करने के लिए, पैरामीटर के लिए खास टाइप (पूर्णांक, स्ट्रिंग, एनम) का इस्तेमाल करें. अगर किसी पैरामीटर में मान्य वैल्यू का सीमित सेट है, तो सूची का इस्तेमाल करें.
  • टूल चुनना: मॉडल में ज़रूरत के मुताबिक टूल इस्तेमाल किए जा सकते हैं. हालांकि, बहुत ज़्यादा टूल देने पर, गलत या काम के न होने वाले टूल चुनने का जोखिम बढ़ जाता है. सबसे अच्छे नतीजे पाने के लिए, कॉन्टेक्स्ट या टास्क के लिए सिर्फ़ काम के टूल उपलब्ध कराएं. साथ ही, ऐक्टिव सेट को ज़्यादा से ज़्यादा 10 से 20 तक रखें. अगर आपके पास कई टूल हैं, तो बातचीत के संदर्भ के आधार पर डाइनैमिक टूल चुनें.
  • प्रॉम्प्ट इंजीनियरिंग:
    • कॉन्टेक्स्ट दें: मॉडल को उसकी भूमिका बताएं (उदाहरण के लिए, "आप मौसम की जानकारी देने वाली एक मददगार सहायक हैं.").
    • निर्देश दें: फ़ंक्शन इस्तेमाल करने का तरीका और समय बताएं. उदाहरण के लिए, "तारीखों का अनुमान न लगाएं; अनुमान के लिए हमेशा आने वाले समय की तारीख का इस्तेमाल करें.").
    • ज़्यादा जानकारी देने के लिए कहें: ज़रूरत पड़ने पर, मॉडल को ज़्यादा जानकारी देने के लिए कहें.
  • तापमान: कम तापमान का इस्तेमाल करें (उदाहरण के लिए, 0) का इस्तेमाल करें.
  • पुष्टि करना: अगर किसी फ़ंक्शन कॉल के गंभीर नतीजे होते हैं (उदाहरण के लिए, ऑर्डर देना), तो उसे लागू करने से पहले उपयोगकर्ता से पुष्टि करें.
  • गड़बड़ी को मैनेज करना: अपने फ़ंक्शन में गड़बड़ी को मैनेज करने की बेहतर सुविधा लागू करें, ताकि अचानक मिलने वाले इनपुट या एपीआई के काम न करने की समस्या को आसानी से हल किया जा सके. गड़बड़ी के बारे में जानकारी देने वाले मैसेज दिखाएं. इनका इस्तेमाल करके, मॉडल उपयोगकर्ता के लिए मददगार जवाब जनरेट कर सकता है.
  • सुरक्षा: बाहरी एपीआई को कॉल करते समय सुरक्षा का ध्यान रखें. पुष्टि करने और अनुमति देने के लिए सही तरीकों का इस्तेमाल करें. फ़ंक्शन कॉल में संवेदनशील डेटा को ज़ाहिर करने से बचें.
  • टोकन की सीमाएं: फ़ंक्शन के ब्यौरे और पैरामीटर, इनपुट टोकन की सीमा में गिने जाते हैं. अगर टोकन की सीमाएं पूरी हो रही हैं, तो फ़ंक्शन की संख्या या जानकारी की लंबाई को सीमित करें. साथ ही, मुश्किल टास्क को छोटे और ज़्यादा फ़ोकस वाले फ़ंक्शन सेट में बांटें.

ध्यान देने वाली बातें और सीमाएं

  • सिर्फ़ OpenAPI स्कीमा का सबसेट काम करता है.
  • Python में काम करने वाले पैरामीटर टाइप सीमित हैं.
  • फ़ंक्शन को अपने-आप कॉल करने की सुविधा, सिर्फ़ Python SDK टूल की है.