Gọi hàm bằng API Gemini

Các mô hình tạo sinh có khả năng giải quyết nhiều loại vấn đề. Tuy nhiên, các mô hình này bị hạn chế bởi những yếu tố như:

  • Chúng bị đóng băng sau khi được huấn luyện, dẫn đến kiến thức cũ.
  • Họ không thể truy vấn hoặc sửa đổi dữ liệu bên ngoài.

Tính năng gọi hàm có thể giúp bạn khắc phục một số hạn chế này. Lệnh gọi hàm đôi khi được gọi là sử dụng công cụ vì cho phép mô hình sử dụng các công cụ bên ngoài như API và hàm để tạo phản hồi cuối cùng.


Hướng dẫn này cho bạn biết cách triển khai chế độ thiết lập lệnh gọi hàm tương tự như tình huống được mô tả trong phần chính tiếp theo của trang này. Nhìn chung, sau đây là các bước để thiết lập tính năng gọi hàm trong ứng dụng của bạn:

  • Bước 1: Viết một hàm có thể cung cấp cho mô hình thông tin cần thiết để tạo phản hồi cuối cùng (ví dụ: hàm có thể gọi một API bên ngoài).

  • Bước 2: Tạo một khai báo hàm mô tả hàm và các tham số của hàm.

  • Bước 3: Cung cấp khai báo hàm trong quá trình khởi tạo mô hình để mô hình biết cách sử dụng hàm (nếu cần).

  • Bước 4: Thiết lập ứng dụng để mô hình có thể gửi thông tin bắt buộc để ứng dụng gọi hàm.

  • Bước 5: Truyền phản hồi của hàm trở lại mô hình để mô hình có thể tạo phản hồi cuối cùng.

Chuyển đến phần triển khai mã

Tổng quan về ví dụ về lệnh gọi hàm

Khi gửi yêu cầu đến mô hình, bạn cũng có thể cung cấp cho mô hình một bộ "công cụ" (chẳng hạn như các hàm) mà mô hình có thể dùng để tạo phản hồi cuối cùng. Để sử dụng các hàm này và gọi chúng ("gọi hàm"), mô hình và ứng dụng của bạn cần truyền thông tin qua lại cho nhau. Vì vậy, cách nên dùng để gọi hàm là thông qua giao diện trò chuyện nhiều lượt.

Hãy tưởng tượng rằng bạn có một ứng dụng mà người dùng có thể nhập một câu lệnh như: What was the weather in Boston on October 17, 2024?.

Các mô hình Gemini có thể không biết thông tin thời tiết này; tuy nhiên, hãy tưởng tượng rằng bạn biết đến một API dịch vụ thời tiết bên ngoài có thể cung cấp thông tin này. Bạn có thể sử dụng tính năng gọi hàm để cung cấp cho mô hình Gemini một đường dẫn đến API đó và thông tin thời tiết của API.

Trước tiên, bạn viết một hàm fetchWeather trong ứng dụng tương tác với API bên ngoài giả định này, có đầu vào và đầu ra như sau:

Thông số Loại Bắt buộc Nội dung mô tả
Mục nhập
location Đối tượng Tên của thành phố và tiểu bang mà bạn muốn xem thời tiết.
Chỉ hỗ trợ các thành phố ở Hoa Kỳ. Phải luôn là một đối tượng lồng nhau của citystate.
date Chuỗi Ngày cần tìm nạp thông tin thời tiết (phải luôn ở định dạng YYYY-MM-DD).
Đầu ra
temperature Số nguyên Nhiệt độ (tính bằng độ F)
chancePrecipitation Chuỗi Khả năng có mưa (biểu thị bằng tỷ lệ phần trăm)
cloudConditions Chuỗi Điều kiện về đám mây (một trong các điều kiện clear, partlyCloudy, mostlyCloudy, cloudy)

