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

जनरेटिव मॉडल, कई तरह की समस्याओं को हल करने में काफ़ी असरदार होते हैं. हालांकि, इन पर ये पाबंदियां लागू होती हैं:

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

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

Google Cloud दस्तावेज़ में, फ़ंक्शन कॉल करने के बारे में ज़्यादा जानें. इसमें, फ़ंक्शन कॉल करने के इस्तेमाल के उदाहरणों की मददगार सूची भी शामिल है.

फ़ंक्शन कॉलिंग मोड, Gemini के सभी मॉडल पर काम करता है. हालांकि, यह Gemini 1.0 मॉडल पर काम नहीं करता.

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

  1. ऐसा फ़ंक्शन लिखें जो मॉडल को वह जानकारी दे सके जिसकी उसे आखिरी जवाब जनरेट करने के लिए ज़रूरत होती है. उदाहरण के लिए, फ़ंक्शन किसी बाहरी एपीआई को कॉल कर सकता है.

  2. फ़ंक्शन का एलान करें, जिसमें फ़ंक्शन और उसके पैरामीटर के बारे में बताया गया हो.

  3. मॉडल के शुरू होने के दौरान फ़ंक्शन का एलान करें, ताकि ज़रूरत पड़ने पर मॉडल को पता रहे कि वह फ़ंक्शन का इस्तेमाल कैसे कर सकता है.

  4. अपने ऐप्लिकेशन को सेट अप करें, ताकि मॉडल आपके ऐप्लिकेशन को फ़ंक्शन को कॉल करने के लिए ज़रूरी जानकारी भेज सके.

  5. फ़ंक्शन के जवाब को मॉडल को वापस भेजें, ताकि मॉडल अपना आखिरी जवाब जनरेट कर सके.

कोड लागू करने पर जाएं

फ़ंक्शन को कॉल करने के उदाहरण की खास जानकारी

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

मान लें कि आपके पास एक ऐसा ऐप्लिकेशन है जिसमें उपयोगकर्ता, इस तरह का प्रॉम्प्ट डाल सकता है: What was the weather in Boston on October 17, 2024?.

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

सबसे पहले, अपने ऐप्लिकेशन में एक फ़ंक्शन fetchWeather लिखें, जो इस hipotética एपीआई के साथ इंटरैक्ट करता है. इसमें यह इनपुट और आउटपुट होता है:

पैरामीटर टाइप ज़रूरी है ब्यौरा
इनपुट
location ऑब्जेक्ट हां उस शहर और राज्य का नाम जहां का मौसम जानना है.
यह सुविधा सिर्फ़ अमेरिका के शहरों में उपलब्ध है. यह हमेशा city और state का नेस्ट किया गया ऑब्जेक्ट होना चाहिए.
date स्ट्रिंग हां वह तारीख जिसके लिए मौसम की जानकारी फ़ेच करनी है. यह तारीख हमेशा YYYY-MM-DD फ़ॉर्मैट में होनी चाहिए.
आउटपुट
temperature पूर्णांक हां तापमान (फ़ैरनहाइट में)
chancePrecipitation स्ट्रिंग हां बारिश या बर्फ़बारी वगैरह होने की संभावना (प्रतिशत के तौर पर)
cloudConditions स्ट्रिंग हां क्लाउड की स्थिति (clear, partlyCloudy, mostlyCloudy, cloudy में से कोई एक)

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

फिर से आने वाले अनुरोध को देखें: What was the weather in Boston on October 17, 2024?. मॉडल यह तय कर सकता है कि fetchWeather फ़ंक्शन से उसे जवाब जनरेट करने में मदद मिल सकती है. मॉडल यह देखेगा कि fetchWeather के लिए कौनसे इनपुट पैरामीटर ज़रूरी हैं. इसके बाद, वह फ़ंक्शन के लिए स्ट्रक्चर्ड इनपुट डेटा जनरेट करेगा, जो कुछ ऐसा दिखेगा:

{
  functionName: fetchWeather,
  location: {
    city: Boston,
    state: Massachusetts  // the model can infer the state from the prompt
  },
  date: 2024-10-17
}

