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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

ก่อนอื่น คุณต้องเขียนฟังก์ชัน 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 จากนั้นจะสร้าง Structured Data ของอินพุตสําหรับฟังก์ชันซึ่งมีลักษณะคร่าวๆ ดังนี้

{
  functionName: fetchWeather,
  location: {
    city: Boston,
    state: Massachusetts  // the model can infer the state from the prompt
  },
  date: 2024-10-17
}

โมเดลจะส่ง Structured Data ของอินพุตนี้ไปยังแอปเพื่อให้แอปเรียกใช้ฟังก์ชัน 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 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: สร้างประกาศฟังก์ชัน

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

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

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

โปรดคำนึงถึงสิ่งต่อไปนี้เกี่ยวกับสคีมาที่คุณระบุ

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

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

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

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

// 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-2.0-flash",
  // 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 = "gemini-2.0-flash",
    // 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("gemini-2.0-flash",
                        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-2.0-flash",
  // 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-2.0-flash',
       // 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-2.0-flash",
  // Provide the function declaration to the model.
  tools: new Tool[] { fetchWeatherTool }
);

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

ขั้นตอนที่ 4: เรียกใช้ฟังก์ชันเพื่อเรียก API ภายนอก

หากโมเดลตัดสินใจว่าฟังก์ชัน fetchWeather จะช่วยสร้างคำตอบสุดท้ายได้จริง แอปของคุณจะต้องเรียกใช้ฟังก์ชันนั้นโดยใช้ Structured Input Data ที่โมเดลระบุ

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

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

ในตัวอย่างนี้ คําขอขาเข้ามีพรอมต์ What was the weather in Boston on October 17, 2024? จากพรอมต์นี้ โมเดลจะอนุมานพารามิเตอร์อินพุตที่จําเป็นสำหรับฟังก์ชัน fetchWeather (นั่นคือ city, state และ date)

Swift

let chat = model.startChat()
let prompt = "What was the weather in Boston on October 17, 2024?"

// Send the user's question (the prompt) to the model using multi-turn chat.
let response = try await chat.sendMessage(prompt)

var functionResponses = [FunctionResponsePart]()

// When the model responds with one or more function calls, invoke the function(s).
for functionCall in response.functionCalls {
  if functionCall.name == "fetchWeather" {
    // TODO(developer): Handle invalid arguments.
    guard case let .object(location) = functionCall.args["location"] else { fatalError() }
    guard case let .string(city) = location["city"] else { fatalError() }
    guard case let .string(state) = location["state"] else { fatalError() }
    guard case let .string(date) = functionCall.args["date"] else { fatalError() }

    functionResponses.append(FunctionResponsePart(
      name: functionCall.name,
      // Forward the structured input data prepared by the model
      // to the hypothetical external API.
      response: fetchWeather(city: city, state: state, date: date)
    ))
  }
  // TODO(developer): Handle other potential function calls, if any.
}

Kotlin

val prompt = "What was the weather in Boston on October 17, 2024?"
val chat = model.startChat()
// Send the user's question (the prompt) to the model using multi-turn chat.
val result = chat.sendMessage(prompt)

val functionCalls = result.functionCalls
// When the model responds with one or more function calls, invoke the function(s).
val fetchWeatherCall = functionCalls.find { it.name == "fetchWeather" }

// Forward the structured input data prepared by the model
// to the hypothetical external API.
val functionResponse = fetchWeatherCall?.let {
    // Alternatively, if your `Location` class is marked as @Serializable, you can use
    // val location = Json.decodeFromJsonElement<Location>(it.args["location"]!!)
    val location = Location(
        it.args["location"]!!.jsonObject["city"]!!.jsonPrimitive.content,
        it.args["location"]!!.jsonObject["state"]!!.jsonPrimitive.content
    )
    val date = it.args["date"]!!.jsonPrimitive.content
    fetchWeather(location, date)
}

Java

String prompt = "What was the weather in Boston on October 17, 2024?";
ChatFutures chatFutures = model.startChat();
// Send the user's question (the prompt) to the model using multi-turn chat.
ListenableFuture<GenerateContentResponse> response =
        chatFutures.sendMessage(new Content("user", List.of(new TextPart(prompt))));

