با استفاده از Gemini API تماس را انجام دهید

مدل‌های مولد در حل انواع مختلفی از مسائل قدرتمند هستند. با این حال، محدودیت‌هایی مانند موارد زیر آنها را محدود می‌کند:

  • آنها پس از آموزش منجمد می‌شوند و این منجر به دانش کهنه می‌شود.
  • آنها نمی‌توانند داده‌های خارجی را جستجو یا تغییر دهند.

فراخوانی تابع می‌تواند به شما در غلبه بر برخی از این محدودیت‌ها کمک کند. فراخوانی تابع گاهی اوقات به عنوان استفاده از ابزار شناخته می‌شود زیرا به یک مدل اجازه می‌دهد تا از ابزارهای خارجی مانند APIها و توابع برای تولید پاسخ نهایی خود استفاده کند.


این راهنما به شما نشان می‌دهد که چگونه می‌توانید یک فراخوانی تابع مشابه سناریویی که در بخش اصلی بعدی این صفحه توضیح داده شده است را پیاده‌سازی کنید. در سطح بالا، مراحل راه‌اندازی فراخوانی تابع در برنامه شما به شرح زیر است:

  • مرحله ۱ : تابعی بنویسید که بتواند اطلاعات مورد نیاز مدل برای تولید پاسخ نهایی را در اختیار آن قرار دهد (برای مثال، این تابع بتواند یک API خارجی را فراخوانی کند).

  • مرحله ۲ : یک اعلان تابع ایجاد کنید که تابع و پارامترهای آن را توصیف کند.

  • مرحله ۳ : تعریف تابع را در طول مقداردهی اولیه مدل ارائه دهید تا مدل بداند در صورت نیاز چگونه می‌تواند از تابع استفاده کند.

  • مرحله ۴ : برنامه خود را طوری تنظیم کنید که مدل بتواند اطلاعات مورد نیاز را برای فراخوانی تابع توسط برنامه ارسال کند.

  • مرحله ۵ : پاسخ تابع را به مدل برگردانید تا مدل بتواند پاسخ نهایی خود را تولید کند.

پرش به پیاده‌سازی کد

مرور کلی یک مثال فراخوانی تابع

وقتی درخواستی را به مدل ارسال می‌کنید، می‌توانید مجموعه‌ای از «ابزارها» (مانند توابع) را نیز در اختیار مدل قرار دهید که می‌تواند از آنها برای تولید پاسخ نهایی خود استفاده کند. برای استفاده از این توابع و فراخوانی آنها ("فراخوانی تابع")، مدل و برنامه شما باید اطلاعات را به صورت متقابل به یکدیگر منتقل کنند، بنابراین روش توصیه شده برای استفاده از فراخوانی تابع از طریق رابط چت چند نوبته است.

تصور کنید که برنامه‌ای دارید که در آن کاربر می‌تواند سوالی مانند این را وارد کند: 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 می‌تواند به آن در پاسخ به درخواست کمک کند یا خیر. اگر مدل تصمیم بگیرد که این تابع واقعاً می‌تواند مفید باشد، مدل داده‌های ساختاریافته‌ای تولید می‌کند که به برنامه شما در فراخوانی تابع کمک می‌کند.

دوباره به درخواست ورودی نگاه کنید: 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 بیابید.

پیاده‌سازی فراخوانی تابع

مراحل زیر در این راهنما به شما نشان می‌دهد که چگونه یک فراخوانی تابع را مشابه گردش کاری که در «مروری بر مثال فراخوانی تابع» (به بخش بالای این صفحه مراجعه کنید) شرح داده شده است، پیاده‌سازی کنید.

قبل از اینکه شروع کنی

برای مشاهده محتوا و کد مخصوص ارائه‌دهنده در این صفحه، روی ارائه‌دهنده API Gemini خود کلیک کنید.

اگر هنوز این کار را نکرده‌اید، راهنمای شروع به کار را تکمیل کنید، که نحوه راه‌اندازی پروژه Firebase، اتصال برنامه به Firebase، افزودن SDK، راه‌اندازی سرویس backend برای ارائه‌دهنده API انتخابی Gemini و ایجاد یک نمونه GenerativeModel را شرح می‌دهد.

برای آزمایش و تکرار روی درخواست‌هایتان، توصیه می‌کنیم از Google AI Studio استفاده کنید.

مرحله ۱ : نوشتن تابع

تصور کنید که برنامه‌ای دارید که کاربر می‌تواند در آن سوالی مانند این را وارد کند: What was the weather in Boston on October 17, 2024? . ممکن است مدل‌های Gemini این اطلاعات آب و هوایی را ندانند؛ با این حال، تصور کنید که شما یک API سرویس آب و هوای خارجی دارید که می‌تواند آن را ارائه دهد. سناریوی این راهنما بر اساس این API خارجی فرضی است.

