บทแนะนำ: การเรียกฟังก์ชันด้วย Gemini API


การเรียกฟังก์ชันช่วยให้คุณได้รับเอาต์พุตข้อมูลที่มีโครงสร้างจากโมเดล Generative ได้ง่ายขึ้น จากนั้นคุณสามารถใช้เอาต์พุตเหล่านี้เพื่อเรียกใช้ API อื่นๆ และส่งคืนข้อมูลการตอบกลับที่เกี่ยวข้องไปยังโมเดลได้ กล่าวคือ การเรียกใช้ฟังก์ชันช่วยให้คุณเชื่อมต่อโมเดล Generative กับระบบภายนอกได้ เพื่อให้เนื้อหาที่สร้างขึ้นมีข้อมูลที่ถูกต้องและเป็นปัจจุบันที่สุด

คุณระบุโมเดล 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: สร้างการประกาศฟังก์ชัน

สร้างการประกาศฟังก์ชันที่คุณจะส่งไปยังโมเดล Generative (ขั้นตอนถัดไปของบทแนะนำนี้)

ใส่รายละเอียดให้มากที่สุดเท่าที่จะทำได้ในฟังก์ชันและคำอธิบายพารามิเตอร์ โมเดล Generative ใช้ข้อมูลนี้เพื่อกําหนดฟังก์ชันที่ควรเลือกและวิธีระบุค่าสําหรับพารามิเตอร์ในการเรียกใช้ฟังก์ชัน

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: ระบุการประกาศฟังก์ชันระหว่างการเริ่มต้นโมเดล

ระบุการประกาศฟังก์ชันเมื่อเริ่มต้นโมเดล Generative โดยการตั้งค่าพารามิเตอร์ 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)