मॉडल, इस स्ट्रक्चर्ड इनपुट डेटा को आपके ऐप्लिकेशन को भेजता है, ताकि आपका ऐप्लिकेशन fetchWeather फ़ंक्शन को कॉल कर सके. जब आपके ऐप्लिकेशन को एपीआई से मौसम की जानकारी मिलती है, तो वह जानकारी को मॉडल को भेज देता है. मौसम की इस जानकारी की मदद से, मॉडल अपनी फ़ाइनल प्रोसेसिंग पूरी कर पाता है और What was the weather in Boston on October 17, 2024? के शुरुआती अनुरोध का जवाब जनरेट कर पाता है

मॉडल, आम भाषा में ऐसा जवाब दे सकता है: On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.

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

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

शुरू करने से पहले

अगर आपने अब तक ऐसा नहीं किया है, तो शुरू करने से जुड़ी गाइड पढ़ें. इसमें, Firebase प्रोजेक्ट सेट अप करने, अपने ऐप्लिकेशन को Firebase से कनेक्ट करने, SDK टूल जोड़ने, Vertex AI सेवा को शुरू करने, और GenerativeModel इंस्टेंस बनाने का तरीका बताया गया है.

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

इस पेज पर, फ़ंक्शन को कॉल करने के इस उदाहरण के लिए पूरा कोड सैंपल बाद में देखा जा सकता है.

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

मान लें कि आपके पास एक ऐसा ऐप्लिकेशन है जिसमें उपयोगकर्ता, इस तरह का प्रॉम्प्ट डाल सकता है: What was the weather in Boston on October 17, 2024?. हो सकता है कि Gemini मॉडल को मौसम की यह जानकारी न पता हो. हालांकि, मान लें कि आपको मौसम की जानकारी देने वाली किसी बाहरी सेवा का एपीआई पता है, जो यह जानकारी दे सकता है. इस गाइड में दिया गया उदाहरण, इस काल्पनिक बाहरी एपीआई पर आधारित है.

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

Swift

// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
func fetchWeather(city: String, state: String, date: String) -> JSONObject {

  // TODO(developer): Write a standard function that would call an external weather API.

  // For demo purposes, this hypothetical response is hardcoded here in the expected format.
  return [
    "temperature": .number(38),
    "chancePrecipitation": .string("56%"),
    "cloudConditions": .string("partlyCloudy"),
  ]
}

Kotlin

// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
// `location` is an object of the form { city: string, state: string }
data class Location(val city: String, val state: String)

suspend fun fetchWeather(location: Location, date: String): JsonObject {

    // TODO(developer): Write a standard function that would call to an external weather API.

    // For demo purposes, this hypothetical response is hardcoded here in the expected format.
    return JsonObject(mapOf(
        "temperature" to JsonPrimitive(38),
        "chancePrecipitation" to JsonPrimitive("56%"),
        "cloudConditions" to JsonPrimitive("partlyCloudy")
    ))
}

Java

// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
// `location` is an object of the form { city: string, state: string }
public JsonObject fetchWeather(Location location, String date) {

  // TODO(developer): Write a standard function that would call to an external weather API.

  // For demo purposes, this hypothetical response is hardcoded here in the expected format.
  return new JsonObject(Map.of(
        "temperature", JsonPrimitive(38),
        "chancePrecipitation", JsonPrimitive("56%"),
        "cloudConditions", JsonPrimitive("partlyCloudy")));
}

Web

// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
// `location` is an object of the form { city: string, state: string }
async function fetchWeather({ location, date }) {

  // TODO(developer): Write a standard function that would call to an external weather API.

  // For demo purposes, this hypothetical response is hardcoded here in the expected format.
  return {
    temperature: 38,
    chancePrecipitation: "56%",
    cloudConditions: "partlyCloudy",
  };
}

Dart

// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
// `location` is an object of the form { city: string, state: string }
Future<Map<String, Object?>> fetchWeather(
  Location location, String date
) async {

  // TODO(developer): Write a standard function that would call to an external weather API.

  // For demo purposes, this hypothetical response is hardcoded here in the expected format.
  final apiResponse = {
    'temperature': 38,
    'chancePrecipitation': '56%',
    'cloudConditions': 'partlyCloudy',
  };
  return apiResponse;
}

दूसरा चरण: फ़ंक्शन का एलान करना

फ़ंक्शन का एलान करें, जिसे बाद में मॉडल को दिया जाएगा (इस गाइड का अगला चरण).

अपने एलान में, फ़ंक्शन और उसके पैरामीटर के ब्यौरे में ज़्यादा से ज़्यादा जानकारी शामिल करें.

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

