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


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

คุณระบุโมเดล Gemini พร้อมคำอธิบายฟังก์ชันได้ ฟังก์ชันเหล่านี้เป็นฟังก์ชันที่คุณเขียนในภาษาของแอป (ซึ่งไม่ใช่ Google Cloud Functions) โมเดลอาจขอให้คุณเรียกฟังก์ชันและส่งผลลัพธ์กลับมาเพื่อช่วยให้โมเดลจัดการกับคำค้นหาของคุณ

ดูข้อมูลเพิ่มเติมได้ในข้อมูลเบื้องต้นเกี่ยวกับการเรียกใช้ฟังก์ชัน หากยังไม่ได้อ่าน

ตั้งค่าโปรเจ็กต์

ก่อนที่จะเรียกใช้ Gemini API คุณต้องตั้งค่าโปรเจ็กต์ ซึ่งรวมถึงการตั้งค่าคีย์ API การเพิ่ม SDK ไปยังทรัพยากร Dependency ของผู้เผยแพร่โฆษณา และการเริ่มต้นโมเดล

ตั้งค่าการเรียกใช้ฟังก์ชัน

สำหรับบทแนะนำนี้ คุณจะให้โมเดลโต้ตอบกับ API การแลกเปลี่ยนสกุลเงินสมมติที่รองรับพารามิเตอร์ต่อไปนี้

พารามิเตอร์ ประเภท จำเป็น คำอธิบาย
currencyDate string ใช่ วันที่ที่จะดึงข้อมูลอัตราแลกเปลี่ยน
(ซึ่งต้องอยู่ในรูปแบบ YYYY-MM-DD เสมอ หรือค่า latest หากไม่ได้ระบุระยะเวลา)
currencyFrom string ใช่ สกุลเงินที่จะแปลง
currencyTo string ไม่ สกุลเงินที่จะแปลง

ตัวอย่างคำขอ 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: สร้างการประกาศฟังก์ชัน

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

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

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

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