تابعی را در برنامه خود بنویسید که با API خارجی فرضی تعامل داشته باشد و اطلاعات مورد نیاز مدل برای تولید درخواست نهایی را در اختیار آن قرار دهد. در این مثال آب و هوا، تابع fetchWeather این API خارجی فرضی را فراخوانی می‌کند.

سویفت

// 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;
}

وحدت

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

مرحله ۲ : ایجاد یک اعلان تابع

تعریف تابعی را که بعداً به مدل ارائه خواهید داد (مرحله بعدی این راهنما) ایجاد کنید.

در تعریف تابع، تا حد امکان جزئیات مربوط به تابع و پارامترهای آن را ذکر کنید.

مدل از اطلاعات موجود در اعلان تابع برای تعیین اینکه کدام تابع را انتخاب کند و چگونه مقادیر پارامتر را برای فراخوانی واقعی تابع ارائه دهد، استفاده می‌کند. برای نحوه انتخاب مدل از بین توابع و همچنین نحوه کنترل آن انتخاب، به بخش رفتارها و گزینه‌های اضافی در ادامه این صفحه مراجعه کنید.

در مورد طرحواره‌ای که ارائه می‌دهید، به نکات زیر توجه کنید:

  • شما باید اعلان‌های تابع را در قالبی از طرحواره ارائه دهید که با طرحواره OpenAPI سازگار باشد. Vertex AI پشتیبانی محدودی از طرحواره OpenAPI ارائه می‌دهد.

    • ویژگی های زیر پشتیبانی می شوند: type ، nullable ، required ، format ، description ، properties ، items ، enum .

    • ویژگی‌های زیر پشتیبانی نمی‌شوند : default ، optional ، maximum ، oneOf .

  • به طور پیش‌فرض، برای Firebase AI Logic SDKها، همه فیلدها الزامی در نظر گرفته می‌شوند، مگر اینکه آنها را در یک آرایه optionalProperties به عنوان اختیاری مشخص کنید. برای این فیلدهای اختیاری، مدل می‌تواند فیلدها را پر کند یا از آنها صرف نظر کند. توجه داشته باشید که این برخلاف رفتار پیش‌فرض دو ارائه‌دهنده API Gemini است اگر از SDKهای سرور یا API آنها مستقیماً استفاده کنید.

برای بهترین شیوه‌های مربوط به اعلان‌های تابع، از جمله نکاتی برای نام‌ها و توضیحات، بهبهترین شیوه‌ها در مستندات رابط برنامه‌نویسی کاربردی (API) توسعه‌دهندگان Gemini .

در اینجا نحوه نوشتن اعلان تابع را مشاهده می‌کنید:

سویفت

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

وحدت

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

مرحله ۳ : ارائه تعریف تابع در طول مقداردهی اولیه مدل

حداکثر تعداد اعلان‌های تابع که می‌توانید با درخواست ارائه دهید، ۱۲۸ است. برای نحوه انتخاب مدل از بین توابع و همچنین نحوه کنترل آن انتخاب (با استفاده از toolConfig برای تنظیم حالت فراخوانی تابع )، به بخش رفتارها و گزینه‌های اضافی در ادامه همین صفحه مراجعه کنید.

سویفت


import FirebaseAILogic

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "gemini-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]),
       ],
     );

وحدت


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

یاد بگیرید که چگونه یک مدل را انتخاب کنیدمناسب برای مورد استفاده و برنامه شما.

مرحله ۴ : فراخوانی تابع برای فراخوانی API خارجی

اگر مدل تصمیم بگیرد که تابع fetchWeather می‌تواند در تولید پاسخ نهایی به آن کمک کند، برنامه شما باید با استفاده از داده‌های ورودی ساختاریافته ارائه شده توسط مدل، فراخوانی واقعی آن تابع را انجام دهد.

از آنجایی که اطلاعات باید بین مدل و برنامه به صورت رفت و برگشتی رد و بدل شوند، روش پیشنهادی برای فراخوانی تابع از طریق رابط چت چند نوبتی است.

قطعه کد زیر نشان می‌دهد که چگونه به برنامه شما گفته می‌شود که مدل می‌خواهد از تابع fetchWeather استفاده کند. همچنین نشان می‌دهد که مدل مقادیر پارامتر ورودی لازم برای فراخوانی تابع (و API خارجی زیربنایی آن) را ارائه کرده است.

در این مثال، درخواست ورودی شامل عبارت « What was the weather in Boston on October 17, 2024? بود. از این عبارت، مدل پارامترهای ورودی مورد نیاز تابع fetchWeather (یعنی city ، state و date ) را استنباط کرد.

سویفت

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}',
  );
}

