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

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

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

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

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

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

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

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

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

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

PythonJavaScript
from google.genai import types

# 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}

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
  };
}

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

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

PythonJavaScript
from google import genai

# Generation Config with Function Declaration
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])

# Configure the client
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

# 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", config=config, contents=contents
)

print(response.candidates[0].content.parts[0].function_call)
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 ऑब्जेक्ट दिखाता है. इसमें, उपयोगकर्ता के सवाल का जवाब देने के लिए, एलान किए गए एक या उससे ज़्यादा फ़ंक्शन को कॉल करने का तरीका बताया जाता है.

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

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

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

PythonJavaScript
# Extract tool call details
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}")
// 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)}`);
}

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

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

PythonJavaScript
# 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(types.Content(role="model", parts=[types.Part(function_call=tool_call)])) # Append the model's function call message
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)
// 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({ role: 'model', parts: [{ functionCall: tool_call }] });
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 (कलेक्शन): यह पैरामीटर के नामों की सूची वाली स्ट्रिंग का कलेक्शन होता है. फ़ंक्शन के काम करने के लिए, इन पैरामीटर के नाम ज़रूरी होते हैं.

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

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

PythonJavaScript
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"],
    },
}
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']
  }
};

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

PythonJavaScript
from google import genai
from google.genai import types

# Set up function declarations
house_tools = [
    types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]

config = {
    "tools": house_tools,
    "automatic_function_calling": {"disable": True},
    # Force the model to call 'any' function, instead of chatting.
    "tool_config": {"function_calling_config": {"mode": "any"}},
}

# Configure the client
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

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})")
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 implementation functions
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}

config = {
    "tools": [power_disco_ball_impl, start_music_impl, dim_lights_impl],
}

chat = client.chats.create(model="gemini-2.0-flash", config=config)
response = chat.send_message("Do everything you need to this place into party!")

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 2.0, कंपज़िशनल फ़ंक्शन कॉलिंग के साथ काम करता है. इसका मतलब है कि मॉडल एक साथ कई फ़ंक्शन कॉल को चेन कर सकता है. उदाहरण के लिए, "मेरी मौजूदा जगह का तापमान बताएं" सवाल का जवाब देने के लिए, Gemini API, get_current_location() फ़ंक्शन और get_weather() फ़ंक्शन, दोनों को एक साथ इस्तेमाल कर सकता है. ये दोनों फ़ंक्शन, जगह की जानकारी को पैरामीटर के तौर पर लेते हैं.

PythonJavaScript
# 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")
// 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: मॉडल को फ़ंक्शन कॉल करने से पाबंदी है. यह किसी फ़ंक्शन के एलान के बिना अनुरोध भेजने के बराबर है. टूल की परिभाषाओं को हटाए बिना, फ़ंक्शन कॉलिंग को कुछ समय के लिए बंद करने के लिए इसका इस्तेमाल करें.

PythonJavaScript
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(
    temperature=0,
    tools=[tools],  # not defined here.
    tool_config=tool_config,
)
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 = {
  temperature: 0,
  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 and model
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))  # Replace with your actual API key setup
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 London?",
    config=config,
)

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

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

Python
# To disable automatic function calling:
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 की मदद से ग्राउंडिंग और कोड को लागू करने वाले दो टूल चालू किए गए हैं.

PythonJavaScript

# 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")
// 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 2.0 Flash ✔️ ✔️ ✔️
Gemini 2.0 Flash-Lite X X X
Gemini 1.5 Flash ✔️ ✔️ ✔️
Gemini 1.5 Pro ✔️ ✔️ ✔️

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

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

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

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