ListenableFuture<JsonObject> handleFunctionCallFuture = Futures.transform(response, result -> {
    for (FunctionCallPart functionCall : result.getFunctionCalls()) {
        if (functionCall.getName().equals("fetchWeather")) {
            Map<String, JsonElement> args = functionCall.getArgs();
            JsonObject locationJsonObject =
                    JsonElementKt.getJsonObject(args.get("location"));
            String city =
                    JsonElementKt.getContentOrNull(
                            JsonElementKt.getJsonPrimitive(
                                    locationJsonObject.get("city")));
            String state =
                    JsonElementKt.getContentOrNull(
                            JsonElementKt.getJsonPrimitive(
                                    locationJsonObject.get("state")));
            Location location = new Location(city, state);

            String date = JsonElementKt.getContentOrNull(
                    JsonElementKt.getJsonPrimitive(
                            args.get("date")));
            return fetchWeather(location, date);
        }
    }
    return null;
}, Executors.newSingleThreadExecutor());

Web

const chat = model.startChat();
const prompt = "What was the weather in Boston on October 17, 2024?";

// Send the user's question (the prompt) to the model using multi-turn chat.
let result = await chat.sendMessage(prompt);
const functionCalls = result.response.functionCalls();
let functionCall;
let functionResult;
// When the model responds with one or more function calls, invoke the function(s).
if (functionCalls.length > 0) {
  for (const call of functionCalls) {
    if (call.name === "fetchWeather") {
      // Forward the structured input data prepared by the model
      // to the hypothetical external API.
      functionResult = await fetchWeather(call.args);
      functionCall = call;
    }
  }
}

Dart

final chat = _functionCallModel.startChat();
const prompt = 'What was the weather in Boston on October 17, 2024?';

// Send the user's question (the prompt) to the model using multi-turn chat.
var response = await chat.sendMessage(Content.text(prompt));

final functionCalls = response.functionCalls.toList();
// When the model responds with one or more function calls, invoke the function(s).
if (functionCalls.isNotEmpty) {
  final functionCall = functionCalls.first;
  if (functionCall.name == 'fetchWeather') {
    // Forward the structured input data prepared by the model
    // to the hypothetical external API.
    Map<String, dynamic> location =
        functionCall.args['location']! as Map<String, dynamic>;
    var date = functionCall.args['date']! as String;
    var city = location['city']! as String;
    var state = location['state']! as String;
    final functionResult = await fetchWeather(Location(city, state), date);
    ...
} else {
  throw UnimplementedError(
    'Function not declared to the model: ${functionCall.name}',
  );
}

Unity

var chat = model.StartChat();
var prompt = "What was the weather in Boston on October 17, 2024?";

// Send the user's question (the prompt) to the model using multi-turn chat.
var response = await chat.SendMessageAsync(prompt);

var functionResponses = new List<ModelContent>();

foreach (var functionCall in response.FunctionCalls) {
  if (functionCall.Name == "fetchWeather") {
    // TODO(developer): Handle invalid arguments.
    var city = functionCall.Args["city"] as string;
    var state = functionCall.Args["state"] as string;
    var date = functionCall.Args["date"] as string;

    functionResponses.Add(ModelContent.FunctionResponse(
      name: functionCall.Name,
      // Forward the structured input data prepared by the model
      // to the hypothetical external API.
      response: FetchWeather(city: city, state: state, date: date)
    ));
  }
  // TODO(developer): Handle other potential function calls, if any.
}

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

หลังจากฟังก์ชัน fetchWeather แสดงข้อมูลสภาพอากาศแล้ว แอปของคุณต้องส่งข้อมูลกลับไปยังโมเดล

จากนั้นโมเดลจะประมวลผลขั้นสุดท้ายและสร้างคำตอบสุดท้ายเป็นภาษาธรรมชาติ เช่น On October 17, 2024 in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.

Swift

// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
let finalResponse = try await chat.sendMessage(
  [ModelContent(role: "function", parts: functionResponses)]
)

// Log the text response.
print(finalResponse.text ?? "No text in response.")

Kotlin

// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
val finalResponse = chat.sendMessage(content("function") {
    part(FunctionResponsePart("fetchWeather", functionResponse!!))
})

// Log the text response.
println(finalResponse.text ?: "No text in response")

Java

ListenableFuture<GenerateContentResponse> modelResponseFuture = Futures.transformAsync(
  handleFunctionCallFuture,
  // Send the response(s) from the function back to the model
  // so that the model can use it to generate its final response.
  functionCallResult -> chatFutures.sendMessage(new Content("function",
  List.of(new FunctionResponsePart(
          "fetchWeather", functionCallResult)))),
  Executors.newSingleThreadExecutor());

Futures.addCallback(modelResponseFuture, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
  if (result.getText() != null) {
      // Log the text response.
      System.out.println(result.getText());
  }
}

@Override
public void onFailure(Throwable t) {
  // handle error
}
}, Executors.newSingleThreadExecutor());

