מדריך: קריאה לפונקציה באמצעות Gemini API


בזכות הקריאה של הפונקציות קל יותר לקבל פלט של נתונים מובְנים ממודלים גנרטיביים. לאחר מכן תוכלו להשתמש בפלטים האלה כדי לקרוא לממשקי API אחרים ולהחזיר למודל את נתוני התגובה הרלוונטיים. במילים אחרות, קריאה של פונקציות עוזרת לחבר מודלים גנרטיביים למערכות חיצוניות כדי שהתוכן שנוצר יכלול את המידע העדכני והמדויק ביותר.

אפשר לספק מודלים של Gemini עם תיאורים של פונקציות. אלו פונקציות שכותבים בשפה של האפליקציה (כלומר, לא Google Cloud Functions). יכול להיות שהמודל יבקש מכם לקרוא לפונקציה ולשלוח בחזרה את התוצאה כדי לעזור למודל לטפל בשאילתה.

למידע נוסף, מומלץ לקרוא את המאמר מבוא לקריאה לפונקציות.

הגדרת הפרויקט

לפני שמפעילים את Gemini API, צריך להגדיר את הפרויקט. הפרויקט כולל הגדרה של מפתח ה-API, הוספת ה-SDK ליחסי התלות של המפרסמים ואתחול המודל.

הגדרה של בקשה להפעלת פונקציה

במדריך הזה נציג למודל אינטראקציה עם ממשק API של המרת מטבעות היפותטית שתומך בפרמטרים הבאים:

פרמטר סוג חובה תיאור
currencyDate string כן התאריך של שליפת שער החליפין ל
(שחייב תמיד להיות בפורמט YYYY-MM-DD או הערך latest אם לא צוינה תקופת זמן)
currencyFrom string כן המטבע להמרה ממנו
currencyTo string no המטבע להמרה

דוגמה לבקשת API

{
  "currencyDate": "2024-04-17",
  "currencyFrom": "USD",
  "currencyTo": "SEK"
}

דוגמה לתגובת API

{
  "base": "USD",
  "date": "2024-04-17",
  "rates": {"SEK": 0.091}
}

שלב 1: יוצרים את הפונקציה ששולחת את בקשת ה-API

אם עדיין לא עשיתם זאת, קודם יוצרים את הפונקציה שמבצעת בקשת API.

למטרות הדגמה במדריך הזה, במקום לשלוח בקשת API בפועל, המערכת תחזיר ערכים כתובים בתוך הקוד באותו פורמט שיוחזר API בפועל.

Future<Map<String, Object?>> findExchangeRate(
  Map<String, Object?> arguments,
) async =>
    // This hypothetical API returns a JSON such as:
    // {"base":"USD","date":"2024-04-17","rates":{"SEK": 0.091}}
    {
      'date': arguments['currencyDate'],
      'base': arguments['currencyFrom'],
      'rates': <String, Object?>{arguments['currencyTo'] as String: 0.091}
    };

שלב 2: יוצרים הצהרה לגבי פונקציה

יוצרים את ההצהרה על הפונקציה שתעבירו למודל הגנרטיבי (השלב הבא במדריך).

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

final exchangeRateTool = FunctionDeclaration(
    'findExchangeRate',
    'Returns the exchange rate between currencies on given date.',
    Schema(SchemaType.object, properties: {
      'currencyDate': Schema(SchemaType.string,
          description: 'A date in YYYY-MM-DD format or '
              'the exact value "latest" if a time period is not specified.'),
      'currencyFrom': Schema(SchemaType.string,
          description: 'The currency code of the currency to convert from, '
              'such as "USD".'),
      'currencyTo': Schema(SchemaType.string,
          description: 'The currency code of the currency to convert to, '
              'such as "USD".')
    }, requiredProperties: [
      'currencyDate',
      'currencyFrom'
    ]));

שלב 3: מציינים את הצהרת הפונקציה במהלך אתחול המודל

מציינים את הצהרת הפונקציה כשמאתחלים את המודל הגנרטיבי על ידי העברתו לפרמטר tools של המודל:

final model = GenerativeModel(
  // Use a model that supports function calling, like Gemini 1.0 Pro
  // See "Supported models" in the "Introduction to function calling" page.
  model: 'gemini-1.0-pro',
  apiKey: apiKey,

  // Specify the function declaration.
  tools: [
    Tool(functionDeclarations: [exchangeRateTool])
  ],
);

שלב 4: יוצרים קריאה לפונקציה

עכשיו אפשר להריץ את המודל באמצעות הפונקציה המוגדרת.

הדרך המומלצת להשתמש בקריאות עם פונקציות היא באמצעות ממשק הצ'אט, כי קריאות לפונקציות משתלבות יפה במבנה של מספר הפניות.

final chat = model.startChat();
final prompt = 'How much is 50 US dollars worth in Swedish krona?';

// Send the message to the generative model.
var response = await chat.sendMessage(Content.text(prompt));

final functionCalls = response.functionCalls.toList();
// When the model response with a function call, invoke the function.
if (functionCalls.isNotEmpty) {
  final functionCall = functionCalls.first;
  final result = switch (functionCall.name) {
    // Forward arguments to the hypothetical API.
    'findExchangeRate' => await findExchangeRate(functionCall.args),
    // Throw an exception if the model attempted to call a function that was
    // not declared.
    _ => throw UnimplementedError(
        'Function not implemented: ${functionCall.name}')
  };
  // Send the response to the model so that it can use the result to generate
  // text for the user.
  response = await chat
      .sendMessage(Content.functionResponse(functionCall.name, result));
}
// When the model responds with non-null text content, print it.
if (response.text case final text?) {
  print(text);
}