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

مدل های مولد در حل بسیاری از مشکلات قدرتمند هستند. با این حال، آنها با محدودیت هایی مانند:

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

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


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

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

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

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

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

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

پرش به اجرای کد

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

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

تصور کنید برنامه ای دارید که در آن کاربر می تواند پیامی مانند: What was the weather in Boston on October 17, 2024? .

مدل های Gemini ممکن است این اطلاعات آب و هوا را ندانند. با این حال، تصور کنید که یک API خدمات هواشناسی خارجی را می شناسید که می تواند آن را ارائه دهد. می‌توانید از فراخوانی تابع برای دادن مسیری به مدل Gemini برای آن API و اطلاعات آب و هوای آن استفاده کنید.

ابتدا، یک تابع fetchWeather در برنامه خود می نویسید که با این API فرضی خارجی، که دارای ورودی و خروجی است، تعامل دارد:

پارامتر تایپ کنید مورد نیاز توضیحات
ورودی
location شیء بله نام شهر و ایالت آن که آب و هوا را برای آن بدست آورید.
فقط شهرهای ایالات متحده پشتیبانی می شوند. همیشه باید یک شی تودرتو از city و state باشد.
date رشته بله تاریخ واکشی آب و هوا (همیشه باید در قالب YYYY-MM-DD باشد).
خروجی
temperature عدد صحیح بله دما (بر حسب فارنهایت)
chancePrecipitation رشته بله احتمال بارندگی (به صورت درصد بیان می شود)
cloudConditions رشته بله شرایط ابری (یکی از clear ، partlyCloudy ، mostlyCloudy ، cloudy )

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

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

مرحله 1 : تابع را بنویسید

تصور کنید برنامه ای دارید که در آن کاربر می تواند پیامی مانند: 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"},
  };
}

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

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

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

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

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

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

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

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

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

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

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

سویفت

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

مرحله 3 : اعلان تابع را در طول اولیه سازی مدل ارائه دهید

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

سویفت


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]),
       ],
     );

وحدت


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 را استنباط کرد (یعنی 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) {
  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}',
  );
}

وحدت

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.

سویفت

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

یاد بگیرید چگونه تولید محتوا را کنترل کنید

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

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

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


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