जनरेटिव मॉडल, कई तरह की समस्याओं को हल करने में कारगर होते हैं. हालांकि, इन पर कुछ पाबंदियां लागू होती हैं. जैसे:
- ट्रेनिंग के बाद, इन्हें अपडेट नहीं किया जाता. इसलिए, इनमें मौजूद जानकारी पुरानी हो जाती है.
- वे बाहरी डेटा में क्वेरी नहीं कर सकते या उसमें बदलाव नहीं कर सकते.
फ़ंक्शन कॉलिंग की सुविधा से, आपको इनमें से कुछ सीमाओं को दूर करने में मदद मिल सकती है. फ़ंक्शन कॉलिंग को कभी-कभी टूल का इस्तेमाल भी कहा जाता है, क्योंकि इससे मॉडल को अपना फ़ाइनल जवाब जनरेट करने के लिए, एपीआई और फ़ंक्शन जैसे बाहरी टूल का इस्तेमाल करने की अनुमति मिलती है.
इस गाइड में बताया गया है कि फ़ंक्शन कॉल सेटअप को कैसे लागू किया जा सकता है. यह सेटअप, इस पेज के अगले मुख्य सेक्शन में बताए गए उदाहरण के जैसा होगा. बड़े लेवल पर, ऐप्लिकेशन में फ़ंक्शन कॉलिंग की सुविधा सेट अप करने के लिए, यह तरीका अपनाएं:
पहला चरण: एक ऐसा फ़ंक्शन लिखें जो मॉडल को वह जानकारी दे सके जिसकी ज़रूरत उसे फ़ाइनल जवाब जनरेट करने के लिए होती है. उदाहरण के लिए, फ़ंक्शन किसी बाहरी एपीआई को कॉल कर सकता है.
दूसरा चरण: फ़ंक्शन के बारे में बताने वाला फ़ंक्शन डिक्लेरेशन बनाएं. इसमें फ़ंक्शन और उसके पैरामीटर के बारे में जानकारी दी गई हो.
तीसरा चरण: मॉडल को शुरू करते समय फ़ंक्शन का एलान करें, ताकि मॉडल को यह पता चल सके कि ज़रूरत पड़ने पर वह फ़ंक्शन का इस्तेमाल कैसे कर सकता है.
चौथा चरण: अपने ऐप्लिकेशन को इस तरह से सेट अप करें कि मॉडल, फ़ंक्शन को कॉल करने के लिए ज़रूरी जानकारी भेज सके.
पांचवां चरण: फ़ंक्शन के जवाब को मॉडल को वापस भेजें, ताकि मॉडल अपना फ़ाइनल जवाब जनरेट कर सके.
कोड लागू करने से जुड़ी जानकारी पर जाएं
फ़ंक्शन कॉल करने के उदाहरण की खास जानकारी
मॉडल को अनुरोध भेजते समय, उसे "टूल" (जैसे कि फ़ंक्शन) का एक सेट भी दिया जा सकता है. इससे मॉडल को फ़ाइनल जवाब जनरेट करने में मदद मिलती है. इन फ़ंक्शन का इस्तेमाल करने और उन्हें कॉल करने ("फ़ंक्शन कॉलिंग") के लिए, मॉडल और आपके ऐप्लिकेशन को एक-दूसरे के साथ जानकारी शेयर करनी होगी. इसलिए, फ़ंक्शन कॉलिंग का इस्तेमाल करने का सुझाव, मल्टी-टर्न चैट इंटरफ़ेस के ज़रिए दिया जाता है.
मान लें कि आपके पास एक ऐसा ऐप्लिकेशन है जिसमें उपयोगकर्ता इस तरह का प्रॉम्प्ट डाल सकता है:
What was the weather in Boston on October 17, 2024?
.
Gemini मॉडल को मौसम की इस जानकारी के बारे में पता नहीं हो सकता. हालांकि, मान लें कि आपको मौसम की जानकारी देने वाली किसी बाहरी सेवा के एपीआई के बारे में पता है. फ़ंक्शन कॉलिंग का इस्तेमाल करके, Gemini मॉडल को उस एपीआई और मौसम की जानकारी का ऐक्सेस दिया जा सकता है.
सबसे पहले, अपने ऐप्लिकेशन में एक फ़ंक्शन fetchWeather
लिखें. यह फ़ंक्शन, इस काल्पनिक बाहरी एपीआई से इंटरैक्ट करता है. इसमें यह इनपुट और आउटपुट होता है:
पैरामीटर | टाइप | ज़रूरी है | ब्यौरा |
---|---|---|---|
इनपुट | |||
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.
फ़ंक्शन कॉलिंग की सुविधा लागू करना
इस गाइड में दिए गए चरणों में, फ़ंक्शन कॉल सेटअप करने का तरीका बताया गया है. यह सेटअप, फ़ंक्शन कॉल के उदाहरण की खास जानकारी में बताए गए वर्कफ़्लो के जैसा ही है. इस पेज का सबसे ऊपर वाला सेक्शन देखें.
शुरू करने से पहले
इस पेज पर, Gemini API उपलब्ध कराने वाली कंपनी के हिसाब से कॉन्टेंट और कोड देखने के लिए, उस कंपनी पर क्लिक करें. |
अगर आपने अब तक शुरुआती गाइड नहीं पढ़ी है, तो इसे पढ़ें. इसमें बताया गया है कि Firebase प्रोजेक्ट कैसे सेट अप करें, अपने ऐप्लिकेशन को Firebase से कैसे कनेक्ट करें, एसडीके कैसे जोड़ें, चुने गए Gemini API प्रोवाइडर के लिए बैकएंड सेवा को कैसे शुरू करें, और GenerativeModel
इंस्टेंस कैसे बनाएं.
हमारा सुझाव है कि अपने प्रॉम्प्ट की जांच करने और उन्हें बेहतर बनाने के लिए, Google AI Studio का इस्तेमाल करें. इससे आपको जनरेट किया गया कोड स्निपेट भी मिल सकता है.
पहला चरण: फ़ंक्शन लिखना
मान लें कि आपके पास एक ऐसा ऐप्लिकेशन है जिसमें उपयोगकर्ता इस तरह का प्रॉम्प्ट डाल सकता है:
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;
}
Unity
// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
System.Collections.Generic.Dictionary<string, object> FetchWeather(
string city, string state, string date) {
// 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 new System.Collections.Generic.Dictionary<string, object>() {
{"temperature", 38},
{"chancePrecipitation", "56%"},
{"cloudConditions", "partlyCloudy"},
};
}
दूसरा चरण: फ़ंक्शन का एलान करना
फ़ंक्शन का ऐसा एलान बनाएं जिसे बाद में मॉडल को दिया जा सके (इस गाइड का अगला चरण).
अपने एलान में, फ़ंक्शन और उसके पैरामीटर के ब्यौरे में ज़्यादा से ज़्यादा जानकारी शामिल करें.
मॉडल, फ़ंक्शन के एलान में दी गई जानकारी का इस्तेमाल करके यह तय करता है कि कौनसे फ़ंक्शन को चुना जाए. साथ ही, यह भी तय करता है कि फ़ंक्शन को कॉल करने के लिए पैरामीटर की वैल्यू कैसे दी जाए. मॉडल, फ़ंक्शन में से किसी एक को कैसे चुन सकता है, इसके बारे में जानने के लिए, इस पेज पर नीचे अन्य व्यवहार और विकल्प सेक्शन देखें. साथ ही, यह भी जानें कि इस विकल्प को कैसे कंट्रोल किया जा सकता है.
आपके दिए गए स्कीमा के बारे में यहां दी गई बातों का ध्यान रखें:
आपको फ़ंक्शन के बारे में जानकारी, स्कीमा फ़ॉर्मैट में देनी होगी. यह फ़ॉर्मैट, OpenAPI स्कीमा के साथ काम करता हो. Vertex AI OpenAPI स्कीमा के लिए सीमित सहायता उपलब्ध कराता है.
इन एट्रिब्यूट का इस्तेमाल किया जा सकता है:
type
,nullable
,required
,format
,description
,properties
,items
,enum
.इन एट्रिब्यूट का इस्तेमाल नहीं किया जा सकता:
default
,optional
,maximum
,oneOf
.
डिफ़ॉल्ट रूप से, Firebase AI Logic SDK के लिए सभी फ़ील्ड को ज़रूरी माना जाता है. हालांकि,
optionalProperties
ऐरे में उन्हें 'ज़रूरी नहीं है' के तौर पर सेट किया जा सकता है. इन वैकल्पिक फ़ील्ड के लिए, मॉडल फ़ील्ड भर सकता है या उन्हें छोड़ सकता है. ध्यान दें कि अगर इन दोनों Gemini API कंपनियों के सर्वर एसडीके या एपीआई का सीधे तौर पर इस्तेमाल किया जाता है, तो यह डिफ़ॉल्ट तरीके से काम नहीं करता.
फ़ंक्शन के एलान से जुड़े सबसे सही तरीके जानने के लिए, Google Cloud दस्तावेज़ में सबसे सही तरीके Gemini Developer API दस्तावेज़ में दिए गए हैं.
फ़ंक्शन का एलान करने का तरीका यहां बताया गया है:
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: FunctionDeclarationsTool = {
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.'
),
},
);
Unity
var fetchWeatherTool = new Tool(new FunctionDeclaration(
name: "fetchWeather",
description: "Get the weather conditions for a specific city on a specific date.",
parameters: new System.Collections.Generic.Dictionary<string, Schema>() {
{ "location", Schema.Object(
properties: new System.Collections.Generic.Dictionary<string, Schema>() {
{ "city", Schema.String(description: "The city of the location.") },
{ "state", Schema.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", Schema.String(
description: "The date for which to get the weather. Date must be in the format: YYYY-MM-DD."
)}
}
));
तीसरा चरण: मॉडल को शुरू करते समय फ़ंक्शन के बारे में जानकारी देना
अनुरोध के साथ ज़्यादा से ज़्यादा 128 फ़ंक्शन के बारे में जानकारी दी जा सकती है. मॉडल, फ़ंक्शन में से किसी एक को कैसे चुन सकता है, इसके बारे में जानने के लिए, इस पेज पर बाद में अन्य व्यवहार और विकल्प सेक्शन देखें. साथ ही, यह भी जानें कि toolConfig
का इस्तेमाल करके, फ़ंक्शन कॉलिंग मोड सेट करके, इस विकल्प को कैसे कंट्रोल किया जा सकता है.
Swift
import FirebaseAI
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
modelName: "gemini-2.5-flash",
// Provide the function declaration to the model.
tools: [.functionDeclarations([fetchWeatherTool])]
)
Kotlin
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-2.5-flash",
// Provide the function declaration to the model.
tools = listOf(Tool.functionDeclarations(listOf(fetchWeatherTool)))
)
Java
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModelFutures model = GenerativeModelFutures.from(
FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-2.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 { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// 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 Gemini Developer API backend service
const firebaseAI = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(firebaseAI, {
model: "gemini-2.5-flash",
// Provide the function declaration to the model.
tools: fetchWeatherTool
});
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
_functionCallModel = FirebaseAI.googleAI().generativeModel(
model: 'gemini-2.5-flash',
// Provide the function declaration to the model.
tools: [
Tool.functionDeclarations([fetchWeatherTool]),
],
);
Unity
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
modelName: "gemini-2.5-flash",
// Provide the function declaration to the model.
tools: new Tool[] { 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) {
for (final functionCall in functionCalls) {
if (functionCall.name == 'fetchWeather') {
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);
// Send the response to the model so that it can use the result to
// generate text for the user.
response = await functionCallChat.sendMessage(
Content.functionResponse(functionCall.name, functionResult),
);
}
}
} else {
throw UnimplementedError(
'Function not declared to the model: ${functionCall.name}',
);
}
Unity
var chat = model.StartChat();
var 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.SendMessageAsync(prompt);
var functionResponses = new List<ModelContent>();
foreach (var functionCall in response.FunctionCalls) {
if (functionCall.Name == "fetchWeather") {
// TODO(developer): Handle invalid arguments.
var city = functionCall.Args["city"] as string;
var state = functionCall.Args["state"] as string;
var date = functionCall.Args["date"] as string;
functionResponses.Add(ModelContent.FunctionResponse(
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.
}
पांचवां चरण: फ़ंक्शन का आउटपुट मॉडल को दें, ताकि वह फ़ाइनल जवाब जनरेट कर सके
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));
Unity
// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
var finalResponse = await chat.SendMessageAsync(functionResponses);
// Log the text response.
UnityEngine.Debug.Log(finalResponse.Text ?? "No text in response.");
अन्य व्यवहार और विकल्प
फ़ंक्शन कॉल करने के लिए, यहां कुछ और व्यवहार दिए गए हैं. आपको इन्हें अपने कोड में शामिल करना होगा. साथ ही, यहां कुछ ऐसे विकल्प दिए गए हैं जिन्हें कंट्रोल किया जा सकता है.
मॉडल, किसी फ़ंक्शन को फिर से कॉल करने या किसी अन्य फ़ंक्शन को कॉल करने के लिए कह सकता है.
अगर किसी फ़ंक्शन कॉल से मिला जवाब, मॉडल को फ़ाइनल जवाब जनरेट करने के लिए काफ़ी नहीं है, तो मॉडल किसी अन्य फ़ंक्शन कॉल के लिए अनुरोध कर सकता है. इसके अलावा, वह किसी दूसरे फ़ंक्शन को कॉल करने के लिए भी कह सकता है. ऐसा सिर्फ़ तब हो सकता है, जब आपने फ़ंक्शन के एलान वाली सूची में मॉडल को एक से ज़्यादा फ़ंक्शन दिए हों.
आपके ऐप्लिकेशन में यह सुविधा होनी चाहिए कि मॉडल, फ़ंक्शन कॉल के लिए अतिरिक्त अनुरोध कर सकता है.
मॉडल, एक ही समय पर कई फ़ंक्शन को कॉल करने के लिए कह सकता है.
मॉडल को फ़ंक्शन के बारे में जानकारी देने के लिए, फ़ंक्शन के एलान वाली सूची में ज़्यादा से ज़्यादा 128 फ़ंक्शन दिए जा सकते हैं. इस जानकारी के आधार पर, मॉडल यह तय कर सकता है कि फ़ाइनल जवाब जनरेट करने के लिए, उसे एक से ज़्यादा फ़ंक्शन की ज़रूरत है. साथ ही, यह इनमें से कुछ फ़ंक्शन को एक साथ कॉल कर सकता है. इसे पैरलल फ़ंक्शन कॉलिंग कहा जाता है.
आपके ऐप्लिकेशन में यह सुविधा होनी चाहिए कि मॉडल एक ही समय पर कई फ़ंक्शन चलाने के लिए कह सकता है. साथ ही, आपके ऐप्लिकेशन को मॉडल को सभी फ़ंक्शन के जवाब देने होंगे.
आपके पास यह कंट्रोल करने का विकल्प होता है कि मॉडल, फ़ंक्शन को कॉल करने के लिए कैसे और कब कहेगा.
आपके पास यह तय करने का विकल्प होता है कि मॉडल को दिए गए फ़ंक्शन के एलान का इस्तेमाल कैसे और कब करना चाहिए. इसे फ़ंक्शन कॉलिंग मोड सेट करना कहा जाता है. यहां कुछ उदाहरण दिए गए हैं:
मॉडल को यह चुनने की अनुमति देने के बजाय कि वह तुरंत नैचुरल भाषा में जवाब दे या फ़ंक्शन कॉल का इस्तेमाल करे, उसे हमेशा फ़ंक्शन कॉल का इस्तेमाल करने के लिए मजबूर किया जा सकता है. इसे फ़ंक्शन कॉलिंग को मजबूर करना कहा जाता है.
अगर आपने फ़ंक्शन के एक से ज़्यादा एलान दिए हैं, तो मॉडल को सिर्फ़ दिए गए फ़ंक्शन के सबसेट का इस्तेमाल करने के लिए सीमित किया जा सकता है.
इन शर्तों (या मोड) को लागू करने के लिए, प्रॉम्प्ट और फ़ंक्शन के एलान के साथ-साथ टूल कॉन्फ़िगरेशन (toolConfig
) जोड़ें. टूल कॉन्फ़िगरेशन में, इनमें से कोई एक मोड तय किया जा सकता है. सबसे ज़्यादा काम का मोड ANY
है.
मोड | ब्यौरा |
---|---|
AUTO |
मॉडल का डिफ़ॉल्ट बिहेवियर. मॉडल यह तय करता है कि फ़ंक्शन कॉल का इस्तेमाल करना है या सामान्य भाषा में जवाब देना है. |
ANY |
मॉडल को फ़ंक्शन कॉल ("फ़ोर्स्ड फ़ंक्शन कॉलिंग") का इस्तेमाल करना चाहिए. अगर आपको मॉडल को फ़ंक्शन के किसी सबसेट तक सीमित करना है, तो allowedFunctionNames में उन फ़ंक्शन के नाम डालें जिनका इस्तेमाल किया जा सकता है.
|
NONE |
मॉडल को फ़ंक्शन कॉल का इस्तेमाल नहीं करना चाहिए. यह व्यवहार, फ़ंक्शन के किसी भी एलान के बिना मॉडल के अनुरोध के बराबर है. |
तुम और क्या कर सकती हो?
अन्य सुविधाएं आज़माएं
- एक से ज़्यादा बार बातचीत (चैट) करने की सुविधा बनाएं.
- सिर्फ़ टेक्स्ट वाले प्रॉम्प्ट से टेक्स्ट जनरेट करना.
- इमेज, PDF, वीडियो, और ऑडियो जैसे अलग-अलग तरह की फ़ाइलों का इस्तेमाल करके, टेक्स्ट जनरेट करें.
कॉन्टेंट जनरेट करने की सुविधा को कंट्रोल करने का तरीका जानें
- प्रॉम्प्ट डिज़ाइन को समझें. इसमें सबसे सही तरीके, रणनीतियां, और उदाहरण के तौर पर दिए गए प्रॉम्प्ट शामिल हैं.
- मॉडल के पैरामीटर कॉन्फ़िगर करें. जैसे, Gemini के लिए तापमान और ज़्यादा से ज़्यादा आउटपुट टोकन या Imagen के लिए आसपेक्ट रेशियो (लंबाई-चौड़ाई का अनुपात) और व्यक्ति की जनरेशन.
- सुरक्षा सेटिंग का इस्तेमाल करें, ताकि आपको ऐसे जवाब मिलने की संभावना को कम किया जा सके जिन्हें नुकसान पहुंचाने वाला माना जा सकता है.
साथ काम करने वाले मॉडल के बारे में ज़्यादा जानें
अलग-अलग कामों के लिए उपलब्ध मॉडल और उनके कोटे और कीमत के बारे में जानें.Firebase AI Logic के साथ अपने अनुभव के बारे में सुझाव/राय दें या शिकायत करें