आपके दिए गए स्कीमा के बारे में इन बातों का ध्यान रखें:

  • आपको फ़ंक्शन के एलान, स्कीमा फ़ॉर्मैट में देने होंगे. यह फ़ॉर्मैट, OpenAPI स्कीमा के साथ काम करना चाहिए. Vertex AI, OpenAPI स्कीमा के साथ सीमित तौर पर काम करता है.

    • इन एट्रिब्यूट का इस्तेमाल किया जा सकता है: type, nullable, required, format, description, properties, items, enum.

    • ये एट्रिब्यूट इस्तेमाल नहीं किए जा सकते: default, optional, maximum, oneOf.

  • डिफ़ॉल्ट रूप से, Vertex AI in Firebase SDKs के लिए, सभी फ़ील्ड को ज़रूरी माना जाता है. हालांकि, अगर आपने उन्हें optionalProperties ऐरे में 'ज़रूरी नहीं है' के तौर पर सेट किया है, तो ऐसा नहीं होगा. इन वैकल्पिक फ़ील्ड के लिए, मॉडल फ़ील्ड में अपने-आप जानकारी भर सकता है या उन्हें स्किप कर सकता है. ध्यान दें कि यह Vertex AI Gemini API के लिए डिफ़ॉल्ट व्यवहार से उलट है.

फ़ंक्शन के एलान से जुड़े सबसे सही तरीकों के बारे में जानने के लिए, Google Cloud दस्तावेज़ में सबसे सही तरीके देखें. इसमें नाम और ब्यौरे से जुड़ी सलाह भी शामिल है.

फ़ंक्शन का एलान करने का तरीका यहां बताया गया है:

Swift

let fetchWeatherTool = FunctionDeclaration(
  name: "fetchWeather",
  description: "Get the weather conditions for a specific city on a specific date.",
  parameters: [
    "location": .object(
      properties: [
        "city": .string(description: "The city of the location."),
        "state": .string(description: "The US state of the location."),
      ],
      description: """
      The name of the city and its state for which to get the weather. Only cities in the
      USA are supported.
      """
    ),
    "date": .string(
      description: """
      The date for which to get the weather. Date must be in the format: YYYY-MM-DD.
      """
    ),
  ]
)

Kotlin

val fetchWeatherTool = FunctionDeclaration(
    "fetchWeather",
    "Get the weather conditions for a specific city on a specific date.",
    mapOf(
        "location" to Schema.obj(
            mapOf(
                "city" to Schema.string("The city of the location."),
                "state" to Schema.string("The US state of the location."),
            ),
            description = "The name of the city and its state for which " +
                "to get the weather. Only cities in the " +
                "USA are supported."
        ),
        "date" to Schema.string("The date for which to get the weather." +
                                " Date must be in the format: YYYY-MM-DD."
        ),
    ),
)

Java

FunctionDeclaration fetchWeatherTool = new FunctionDeclaration(
        "fetchWeather",
        "Get the weather conditions for a specific city on a specific date.",
        Map.of("location",
                Schema.obj(Map.of(
                        "city", Schema.str("The city of the location."),
                        "state", Schema.str("The US state of the location."))),
                "date",
                Schema.str("The date for which to get the weather. " +
                              "Date must be in the format: YYYY-MM-DD.")),
        Collections.emptyList());

Web

const fetchWeatherTool = {
  functionDeclarations: [
   {
      name: "fetchWeather",
      description:
        "Get the weather conditions for a specific city on a specific date",
      parameters: Schema.object({
        properties: {
          location: Schema.object({
            description:
              "The name of the city and its state for which to get " +
              "the weather. Only cities in the USA are supported.",
            properties: {
              city: Schema.string(
                description: "The city of the location."
              ),
              state: Schema.string(
                description: "The US state of the location."
              ),
            },
          }),
          date: Schema.string({
            description:
              "The date for which to get the weather. Date must be in the" +
              " format: YYYY-MM-DD.",
          }),
        },
      }),
    },
  ],
};

Dart