Khi khởi tạo mô hình, bạn cho mô hình biết rằng hàm fetchWeather này tồn tại và cách sử dụng hàm này để xử lý các yêu cầu đến (nếu cần). Đây được gọi là "khai báo hàm". Mô hình không gọi trực tiếp hàm . Thay vào đó, khi mô hình đang xử lý yêu cầu đến, mô hình sẽ quyết định xem hàm fetchWeather có thể giúp mô hình phản hồi yêu cầu hay không. Nếu mô hình quyết định rằng hàm này thực sự hữu ích, thì mô hình sẽ tạo dữ liệu có cấu trúc giúp ứng dụng của bạn gọi hàm.

Xem lại yêu cầu đến: What was the weather in Boston on October 17, 2024?. Mô hình có thể quyết định rằng hàm fetchWeather có thể giúp mô hình tạo ra một câu trả lời. Mô hình sẽ xem những tham số đầu vào nào cần thiết cho fetchWeather, sau đó tạo dữ liệu đầu vào có cấu trúc cho hàm có dạng như sau:

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

Mô hình này truyền dữ liệu đầu vào có cấu trúc này đến ứng dụng của bạn để ứng dụng có thể gọi hàm fetchWeather. Khi ứng dụng của bạn nhận được thông tin về điều kiện thời tiết từ API, ứng dụng sẽ chuyển thông tin đó cho mô hình. Thông tin thời tiết này cho phép mô hình hoàn tất quá trình xử lý cuối cùng và tạo phản hồi cho yêu cầu ban đầu của What was the weather in Boston on October 17, 2024?

Mô hình có thể đưa ra câu trả lời cuối cùng bằng ngôn ngữ tự nhiên như: On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.

Sơ đồ minh hoạ cách tính năng gọi hàm liên quan đến việc mô hình tương tác với một hàm trong ứng dụng của bạn 

Bạn có thể tìm hiểu thêm về tính năng gọi hàm trong tài liệu Gemini Developer API.

Triển khai tính năng gọi hàm

Các bước sau đây trong hướng dẫn này sẽ hướng dẫn bạn cách triển khai chế độ thiết lập lệnh gọi hàm tương tự như quy trình được mô tả trong phần Tổng quan về ví dụ gọi hàm (xem phần trên cùng của trang này).

Trước khi bắt đầu

Nhấp vào nhà cung cấp Gemini API để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Nếu bạn chưa thực hiện, hãy hoàn tất hướng dẫn bắt đầu sử dụng. Hướng dẫn này mô tả cách thiết lập dự án Firebase, kết nối ứng dụng với Firebase, thêm SDK, khởi động dịch vụ phụ trợ cho nhà cung cấp Gemini API mà bạn chọn và tạo một thực thể GenerativeModel.

Để kiểm thử và lặp lại các câu lệnh, thậm chí nhận được một đoạn mã được tạo, bạn nên sử dụng Google AI Studio.

Bước 1: Viết hàm

Hãy tưởng tượng rằng bạn có một ứng dụng mà người dùng có thể nhập một câu lệnh như: What was the weather in Boston on October 17, 2024?. Các mô hình Gemini có thể không biết thông tin thời tiết này; tuy nhiên, hãy tưởng tượng rằng bạn biết về một API dịch vụ thời tiết bên ngoài có thể cung cấp thông tin này. Tình huống trong hướng dẫn này dựa vào API bên ngoài giả định này.

Viết hàm trong ứng dụng sẽ tương tác với API bên ngoài giả định và cung cấp cho mô hình thông tin cần thiết để tạo yêu cầu cuối cùng. Trong ví dụ về thời tiết này, đó sẽ là một hàm fetchWeather thực hiện lệnh gọi đến API bên ngoài giả định này.

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"},
  };
}

Bước 2: Tạo một khai báo hàm

Tạo khai báo hàm mà sau này bạn sẽ cung cấp cho mô hình (bước tiếp theo của hướng dẫn này).

Trong phần khai báo, hãy cung cấp càng nhiều thông tin chi tiết càng tốt trong phần mô tả về hàm và các tham số của hàm.