Web

// Send the response from the function back to the model
// so that the model can use it to generate its final response.
result = await chat.sendMessage([
  {
    functionResponse: {
      name: functionCall.name, // "fetchWeather"
      response: functionResult,
    },
  },
]);
console.log(result.response.text());

Dart

// Send the response from the function back to the model
// so that the model can use it to generate its final response.
response = await chat
     .sendMessage(Content.functionResponse(functionCall.name, functionResult));

Unity

// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
var finalResponse = await chat.SendMessageAsync(functionResponses);

// Log the text response.
UnityEngine.Debug.Log(finalResponse.Text ?? "No text in response.");

ลักษณะการทํางานและตัวเลือกเพิ่มเติม

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

โมเดลอาจขอให้เรียกใช้ฟังก์ชันอีกครั้งหรือเรียกใช้ฟังก์ชันอื่น

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

แอปของคุณต้องรองรับการที่โมเดลอาจเรียกใช้ฟังก์ชันเพิ่มเติม

โมเดลอาจขอให้เรียกใช้ฟังก์ชันหลายรายการพร้อมกัน

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

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

คุณควบคุมวิธีที่โมเดลจะขอเรียกใช้ฟังก์ชันได้

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

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

  • หากมีการประกาศฟังก์ชันหลายรายการ คุณสามารถจํากัดให้โมเดลใช้เฉพาะฟังก์ชันย่อยที่ระบุไว้ได้

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

โหมด คำอธิบาย
AUTO ลักษณะการทํางานเริ่มต้นของรูปแบบ โมเดลจะตัดสินใจว่าจะเรียกใช้ฟังก์ชันหรือการตอบกลับด้วยภาษาธรรมชาติ
ANY โมเดลต้องใช้การเรียกใช้ฟังก์ชัน ("การเรียกใช้ฟังก์ชันแบบบังคับ") หากต้องการจำกัดรูปแบบให้ใช้ฟังก์ชันเพียงชุดย่อย ให้ระบุชื่อฟังก์ชันที่อนุญาตใน allowedFunctionNames
NONE โมเดลต้องไม่ใช้การเรียกฟังก์ชัน ลักษณะการทํางานนี้เทียบเท่ากับคําขอโมเดลที่ไม่มีประกาศฟังก์ชันที่เชื่อมโยง



คุณทำอะไรได้อีกบ้าง

ลองใช้ความสามารถอื่นๆ

ดูวิธีควบคุมการสร้างเนื้อหา

คุณยังทดสอบพรอมต์และการกําหนดค่ารูปแบบ รวมถึงรับข้อมูลโค้ดที่สร้างขึ้นโดยใช้ Google AI Studio ได้ด้วย

ดูข้อมูลเพิ่มเติมเกี่ยวกับรูปแบบที่รองรับ

ดูข้อมูลเกี่ยวกับรูปแบบที่ใช้ได้กับกรณีการใช้งานต่างๆ รวมถึงโควต้าและราคา


แสดงความคิดเห็นเกี่ยวกับประสบการณ์การใช้งาน Firebase AI Logic