final fetchWeatherTool = FunctionDeclaration(
    'fetchWeather',
    'Get the weather conditions for a specific city on a specific date.',
    parameters: {
      'location': Schema.object(
        description:
          'The name of the city and its state for which to get'
          'the weather. Only cities in the USA are supported.',
        properties: {
          'city': Schema.string(
             description: 'The city of the location.'
           ),
          'state': Schema.string(
             description: 'The US state of the location.'
          ),
        },
      ),
      'date': Schema.string(
        description:
          'The date for which to get the weather. Date must be in the format: YYYY-MM-DD.'
      ),
    },
  );

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

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

Swift

import FirebaseVertexAI

// Initialize the Vertex AI service and the generative model.
let model = VertexAI.vertexAI().generativeModel(
  modelName: "gemini-2.0-flash",
  // Provide the function declaration to the model.
  tools: [.functionDeclarations([fetchWeatherTool])]
)

Kotlin

// Initialize the Vertex AI service and the generative model
val model = Firebase.vertexAI.generativeModel(
    modelName = "gemini-2.0-flash",
    // Provide the function declaration to the model.
    tools = listOf(Tool.functionDeclarations(listOf(fetchWeatherTool)))
)

Java

// Initialize the Vertex AI service and the generative model
// Use a model that supports function calling, like a Gemini 1.5 model
GenerativeModelFutures model = GenerativeModelFutures.from(
        FirebaseVertexAI.getInstance()
                .generativeModel("gemini-1.5-flash",
                        null,
                        null,
                        // Provide the function declaration to the model.
                        List.of(Tool.functionDeclarations(List.of(fetchWeatherTool)))));

Web

import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Vertex AI service
const vertexAI = getVertexAI(firebaseApp);

// Initialize the generative model
const model = getGenerativeModel(vertexAI, {
  model: "gemini-2.0-flash",
  // Provide the function declaration to the model.
  tools: fetchWeatherTool
});

Dart

import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';

await Firebase.initializeApp();

// Initialize the Vertex AI service and the generative model.
_functionCallModel = FirebaseVertexAI.instance.generativeModel(
       model: 'gemini-2.0-flash',
       // Provide the function declaration to the model.
       tools: [
         Tool.functionDeclarations([fetchWeatherTool]),
       ],
     );

अपने इस्तेमाल के उदाहरण और ऐप्लिकेशन के हिसाब से सही मॉडल और जगह चुनने का तरीका जानें.

चौथा चरण: बाहरी एपीआई को कॉल करने के लिए फ़ंक्शन को कॉल करना

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

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

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

इस उदाहरण में, इनकमिंग अनुरोध में प्रॉम्प्ट What was the weather in Boston on October 17, 2024? शामिल था. इस प्रॉम्प्ट से, मॉडल ने fetchWeather फ़ंक्शन के लिए ज़रूरी इनपुट पैरामीटर का अनुमान लगाया. जैसे, city, state, और date.

Swift

let chat = model.startChat()
let prompt = "What was the weather in Boston on October 17, 2024?"

// Send the user's question (the prompt) to the model using multi-turn chat.
let response = try await chat.sendMessage(prompt)

var functionResponses = [FunctionResponsePart]()

// When the model responds with one or more function calls, invoke the function(s).
for functionCall in response.functionCalls {
  if functionCall.name == "fetchWeather" {
    // TODO(developer): Handle invalid arguments.
    guard case let .object(location) = functionCall.args["location"] else { fatalError() }
    guard case let .string(city) = location["city"] else { fatalError() }
    guard case let .string(state) = location["state"] else { fatalError() }
    guard case let .string(date) = functionCall.args["date"] else { fatalError() }

    functionResponses.append(FunctionResponsePart(
      name: functionCall.name,
      // Forward the structured input data prepared by the model
      // to the hypothetical external API.
      response: fetchWeather(city: city, state: state, date: date)
    ))
  }
  // TODO(developer): Handle other potential function calls, if any.
}

Kotlin

val prompt = "What was the weather in Boston on October 17, 2024?"
val chat = model.startChat()
// Send the user's question (the prompt) to the model using multi-turn chat.
val result = chat.sendMessage(prompt)

val functionCalls = result.functionCalls
// When the model responds with one or more function calls, invoke the function(s).
val fetchWeatherCall = functionCalls.find { it.name == "fetchWeather" }