Mô hình sử dụng thông tin trong khai báo hàm để xác định hàm cần chọn và cách cung cấp giá trị tham số cho lệnh gọi thực tế đến hàm. Xem phần Các hành vi và lựa chọn khác ở phần sau của trang này để biết cách mô hình có thể chọn trong số các hàm, cũng như cách bạn có thể kiểm soát lựa chọn đó.

Lưu ý những điều sau đây về giản đồ mà bạn cung cấp:

  • Bạn phải cung cấp khai báo hàm theo định dạng giản đồ tương thích với giản đồ OpenAPI. Vertex AI cung cấp dịch vụ hỗ trợ có giới hạn cho giản đồ OpenAPI.

    • Các thuộc tính sau được hỗ trợ: type, nullable, required, format, description, properties, items, enum.

    • Không hỗ trợ các thuộc tính sau: default, optional, maximum, oneOf.

  • Theo mặc định, đối với các SDK Firebase AI Logic, tất cả các trường đều được coi là bắt buộc, trừ phi bạn chỉ định chúng là không bắt buộc trong một mảng optionalProperties. Đối với các trường không bắt buộc này, mô hình có thể điền sẵn hoặc bỏ qua các trường. Xin lưu ý rằng điều này ngược lại với hành vi mặc định của hai nhà cung cấp Gemini API nếu bạn sử dụng SDK máy chủ hoặc API của họ một cách trực tiếp.

Để biết các phương pháp hay nhất liên quan đến khai báo hàm, bao gồm cả các mẹo về tên và nội dung mô tả, hãy xem Các phương pháp hay nhất trong tài liệu Gemini Developer API.

Sau đây là cách bạn có thể viết một nội dung khai báo hàm:

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."
    )}
  }
));

Bước 3: Cung cấp khai báo hàm trong quá trình khởi tạo mô hình

Bạn có thể cung cấp tối đa 128 khai báo hàm bằng yêu cầu. Xem phần Các hành vi và lựa chọn khác ở phần sau của trang này để biết cách mô hình có thể chọn trong số các hàm, cũng như cách bạn có thể kiểm soát lựa chọn đó (bằng cách sử dụng toolConfig để đặt chế độ gọi hàm).

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

Tìm hiểu cách chọn một mô hình phù hợp với trường hợp sử dụng và ứng dụng của bạn.

Bước 4: Gọi hàm để gọi API bên ngoài

Nếu mô hình quyết định rằng hàm fetchWeather thực sự có thể giúp mô hình tạo ra một phản hồi cuối cùng, thì ứng dụng của bạn cần thực hiện lệnh gọi thực tế đến hàm đó bằng cách sử dụng dữ liệu đầu vào có cấu trúc do mô hình cung cấp.

Vì thông tin cần được truyền qua lại giữa mô hình và ứng dụng, nên cách được đề xuất để sử dụng tính năng gọi hàm là thông qua giao diện trò chuyện nhiều lượt.

Đoạn mã sau đây cho thấy cách ứng dụng của bạn được thông báo rằng mô hình muốn sử dụng hàm fetchWeather. Điều này cũng cho thấy rằng mô hình đã cung cấp các giá trị tham số đầu vào cần thiết cho lệnh gọi hàm (và API bên ngoài cơ bản của lệnh gọi hàm).

Trong ví dụ này, yêu cầu đến chứa câu lệnh What was the weather in Boston on October 17, 2024?. Từ câu lệnh này, mô hình đã suy luận các tham số đầu vào mà hàm fetchWeather yêu cầu (tức là city, statedate).

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) {
  for (final functionCall in functionCalls) {
    if (functionCall.name == 'fetchWeather') {
      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);
      // Send the response to the model so that it can use the result to
      // generate text for the user.
      response = await functionCallChat.sendMessage(
        Content.functionResponse(functionCall.name, functionResult),
      );
    }
  }
} 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.
}

Bước 5: Cung cấp đầu ra của hàm cho mô hình để tạo phản hồi cuối cùng

Sau khi hàm fetchWeather trả về thông tin thời tiết, ứng dụng của bạn cần truyền thông tin đó trở lại mô hình.

