קריאה לפונקציה באמצעות ה-API של Gemini

מודלים גנרטיביים הם כלי יעיל לפתרון בעיות מסוגים שונים. עם זאת, יש מגבלות שחלות עליהם, כמו:

  • הידע שלהם קפוא אחרי האימון, ולכן הוא לא עדכני.
  • הם לא יכולים לשלוח שאילתות לנתונים חיצוניים או לשנות אותם.

התכונה 'קריאה להפעלת פונקציות' יכולה לעזור לכם להתגבר על חלק מההגבלות האלה. לפעמים קוראים לקריאה להפעלת פונקציות שימוש בכלים, כי הוא מאפשר למודל להשתמש בכלים חיצוניים כמו ממשקי 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 מחרוזת כן תנאים בענן (אחד מהערכים 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 Developer API.

הטמעה של בקשות להפעלת פונקציות

בשלבים הבאים במדריך הזה מוסבר איך להטמיע הגדרה של קריאה לפונקציה שדומה לתהליך העבודה שמתואר בסקירה כללית של דוגמה לקריאה לפונקציה (בחלק העליון של הדף הזה).

מודלים נתמכים

  • gemini-3.1-pro-preview
  • ‫gemini-3.8-flash (וגרסאות ישנות יותר: gemini-3.7-flash,‏ gemini-3.6-flash ו-gemini-3.5-flash)
  • ‫gemini-3.5-flash-lite (וגם gemini-3.1-flash-lite)

מודלים של Gemini 2.5 לשימוש כללי תומכים ביכולת הזו, אבל כולם הוצאו משימוש.

גם מודלים של Gemini Live API תומכים ביכולת הזו, אבל כל דוגמאות הקוד במדריך הזה הן למודלים של Gemini לשימוש כללי.

לפני שמתחילים

לוחצים על הספק Gemini API כדי לראות בדף הזה תוכן וקוד שספציפיים לספק.

אם עדיין לא עשיתם את זה, כדאי לעיין במדריך לתחילת העבודה, שבו מוסבר איך להגדיר את פרויקט Firebase, לקשר את האפליקציה ל-Firebase, להוסיף את ה-SDK, לאתחל את שירות לקצה העורפי עבור ספק 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. ‫Agent Platform מציע תמיכה מוגבלת בסכימת OpenAPI.

    • המאפיינים הנתמכים הם: type, ‏ nullable, ‏ required,‏ format, ‏ description, ‏ properties, ‏ items, ‏ enum.

    • המאפיינים הבאים לא נתמכים: default, optional, maximum, oneOf.

  • כברירת מחדל, כשמדובר ב-Firebase AI Logic SDK, כל השדות נחשבים שדות חובה, אלא אם מציינים אותם כשדות אופציונליים במערך optionalProperties. בשדות האופציונליים האלה, המודל יכול למלא את השדות או לדלג עליהם. שימו לב: ההתנהגות הזו הפוכה מההתנהגות שמוגדרת כברירת מחדל אצל שני הספקים האלה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 FirebaseAILogic

// 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_MODEL_NAME",
  // 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 = "<var>GEMINI_MODEL_NAME</var>",
    // 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("<var>GEMINI_MODEL_NAME</var>",
                        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_MODEL_NAME",
  // 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_MODEL_NAME',
       // 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_MODEL_NAME",
  // 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: "user", 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("user") {
    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("user",
  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 אסור למודל להשתמש בקריאות להפעלת פונקציות. ההתנהגות הזו מקבילה לבקשת מודל ללא הצהרות פונקציה משויכות.



מה עוד אפשר לעשות?

אפשר לנסות יכולות אחרות

איך שולטים ביצירת תוכן

אפשר גם להתנסות בהנחיות ובהגדרות של המודל, ואפילו לקבל קטע קוד שנוצר באמצעות Google AI Studio.

מידע נוסף על המודלים הנתמכים

מידע על המודלים שזמינים לתרחישי שימוש שונים, על המיכסות שלהם ועל המחירים.


רוצה לתת משוב על חוויית השימוש ב-Firebase AI Logic?