// Forward the structured input data prepared by the model
// to the hypothetical external API.
val functionResponse = fetchWeatherCall?.let {
    // Alternatively, if your `Location` class is marked as @Serializable, you can use
    // val location = Json.decodeFromJsonElement<Location>(it.args["location"]!!)
    val location = Location(
        it.args["location"]!!.jsonObject["city"]!!.jsonPrimitive.content,
        it.args["location"]!!.jsonObject["state"]!!.jsonPrimitive.content
    )
    val date = it.args["date"]!!.jsonPrimitive.content
    fetchWeather(location, date)
}

Java

String prompt = "What was the weather in Boston on October 17, 2024?";
ChatFutures chatFutures = model.startChat();
// Send the user's question (the prompt) to the model using multi-turn chat.
ListenableFuture<GenerateContentResponse> response =
        chatFutures.sendMessage(new Content("user", List.of(new TextPart(prompt))));

ListenableFuture<JsonObject> handleFunctionCallFuture = Futures.transform(response, result -> {
    for (FunctionCallPart functionCall : result.getFunctionCalls()) {
        if (functionCall.getName().equals("fetchWeather")) {
            Map<String, JsonElement> args = functionCall.getArgs();
            JsonObject locationJsonObject =
                    JsonElementKt.getJsonObject(args.get("location"));
            String city =
                    JsonElementKt.getContentOrNull(
                            JsonElementKt.getJsonPrimitive(
                                    locationJsonObject.get("city")));
            String state =
                    JsonElementKt.getContentOrNull(
                            JsonElementKt.getJsonPrimitive(
                                    locationJsonObject.get("state")));
            Location location = new Location(city, state);

            String date = JsonElementKt.getContentOrNull(
                    JsonElementKt.getJsonPrimitive(
                            args.get("date")));
            return fetchWeather(location, date);
        }
    }
    return null;
}, Executors.newSingleThreadExecutor());

Web

const chat = model.startChat();
const prompt = "What was the weather in Boston on October 17, 2024?";

// Send the user's question (the prompt) to the model using multi-turn chat.
let result = await chat.sendMessage(prompt);
const functionCalls = result.response.functionCalls();
let functionCall;
let functionResult;
// When the model responds with one or more function calls, invoke the function(s).
if (functionCalls.length > 0) {
  for (const call of functionCalls) {
    if (call.name === "fetchWeather") {
      // Forward the structured input data prepared by the model
      // to the hypothetical external API.
      functionResult = await fetchWeather(call.args);
      functionCall = call;
    }
  }
}

Dart

final chat = _functionCallModel.startChat();
const prompt = 'What was the weather in Boston on October 17, 2024?';

// Send the user's question (the prompt) to the model using multi-turn chat.
var response = await chat.sendMessage(Content.text(prompt));

final functionCalls = response.functionCalls.toList();
// When the model responds with one or more function calls, invoke the function(s).
if (functionCalls.isNotEmpty) {
  final functionCall = functionCalls.first;
  if (functionCall.name == 'fetchWeather') {
    // Forward the structured input data prepared by the model
    // to the hypothetical external API.
    Map<String, dynamic> location =
        functionCall.args['location']! as Map<String, dynamic>;
    var date = functionCall.args['date']! as String;
    var city = location['city']! as String;
    var state = location['state']! as String;
    final functionResult = await fetchWeather(Location(city, state), date);
    ...
} else {
  throw UnimplementedError(
    'Function not declared to the model: ${functionCall.name}',
  );
}

पांचवां चरण: आखिरी जवाब जनरेट करने के लिए, मॉडल को फ़ंक्शन का आउटपुट दें

fetchWeather फ़ंक्शन से मौसम की जानकारी मिलने के बाद, आपके ऐप्लिकेशन को उसे मॉडल को वापस भेजना होगा.

इसके बाद, मॉडल आखिरी प्रोसेसिंग करता है और नैचुरल लैंग्वेज में फ़ाइनल जवाब जनरेट करता है, जैसे कि: On October 17, 2024 in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.

Swift

// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
let finalResponse = try await chat.sendMessage(
  [ModelContent(role: "function", parts: functionResponses)]
)

// Log the text response.
print(finalResponse.text ?? "No text in response.")

Kotlin

// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
val finalResponse = chat.sendMessage(content("function") {
    part(FunctionResponsePart("fetchWeather", functionResponse!!))
})

// Log the text response.
println(finalResponse.text ?: "No text in response")

Java

ListenableFuture<GenerateContentResponse> modelResponseFuture = Futures.transformAsync(
  handleFunctionCallFuture,
  // Send the response(s) from the function back to the model
  // so that the model can use it to generate its final response.
  functionCallResult -> chatFutures.sendMessage(new Content("function",
  List.of(new FunctionResponsePart(
          "fetchWeather", functionCallResult)))),
  Executors.newSingleThreadExecutor());

Futures.addCallback(modelResponseFuture, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
  if (result.getText() != null) {
      // Log the text response.
      System.out.println(result.getText());
  }
}

@Override
public void onFailure(Throwable t) {
  // handle error
}
}, Executors.newSingleThreadExecutor());