وحدت

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.
}

مرحله ۵ : خروجی تابع را برای تولید پاسخ نهایی به مدل ارائه دهید.

بعد از اینکه تابع fetchWeather اطلاعات آب و هوا را برمی‌گرداند، برنامه شما باید آن را به مدل ارسال کند.

سپس، مدل پردازش نهایی خود را انجام می‌دهد و یک پاسخ نهایی به زبان طبیعی مانند زیر تولید می‌کند: On October 17, 2024 in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.

سویفت

// 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));

وحدت

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

رفتارها و گزینه‌های اضافی

در اینجا چند رفتار اضافی برای فراخوانی تابع که باید در کد خود جای دهید و گزینه‌هایی که می‌توانید کنترل کنید، آورده شده است.

ممکن است مدل درخواست کند که یک تابع یا تابع دیگری را دوباره فراخوانی کند.

اگر پاسخ حاصل از یک فراخوانی تابع برای مدل جهت تولید پاسخ نهایی کافی نباشد، آنگاه مدل ممکن است درخواست فراخوانی تابع دیگری یا فراخوانی یک تابع کاملاً متفاوت را داشته باشد. مورد دوم تنها در صورتی می‌تواند اتفاق بیفتد که شما بیش از یک تابع را در لیست اعلان تابع خود به مدل ارائه دهید.

برنامه شما باید این امکان را فراهم کند که مدل ممکن است فراخوانی‌های تابع اضافی را درخواست کند.

ممکن است مدل درخواست فراخوانی چندین تابع را به طور همزمان داشته باشد.

شما می‌توانید تا ۱۲۸ تابع را در لیست اعلان تابع خود به مدل ارائه دهید. با توجه به این، مدل ممکن است تصمیم بگیرد که برای تولید پاسخ نهایی خود به چندین تابع نیاز دارد. و ممکن است تصمیم بگیرد که برخی از این توابع را همزمان فراخوانی کند - به این عمل فراخوانی تابع موازی می‌گویند.

برنامه شما باید این را در نظر بگیرد که مدل ممکن است چندین تابع را به طور همزمان اجرا کند و برنامه شما باید تمام پاسخ‌ها را از توابع به مدل ارائه دهد.

شما می‌توانید کنترل کنید که مدل چگونه و آیا می‌تواند توابع را فراخوانی کند یا خیر.

شما می‌توانید محدودیت‌هایی در مورد نحوه و امکان استفاده مدل از اعلان‌های تابع ارائه شده اعمال کنید. به این کار تنظیم حالت فراخوانی تابع گفته می‌شود. در اینجا چند مثال آورده شده است:

  • به جای اینکه به مدل اجازه دهید بین پاسخ فوری به زبان طبیعی و فراخوانی تابع یکی را انتخاب کند، می‌توانید آن را مجبور کنید که همیشه از فراخوانی‌های تابع استفاده کند. به این کار فراخوانی اجباری تابع می‌گویند.

  • اگر چندین تابع تعریف کنید، می‌توانید مدل را به استفاده از تنها زیرمجموعه‌ای از توابع ارائه شده محدود کنید.

شما این محدودیت‌ها (یا حالت‌ها) را با اضافه کردن پیکربندی ابزار ( toolConfig ) به همراه اعلان اعلان و تعریف تابع پیاده‌سازی می‌کنید. در پیکربندی ابزار، می‌توانید یکی از حالت‌های زیر را مشخص کنید. مفیدترین حالت ANY است.

حالت توضیحات
AUTO رفتار پیش‌فرض مدل. مدل تصمیم می‌گیرد که آیا از فراخوانی تابع یا پاسخ زبان طبیعی استفاده کند.
ANY مدل باید از فراخوانی‌های تابع ("فراخوانی اجباری تابع") استفاده کند. برای محدود کردن مدل به زیرمجموعه‌ای از توابع، نام‌های تابع مجاز را در allowedFunctionNames مشخص کنید.
NONE مدل نباید از فراخوانی تابع استفاده کند. این رفتار معادل درخواست مدل بدون هیچگونه اعلان تابع مرتبط است.



چه کار دیگری می‌توانید انجام دهید؟

قابلیت‌های دیگر را امتحان کنید

آموزش کنترل تولید محتوا

شما همچنین می‌توانید با استفاده از دستورات و پیکربندی‌های مدل، آزمایش کنید و حتی یک قطعه کد تولید شده با استفاده از Google AI Studio دریافت کنید.

درباره مدل‌های پشتیبانی‌شده بیشتر بدانید

درباره مدل‌های موجود برای موارد استفاده مختلف و سهمیه‌ها و قیمت‌گذاری آنها اطلاعات کسب کنید.


درباره تجربه خود با Firebase AI Logic بازخورد دهید