Sau đó, mô hình sẽ thực hiện quy trình xử lý cuối cùng và tạo ra một câu trả lời cuối cùng bằng ngôn ngữ tự nhiên, chẳng hạn như: 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.");

Các hành vi và lựa chọn khác

Sau đây là một số hành vi bổ sung đối với tính năng gọi hàm mà bạn cần điều chỉnh trong mã và các lựa chọn mà bạn có thể kiểm soát.

Mô hình có thể yêu cầu gọi lại một hàm hoặc gọi một hàm khác.

Nếu phản hồi từ một lệnh gọi hàm là không đủ để mô hình tạo phản hồi cuối cùng, thì mô hình có thể yêu cầu một lệnh gọi hàm bổ sung hoặc yêu cầu gọi một hàm hoàn toàn khác. Điều này chỉ có thể xảy ra nếu bạn cung cấp nhiều hàm cho mô hình trong danh sách khai báo hàm.

Ứng dụng của bạn cần đáp ứng yêu cầu rằng mô hình có thể yêu cầu các lệnh gọi hàm bổ sung.

Mô hình có thể yêu cầu gọi nhiều hàm cùng một lúc.

Bạn có thể cung cấp tối đa 128 hàm trong danh sách khai báo hàm cho mô hình. Do đó, mô hình có thể quyết định rằng cần nhiều hàm để giúp mô hình tạo ra phản hồi cuối cùng. Và có thể quyết định gọi một số hàm này cùng lúc – đây được gọi là gọi hàm song song.

Ứng dụng của bạn cần đáp ứng yêu cầu rằng mô hình có thể yêu cầu nhiều hàm chạy cùng lúc và ứng dụng của bạn cần cung cấp tất cả các phản hồi từ các hàm cho mô hình.

Bạn có thể kiểm soát cách thức và việc mô hình có thể yêu cầu gọi các hàm hay không.

Bạn có thể đặt một số ràng buộc về cách thức và liệu mô hình có nên sử dụng các khai báo hàm được cung cấp hay không. Đây được gọi là thiết lập chế độ gọi hàm. Sau đây là một số ví dụ:

  • Thay vì cho phép mô hình chọn giữa phản hồi bằng ngôn ngữ tự nhiên ngay lập tức và một lệnh gọi hàm, bạn có thể buộc mô hình luôn sử dụng lệnh gọi hàm. Đây được gọi là gọi hàm bắt buộc.

  • Nếu cung cấp nhiều khai báo hàm, bạn có thể hạn chế mô hình chỉ sử dụng một số hàm được cung cấp.

Bạn triển khai các ràng buộc (hoặc chế độ) này bằng cách thêm cấu hình công cụ (toolConfig) cùng với câu lệnh và khai báo hàm. Trong cấu hình công cụ, bạn có thể chỉ định một trong những chế độ sau. Chế độ hữu ích nhất là ANY.

Chế độ Nội dung mô tả
AUTO Hành vi mặc định của mô hình. Mô hình này quyết định có sử dụng lệnh gọi hàm hay câu trả lời bằng ngôn ngữ tự nhiên.
ANY Mô hình phải sử dụng lệnh gọi hàm ("lệnh gọi hàm bắt buộc"). Để giới hạn mô hình trong một tập hợp con các hàm, hãy chỉ định tên hàm được phép trong allowedFunctionNames.
NONE Mô hình không được sử dụng lệnh gọi hàm. Hành vi này tương đương với một yêu cầu mô hình mà không có bất kỳ khai báo hàm nào được liên kết.



Bạn có thể làm gì khác?

Dùng thử các tính năng khác

Tìm hiểu cách kiểm soát hoạt động tạo nội dung

Bạn cũng có thể thử nghiệm với các câu lệnh và cấu hình mô hình, thậm chí nhận được một đoạn mã được tạo bằng Google AI Studio.

Tìm hiểu thêm về các mô hình được hỗ trợ

Tìm hiểu về các mô hình có sẵn cho nhiều trường hợp sử dụnghạn mức cũng như giá của các mô hình đó.


Gửi ý kiến phản hồi về trải nghiệm của bạn với Firebase AI Logic