Web

// Send the response from the function back to the model
// so that the model can use it to generate its final response.
result = await chat.sendMessage([
  {
    functionResponse: {
      name: functionCall.name, // "fetchWeather"
      response: functionResult,
    },
  },
]);
console.log(result.response.text());

Dart

// Send the response from the function back to the model
// so that the model can use it to generate its final response.
response = await chat
     .sendMessage(Content.functionResponse(functionCall.name, functionResult));

अन्य व्यवहार और विकल्प

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

मॉडल, किसी फ़ंक्शन को फिर से कॉल करने या किसी दूसरे फ़ंक्शन को कॉल करने के लिए कह सकता है.

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

आपके ऐप्लिकेशन में यह सुविधा होनी चाहिए कि मॉडल, ज़्यादा फ़ंक्शन कॉल के लिए कह सके.

मॉडल, एक ही समय पर कई फ़ंक्शन कॉल करने के लिए कह सकता है.

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

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

आपके पास यह कंट्रोल करने का विकल्प होता है कि मॉडल, फ़ंक्शन को कॉल करने के लिए कैसे और कब कहे.

आपके पास यह तय करने का विकल्प होता है कि मॉडल, दिए गए फ़ंक्शन के एलान का इस्तेमाल कैसे करे और करे भी या नहीं. इसे फ़ंक्शन कॉलिंग मोड सेट करना कहा जाता है. यहां कुछ उदाहरण दिए गए हैं:

  • मॉडल को तुरंत मिलने वाले सामान्य भाषा वाले जवाब और फ़ंक्शन कॉल में से किसी एक को चुनने की अनुमति देने के बजाय, उसे हमेशा फ़ंक्शन कॉल का इस्तेमाल करने के लिए मजबूर किया जा सकता है. इसे फ़ंक्शन को जबरन कॉल करना कहा जाता है.

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

इन पाबंदियों (या मोड) को लागू करने के लिए, प्रॉम्प्ट और फ़ंक्शन के एलान के साथ-साथ टूल कॉन्फ़िगरेशन (toolConfig) जोड़ें. टूल के कॉन्फ़िगरेशन में, इनमें से कोई एक मोड चुना जा सकता है. सबसे ज़्यादा काम का मोड ANY है.

मोड ब्यौरा
AUTO मॉडल का डिफ़ॉल्ट व्यवहार. मॉडल यह तय करता है कि फ़ंक्शन कॉल का इस्तेमाल करना है या सामान्य भाषा में जवाब देना है.
ANY मॉडल में फ़ंक्शन कॉल ("फ़ोर्स्ड फ़ंक्शन कॉलिंग") का इस्तेमाल करना ज़रूरी है. मॉडल को फ़ंक्शन के सबसेट तक सीमित करने के लिए, allowedFunctionNames में इस्तेमाल किए जा सकने वाले फ़ंक्शन के नाम बताएं.
NONE मॉडल में फ़ंक्शन कॉल का इस्तेमाल नहीं किया जाना चाहिए. यह व्यवहार, किसी फ़ंक्शन के एलान के बिना मॉडल के अनुरोध के बराबर है.



तुम और क्या कर सकती हो?

अन्य सुविधाएं आज़माएं

कॉन्टेंट जनरेशन को कंट्रोल करने का तरीका जानें

Vertex AI Studio का इस्तेमाल करके, प्रॉम्प्ट और मॉडल कॉन्फ़िगरेशन के साथ भी एक्सपेरिमेंट किया जा सकता है.

इस्तेमाल किए जा सकने वाले मॉडल के बारे में ज़्यादा जानें

अलग-अलग कामों के लिए उपलब्ध मॉडल, उनके कोटे, और कीमत के बारे में जानें.


Vertex AI in Firebase के साथ अपने अनुभव के बारे में सुझाव/राय दें या शिकायत करें