מודלים גנרטיביים יכולים לפתור בעיות רבות. עם זאת, יש מגבלות שחלות עליהן, כמו:
- הידע שלהם קפוא אחרי האימון, ולכן הוא לא עדכני.
- הם לא יכולים לשלוח שאילתות לנתונים חיצוניים או לשנות אותם.
התקשרות לפונקציות יכולה לעזור לכם להתגבר על חלק מהמגבלות האלה. לפעמים קוראים לשימוש בפונקציות שימוש בכלים, כי הוא מאפשר למודל להשתמש בכלים חיצוניים כמו ממשקי API ופונקציות כדי ליצור את התשובה הסופית שלו.
במדריך הזה מוסבר איך להטמיע הגדרה של קריאה לפונקציה שדומה לתרחיש שמתואר בקטע הגדול הבא בדף הזה. באופן כללי, השלבים להגדרת קריאות לפונקציות באפליקציה הם:
שלב 1: כותבים פונקציה שיכולה לספק למודל את המידע שהוא צריך כדי ליצור את התשובה הסופית (לדוגמה, הפונקציה יכולה לקרוא ל-API חיצוני).
שלב 2: יוצרים הצהרה על פונקציה שמתארת את הפונקציה ואת הפרמטרים שלה.
שלב 3: מספקים את הצהרת הפונקציה במהלך אתחול המודל, כדי שהמודל יידע איך להשתמש בפונקציה, אם צריך.
שלב 4: מגדירים את האפליקציה כך שהמודל יוכל לשלוח את המידע הנדרש כדי שהאפליקציה תוכל להפעיל את הפונקציה.
שלב 5: מעבירים את התשובה של הפונקציה בחזרה למודל כדי שהמודל יוכל ליצור את התשובה הסופית שלו.
סקירה כללית של דוגמה להפעלת פונקציה
כששולחים בקשה למודל, אפשר גם לספק למודל קבוצה של 'כלים' (כמו פונקציות) שהוא יכול להשתמש בהם כדי ליצור את התשובה הסופית. כדי להשתמש בפונקציות האלה ולהפעיל אותן ('הפעלת פונקציות'), המודל והאפליקציה צריכים להעביר מידע אחד לשני. לכן, הדרך המומלצת להשתמש בהפעלת פונקציות היא באמצעות ממשק צ'אט מרובה-תורות.
נניח שיש לכם אפליקציה שבה משתמש יכול להזין הנחיה כמו:
What was the weather in Boston on October 17, 2024?
.
יכול להיות שהמודלים של Gemini לא יודעים את פרטי מזג האוויר האלה, אבל נניח שאתם מכירים API של שירות מזג אוויר חיצוני שיכול לספק אותם. אפשר להשתמש בהפעלת פונקציות כדי לספק למודל Gemini נתיב ל-API הזה ולמידע על מזג האוויר.
קודם כל, כותבים פונקציה fetchWeather
באפליקציה שמקיימת אינטראקציה עם ה-API החיצוני ההיפותטי הזה, שיש לו את הקלט והפלט הבאים:
פרמטר | סוג | חובה | תיאור |
---|---|---|---|
קלט | |||
location |
אובייקט | כן | שם העיר והמדינה שרוצים לקבל את נתוני מזג האוויר שלהן. יש תמיכה רק בערים בארה"ב. חייב להיות תמיד אובייקט מוטמע של city ושל state .
|
date |
מחרוזת | כן | התאריך שבו רוצים לקבל את נתוני מזג האוויר (חייב להיות בפורמט YYYY-MM-DD ).
|
פלט | |||
temperature |
מספר שלם | כן | טמפרטורה (בפרנהייט) |
chancePrecipitation |
מחרוזת | כן | סיכוי למשקעים (באחוזים) |
cloudConditions |
מחרוזת | כן | תנאי Cloud (אחד מהתנאים 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
. כשהאפליקציה מקבלת בחזרה מה-API את נתוני תנאי מזג האוויר, היא מעבירה את המידע למודל. המידע על מזג האוויר מאפשר למודל להשלים את העיבוד הסופי וליצור את התגובה לבקשה הראשונית של 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, להוסיף את ה-SDK, לאתחל את שירות ה-Backend עבור ספק Gemini API שבחרתם וליצור מופע GenerativeModel
.
כדי לבדוק את ההנחיות ולשפר אותן, ואפילו כדי לקבל קטע קוד שנוצר, מומלץ להשתמש ב-Google AI Studio.
שלב 1: כותבים את הפונקציה
נניח שיש לכם אפליקציה שבה משתמש יכול להזין הנחיה כמו:
What was the weather in Boston on October 17, 2024?
. Gemini
יכול להיות שהמודלים לא ידעו את פרטי מזג האוויר האלה, אבל נניח שאתם מכירים API של שירות מזג אוויר חיצוני שיכול לספק אותם. התרחיש במדריך הזה מבוסס על API חיצוני היפותטי.
כותבים באפליקציה את הפונקציה שתקיים אינטראקציה עם ה-API החיצוני ההיפותטי ותספק למודל את המידע שהוא צריך כדי ליצור את הבקשה הסופית. בדוגמה הזו של מזג האוויר, זו תהיה פונקציה fetchWeather
שמבצעת את הקריאה ל-API החיצוני ההיפותטי הזה.
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"},
};
}
שלב 2: יצירת הצהרה על פונקציה
יוצרים את הצהרת הפונקציה שתספקו בהמשך למודל (בשלב הבא במדריך הזה).
בהצהרה, חשוב לכלול כמה שיותר פרטים בתיאורים של הפונקציה והפרמטרים שלה.
המודל משתמש במידע בהצהרת הפונקציה כדי לקבוע איזו פונקציה לבחור ואיך לספק ערכי פרמטרים לקריאה בפועל לפונקציה. בהמשך הדף הזה מוסבר איך המודל עשוי לבחור בין הפונקציות, וגם איך אתם יכולים לשלוט בבחירה הזו. אפשר לעיין בקטע התנהגויות ואפשרויות נוספות.
חשוב לשים לב לנקודות הבאות לגבי הסכימה שאתם מספקים:
צריך לספק הצהרות על פונקציות בפורמט סכימה שתואם לסכימת OpenAPI. Vertex AI מציע תמיכה מוגבלת בסכימת OpenAPI.
המאפיינים הנתמכים הם:
type
, nullable
, required
,format
, description
, properties
, items
, enum
.המאפיינים הבאים לא נתמכים:
default
,optional
,maximum
,oneOf
.
כברירת מחדל, בכל השדות ב-SDK נדרש ערך required, אלא אם מציינים שהם אופציונליים במערך
optionalProperties
.Firebase AI Logic בשדות האופציונליים האלה, המודל יכול למלא את השדות או לדלג עליהם. הערה: ההתנהגות הזו הפוכה מההתנהגות שמוגדרת כברירת מחדל אצל שני ספקי Gemini API אם משתמשים בערכות ה-SDK שלהם לשרת או ב-API שלהם ישירות.
לשיטות מומלצות שקשורות להצהרות על פונקציות, כולל טיפים לשמות ולתיאורים, אפשר לעיין במאמר שיטות מומלצות במסמכי התיעוד של 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."
)}
}
));
שלב 3: מספקים את הצהרת הפונקציה במהלך אתחול המודל
המספר המקסימלי של הצהרות פונקציות שאפשר לספק בבקשה הוא 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 }
);
איך בוחרים מודל שמתאימים לתרחיש השימוש ולאפליקציה שלכם.
שלב 4: קוראים לפונקציה כדי להפעיל את ה-API החיצוני
אם המודל מחליט שהפונקציה fetchWeather
יכולה לעזור לו ליצור תשובה סופית, האפליקציה צריכה לבצע את הקריאה בפועל לפונקציה הזו באמצעות נתוני הקלט המובנים שסופקו על ידי המודל.
מכיוון שצריך להעביר מידע הלוך ושוב בין המודל לבין האפליקציה, הדרך המומלצת להשתמש בקריאה לפונקציה היא באמצעות ממשק הצ'אט מרובה-תורות.
קטע הקוד הבא מראה איך האפליקציה מקבלת הודעה שהמודל רוצה להשתמש בפונקציה fetchWeather
. הוא גם מראה שהמודל סיפק את ערכי פרמטרי הקלט הנדרשים לקריאה לפונקציה (ול-API החיצוני הבסיסי שלה).
בדוגמה הזו, הבקשה הנכנסת הכילה את ההנחיה 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.
}
שלב 5: מספקים את הפלט של הפונקציה למודל כדי ליצור את התשובה הסופית
אחרי שהפונקציה 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?