การเรียกใช้ฟังก์ชันโดยใช้ Gemini API

โมเดลแบบ Generative มีประสิทธิภาพในการแก้ปัญหาหลายประเภท อย่างไรก็ตาม โมเดลเหล่านี้มีข้อจำกัด เช่น

  • โมเดลจะหยุดการอัปเดตหลังจากการฝึก ซึ่งทำให้ความรู้ล้าสมัย
  • ผู้ใช้จะค้นหาหรือแก้ไขข้อมูลภายนอกไม่ได้

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


คู่มือนี้จะแสดงวิธีตั้งค่าการเรียกใช้ฟังก์ชันที่คล้ายกับ สถานการณ์ที่อธิบายไว้ในส่วนหลักถัดไปของหน้านี้ ขั้นตอนการตั้งค่าการเรียกใช้ฟังก์ชันในแอปมีดังนี้

  • ขั้นตอนที่ 1: เขียนฟังก์ชันที่ให้ข้อมูลแก่โมเดลซึ่ง โมเดลต้องใช้ในการสร้างคำตอบสุดท้าย (เช่น ฟังก์ชันสามารถเรียก API ภายนอกได้)

  • ขั้นตอนที่ 2: สร้างการประกาศฟังก์ชันที่อธิบายฟังก์ชันและพารามิเตอร์ของฟังก์ชัน

  • ขั้นตอนที่ 3: ระบุการประกาศฟังก์ชันในระหว่างการเริ่มต้นโมเดลเพื่อให้ โมเดลทราบวิธีใช้ฟังก์ชันหากจำเป็น

  • ขั้นตอนที่ 4: ตั้งค่าแอปเพื่อให้โมเดลส่งข้อมูลที่จำเป็น เพื่อให้แอปเรียกใช้ฟังก์ชันได้

  • ขั้นตอนที่ 5: ส่งการตอบกลับของฟังก์ชันกลับไปยังโมเดลเพื่อให้โมเดล สร้างการตอบกลับสุดท้ายได้

ข้ามไปยังการติดตั้งใช้งานโค้ด

ภาพรวมของตัวอย่างการเรียกใช้ฟังก์ชัน

เมื่อส่งคำขอไปยังโมเดล คุณยังระบุชุด "เครื่องมือ" (เช่น ฟังก์ชัน) ที่โมเดลใช้เพื่อสร้างคำตอบสุดท้ายได้ด้วย ในการใช้ฟังก์ชันเหล่านี้และเรียกใช้ ("การเรียกใช้ฟังก์ชัน") โมเดล และแอปของคุณต้องส่งข้อมูลไปมาถึงกัน ดังนั้นวิธีที่แนะนำในการใช้การเรียกใช้ฟังก์ชันคือผ่านอินเทอร์เฟซแชทแบบการสนทนาไปมา

ลองนึกภาพว่าคุณมีแอปที่ผู้ใช้สามารถป้อนพรอมต์ เช่น What was the weather in Boston on October 17, 2024?

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

ก่อนอื่นให้เขียนฟังก์ชัน fetchWeather ในแอปที่โต้ตอบกับ API ภายนอกสมมติที่มีอินพุตและเอาต์พุตต่อไปนี้

พารามิเตอร์ ประเภท จำเป็น คำอธิบาย
อินพุต
location ออบเจ็กต์ ใช่ ชื่อเมืองและรัฐที่จะรับข้อมูลสภาพอากาศ
รองรับเฉพาะเมืองในสหรัฐอเมริกา ต้องเป็นออบเจ็กต์ที่ซ้อนกันของ city และ state เสมอ
date สตริง ใช่ วันที่ที่จะดึงข้อมูลสภาพอากาศ (ต้องอยู่ในรูปแบบ YYYY-MM-DD เสมอ)
เอาต์พุต
temperature จำนวนเต็ม ใช่ อุณหภูมิ (หน่วยเป็นฟาเรนไฮต์)
chancePrecipitation สตริง ใช่ โอกาสเกิดฝน/ลูกเห็บ/หิมะ (แสดงเป็นเปอร์เซ็นต์)
cloudConditions สตริง ใช่ สภาพอากาศ (clear, partlyCloudy, mostlyCloudy, cloudy)

เมื่อเริ่มต้นโมเดล คุณจะบอกโมเดลว่ามีfetchWeather ฟังก์ชันนี้อยู่ และวิธีใช้ฟังก์ชันนี้เพื่อประมวลผลคำขอขาเข้าหากจำเป็น ซึ่งเรียกว่า "การประกาศฟังก์ชัน" โมเดลไม่ได้เรียกใช้ฟังก์ชัน โดยตรง แต่ในขณะที่โมเดลประมวลผลคำขอที่เข้ามา โมเดลจะ พิจารณาว่าfetchWeatherฟังก์ชันจะช่วยตอบคำขอได้หรือไม่ หากโมเดลพิจารณาแล้วว่าฟังก์ชันนั้นมีประโยชน์จริง โมเดลจะสร้าง Structured Data ที่จะช่วยให้แอปของคุณเรียกใช้ฟังก์ชัน

ดูคำขอที่เข้ามาอีกครั้ง 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.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: สร้างการประกาศฟังก์ชัน

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

ในการประกาศ ให้ใส่รายละเอียดให้มากที่สุดในคำอธิบายสำหรับ ฟังก์ชันและพารามิเตอร์ของฟังก์ชัน

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

oxidized

  • คุณต้องระบุการประกาศฟังก์ชันในรูปแบบสคีมาที่เข้ากันได้ กับสคีมา OpenAPI Agent Platform รองรับสคีมา OpenAPI แบบจำกัด

    • แอตทริบิวต์ที่รองรับ ได้แก่ type, nullable, required, format, description, properties, items, enum

    • แอตทริบิวต์ต่อไปนี้ไม่รองรับ ได้แก่ default, optional, maximum, oneOf

  • โดยค่าเริ่มต้น สำหรับ Firebase AI Logic SDK ระบบจะถือว่าช่องทั้งหมดเป็นต้องระบุ เว้นแต่คุณจะระบุเป็นไม่บังคับในอาร์เรย์ optionalProperties สำหรับฟิลด์ที่ไม่บังคับเหล่านี้ โมเดลสามารถป้อนข้อมูลในฟิลด์หรือข้าม ฟิลด์ได้ โปรดทราบว่าลักษณะการทำงานนี้จะตรงกันข้ามกับลักษณะการทำงานเริ่มต้นของ Gemini APIผู้ให้บริการทั้ง 2 รายหากคุณใช้ 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 }
);

ดูวิธีเลือกโมเดล (ไม่บังคับ) ที่เหมาะสมกับกรณีการใช้งานและแอปของคุณ