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


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

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

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

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

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

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

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

פרמטר סוג חובה תיאור
currencyFrom string כן המטבע להמרה ממנו
currencyTo string כן המטבע להמרה

דוגמה לבקשת API

{
  "currencyFrom": "USD",
  "currencyTo": "SEK"
}

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

{
  "base": "USD",
  "rates": {"SEK": 0.091}
}

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

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

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

func makeAPIRequest(currencyFrom: String,
                    currencyTo: String) -> JSONObject {
  // This hypothetical API returns a JSON such as:
  // {"base":"USD","rates":{"SEK": 0.091}}
  return [
    "base": .string(currencyFrom),
    "rates": .object([currencyTo: .number(0.091)]),
  ]
}

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

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

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

let getExchangeRate = FunctionDeclaration(
  name: "getExchangeRate",
  description: "Get the exchange rate for currencies between countries",
  parameters: [
    "currencyFrom": Schema(
      type: .string,
      description: "The currency to convert from."
    ),
    "currencyTo": Schema(
      type: .string,
      description: "The currency to convert to."
    ),
  ],
  requiredParameters: ["currencyFrom", "currencyTo"]
)

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

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

// Use a model that supports function calling, like Gemini 1.0 Pro.
// See "Supported models" in the "Introduction to function calling" page.
let generativeModel = GenerativeModel(
  name: "gemini-1.0-pro",
  apiKey: apiKey,
  // Specify the function declaration.
  tools: [Tool(functionDeclarations: [getExchangeRate])]
)

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

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

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

let chat = generativeModel.startChat()

let prompt = "How much is 50 US dollars worth in Swedish krona?"

// Send the message to the generative model
let response1 = try await chat.sendMessage(prompt)

// Check if the model responded with a function call
guard let functionCall = response1.functionCalls.first else {
  fatalError("Model did not respond with a function call.")
}
// Print an error if the returned function was not declared
guard functionCall.name == "getExchangeRate" else {
  fatalError("Unexpected function called: \(functionCall.name)")
}
// Verify that the names and types of the parameters match the declaration
guard case let .string(currencyFrom) = functionCall.args["currencyFrom"] else {
  fatalError("Missing argument: currencyFrom")
}
guard case let .string(currencyTo) = functionCall.args["currencyTo"] else {
  fatalError("Missing argument: currencyTo")
}

// Call the hypothetical API
let apiResponse = makeAPIRequest(currencyFrom: currencyFrom, currencyTo: currencyTo)

// Send the API response back to the model so it can generate a text response that can be
// displayed to the user.
let response = try await chat.sendMessage([ModelContent(
  role: "function",
  parts: [.functionResponse(FunctionResponse(
    name: functionCall.name,
    response: apiResponse
  ))]
)])

// Log the text response.
guard let modelResponse = response.text else {
  fatalError("Model did not respond with text.")
}
print(modelResponse)