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 をアプリに記述します。この API には次の入力と出力があります。

パラメータ 必須 説明
入力
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 配列で省略可能として指定しない限り、すべてのフィールドが必須と見なされます。これらの省略可能なフィールドでは、モデルはフィールドにデータを入力することも、フィールドをスキップすることもできます。なお、2 つの Gemini API プロバイダのサーバー SDK または 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.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 }
);

ユースケースとアプリに適したモデル を選択する方法について説明します。

ステップ 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) {
  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.
}

ステップ 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 の使用感についてフィードバックを送信する