Gemini API を使用した関数呼び出し

生成モデルは、さまざまな問題の解決に効果的です。ただし、次のような制限があります。

  • トレーニングが完了するとその後は更新されないため、知識が最新ではなくなります。
  • 外部データのクエリや変更はできません。

関数呼び出しを使用すると、これらの制限の一部を克服できます。関数呼び出しは「ツールの使用」と呼ばれることもあります。これは、関数呼び出しによってモデルが API や関数などの外部ツールを使用して最終レスポンスを生成できるためです。


このガイドでは、このページの次の主要なセクションで説明するシナリオに似た関数呼び出しの設定を実装する方法について説明します。アプリで関数呼び出しを設定する大まかな手順は次のとおりです。

  • ステップ 1: 最終的なレスポンスを生成するためにモデルに必要な情報を提供できる関数を作成します(関数は外部 API を呼び出すことができます)。

  • ステップ 2: 関数とそのパラメータを記述する関数宣言を作成します。

  • ステップ 3: 必要に応じて、モデルの初期化時に関数宣言を提供して、モデルが関数を使用する方法を認識できるようにします。

  • ステップ 4: モデルがアプリが関数を呼び出すために必要な情報を送信できるようにアプリを設定します。

  • ステップ 5: 関数のレスポンスをモデルに渡して、モデルが最終的なレスポンスを生成できるようにします。

コードの実装に移動

関数呼び出しの例の概要

モデルにリクエストを送信するときに、モデルが最終的なレスポンスを生成するために使用できる一連の「ツール」(関数など)をモデルに提供することもできます。これらの関数を活用して呼び出す(「関数呼び出し」)には、モデルとアプリが情報を相互にやり取りする必要があります。そのため、関数呼び出しを使用するには、マルチターン チャット インターフェースを使用することをおすすめします。

ユーザーが次のようなプロンプトを入力できるアプリがあるとします。What was the weather in Boston on October 17, 2024?

Gemini モデルは、この気象情報を把握していない場合があります。ただし、それを提供できる外部気象サービス API があるとします。関数呼び出しを使用して、Gemini モデルにその API とその天気情報へのパスを提供できます。

まず、この架空の外部 API とやり取りする関数 fetchWeather をアプリに作成します。この関数には、次の入出力があります。

パラメータ 必須 説明
入力
location オブジェクト 天気を取得する都市の名前とその州。
米国の都市のみがサポートされています。常に citystate のネストされたオブジェクトにする必要があります。
date 文字列 天気を取得する日付(常に YYYY-MM-DD 形式にする必要があります)。
出力
temperature Integer 温度(華氏)
chancePrecipitation 文字列 降水確率(% 単位)
cloudConditions 文字列 雲の状態(clearpartlyCloudymostlyCloudycloudy のいずれか)

モデルを初期化するときに、この fetchWeather 関数が存在することと、必要に応じて受信リクエストの処理に使用できることをモデルに伝えます。これは「関数宣言」と呼ばれます。モデルは関数を直接呼び出しません。代わりに、モデルは受信したリクエストを処理するときに、fetchWeather 関数を使用してリクエストに応答できるかどうかを判断します。モデルが関数が実際に有用であると判断した場合、モデルはアプリが関数を呼び出すのに役立つ構造化データを生成します。

受信したリクエスト(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 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 とやり取りし、最終的なリクエストの生成に必要な情報をモデルに提供する関数をアプリに記述します。この天気予報の例では、この仮想の外部 API を呼び出すのは fetchWeather 関数です。

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 スキーマを限定的にサポートしています。

    • サポートされている属性は、typenullablerequiredformatdescriptionpropertiesitemsenum です。

    • defaultoptionalmaximumoneOf の属性はサポートされていません。

  • デフォルトでは、Firebase AI Logic SDK では、optionalProperties 配列で省略可能として指定しない限り、すべてのフィールドが必須と見なされます。これらの省略可能なフィールドの場合、モデルはフィールドにデータを入力することも、フィールドをスキップすることもできます。これは、サーバー SDK または API を直接使用する場合の 2 つの Gemini API プロバイダのデフォルトの動作とは逆です。

名前と説明に関するヒントなど、関数宣言に関するベスト プラクティスについては、Google Cloud ドキュメントの 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 関数が最終的なレスポンスを生成するのに役立つと判断した場合、アプリはモデルから提供された構造化入力データを使用して、その関数を実際に呼び出す必要があります。

モデルとアプリの間で情報をやり取りする必要があるため、関数呼び出しを使用する場合は、マルチターン チャット インターフェースを使用することをおすすめします。

次のコード スニペットは、モデルが fetchWeather 関数を使用することをアプリに通知する方法を示しています。また、モデルが関数呼び出し(およびその基盤となる外部 API)に必要な入力パラメータ値を提供していることも示しています。

この例では、受信したリクエストにプロンプト What was the weather in Boston on October 17, 2024? が含まれています。このプロンプトから、モデルは fetchWeather 関数に必要な入力パラメータ(citystatedate)を推論しました。

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 です。

Mode 説明
AUTO デフォルトのモデル動作。関数呼び出しと自然言語によるレスポンスのどちらを使用するかは、モデルが決定します。
ANY モデルは関数呼び出し(「強制関数呼び出し」)を使用する必要があります。モデルを関数のサブセットに制限するには、allowedFunctionNames で許可される関数名を指定します。
NONE モデルは関数呼び出しを使用しないでください。この動作は、関連する関数宣言のないモデル リクエストと同じです。



Google アシスタントの機能

その他の機能を試す

コンテンツ生成を制御する方法

プロンプトとモデル構成をテストしたり、Google AI Studio を使用して生成されたコード スニペットを取得したりすることもできます。

サポートされているモデルの詳細

さまざまなユースケースで利用可能なモデルと、その割り当て料金について学びます。


Firebase AI Logic の使用感に関するフィードバックを送信する