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 ডকুমেন্টেশন দেখুন।

ফাংশন কলিং প্রয়োগ করা

এই নির্দেশিকার নিম্নলিখিত ধাপগুলি থেকে আপনি জানতে পারবেন যে কীভাবে ফাংশন কলিংয়ের উদাহরণের ওভারভিউ তে (এই পৃষ্ঠার উপরের বিভাগ দেখুন) বর্ণিত ওয়ার্কফ্লোর মতো ফাংশন কল সেট-আপ করতে হয়।

মানানসই মডেল

  • gemini-3.1-pro-preview
  • gemini-3.8-flash (এবং এর আগের gemini-3.7-flash, gemini-3.6-flash ও gemini-3.5-flash)
  • gemini-3.5-flash-lite (এবং পুরনো gemini-3.1-flash-lite)

সাধারণ-ব্যবহারের Gemini 2.5 মডেলগুলিতে এই কেপেবিলিটি কাজ করে, তবে সেগুলি সবকটিই বাতিল করা হয়েছে।

এছাড়াও, এই ক্ষমতা Gemini Live API মডেল -এও কাজ করে, তবে এই নির্দেশিকায় দেওয়া সব কোড স্যাম্পেল সাধারণ-ব্যবহারের Gemini মডেলের জন্য।

শুরু করার আগে

এই পৃষ্ঠায় প্রদানকারী-নির্দিষ্ট কন্টেন্ট ও কোড দেখতে আপনার Gemini API প্রদানকারীর আইকনে ক্লিক করুন।

আপনি এখনও না করে থাকলে, শুরু করার নির্দেশিকা সম্পূর্ণ করুন, যা বর্ণনা করে যে কীভাবে আপনার Firebase প্রোজেক্ট সেট-আপ করতে হয়, Firebase-এর সাথে আপনার অ্যাপ কানেক্ট করতে হয়, SDK যোগ করতে হয়, আপনার বেছে নেওয়া Gemini API প্রদানকারীর জন্য ব্যাকএন্ড পরিষেবা চালু করতে হয় এবং GenerativeModel ইনস্ট্যান্স তৈরি করতে হয়।

আপনার প্রম্পট পরীক্ষা ও ইটারেট করার জন্য, আমরা Google AI Studio ব্যবহার করার সাজেশন দিই।

ধাপ ১: ফাংশনটি লেখা

ধরে নিন, আপনার এমন একটি অ্যাপ আছে যেখানে ব্যবহারকারী এই ধরনের প্রম্পট লিখতে পারেন: What was the weather in Boston on October 17, 2024?. Gemini মডেলগুলি হয়ত এই আবহাওয়ার তথ্য জানে না; তবে, ধরে নিন যে আপনি এমন একটি এক্সটার্নাল আবহাওয়ার পরিষেবা API জানেন যা এটি প্রদান করতে পারে। এই গাইডে বর্ণিত পরিস্থিতি এই কাল্পনিক এক্সটার্নাল API-এর উপর নির্ভর করে।

আপনার অ্যাপে এমন ফাংশন লিখুন যা কাল্পনিক এক্সটার্নাল API-এর সাথে ইন্টার‍্যাক্ট করবে এবং মডেলকে সেই তথ্য প্রদান করবে যা তার চূড়ান্ত অনুরোধ জেনারেট করার জন্য প্রয়োজন। এই আবহাওয়ার উদাহরণে, এটি একটি fetchWeather ফাংশন হবে যা এই কাল্পনিক এক্সটার্নাল API-তে কল করে।

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

ধাপ ২: ফাংশন ঘোষণা তৈরি করুন

ফাংশন ডিক্লারেশন তৈরি করুন যা আপনি পরে মডেলকে প্রদান করবেন (এই নির্দেশিকার পরবর্তী ধাপ)।

আপনার ঘোষণায়, ফাংশন ও এর প্যারামিটার সম্পর্কে যতটা সম্ভব বিস্তারিত বিবরণ দিন।

কোন ফাংশন বেছে নিতে হবে এবং ফাংশনে প্রকৃত কল করার জন্য কীভাবে প্যারামিটার ভ্যালু দিতে হবে তা নির্ধারণ করতে মডেলটি ফাংশন ঘোষণার তথ্য ব্যবহার করে। ফাংশনগুলির মধ্যে থেকে মডেল কীভাবে বেছে নিতে পারে এবং আপনি কীভাবে সেই পছন্দ নিয়ন্ত্রণ করতে পারেন তা জানতে অতিরিক্ত আচরণ ও বিকল্প দেখুন।

আপনার দেওয়া স্কিমা সম্পর্কে নিম্নলিখিত বিষয়গুলি মনে রাখবেন:

  • আপনাকে অবশ্যই এমন স্কিমা ফর্ম্যাটে ফাংশন ঘোষণা প্রদান করতে হবে যা OpenAPI স্কিমার সাথে মানানসই। Agent Platform OpenAPI স্কিমার সীমিত সহায়তা প্রদান করে।

    • নিম্নলিখিত অ্যাট্রিবিউট কাজ করে: type, nullable, required, format, description, properties, items, enum.

    • নিম্নলিখিত অ্যাট্রিবিউট কাজ করে না: default, optional, maximum, oneOf.

  • ডিফল্ট হিসেবে, Firebase AI Logic SDK-এর ক্ষেত্রে, সব ফিল্ডকে প্রয়োজনীয় হিসেবে বিবেচনা করা হয়, যদি না আপনি optionalProperties অ্যারেতে সেগুলিকে ঐচ্ছিক হিসেবে উল্লেখ করেন। এইসব ঐচ্ছিক ফিল্ডের জন্য, মডেল ফিল্ড পূরণ করতে বা সেগুলি এড়িয়ে যেতে পারে। মনে রাখবেন, আপনি যদি সরাসরি দুটি Gemini API পরিষেবা প্রদানকারীর সার্ভার SDK বা API ব্যবহার করেন, তাহলে এটি তাদের ডিফল্ট আচরণের বিপরীত।

নাম ও বিবরণ সহ ফাংশন ঘোষণা সংক্রান্ত পেশাদার পদ্ধতি সম্পর্কে পরামর্শ পেতে পেশাদার পদ্ধতি 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."
    )}
  }
));

ধাপ ৩: মডেল ইনিশিয়ালাইজ করার সময় ফাংশন ঘোষণা করুন

অনুরোধের সাথে আপনি সর্বাধিক ১২৮টি ফাংশন ঘোষণা প্রদান করতে পারবেন। ফাংশনগুলির মধ্যে থেকে মডেল কীভাবে বেছে নিতে পারে এবং আপনি কীভাবে সেই পছন্দ নিয়ন্ত্রণ করতে পারেন (toolConfig ব্যবহার করে ফাংশন কলিং মোড সেট করা) তা জানতে এই পৃষ্ঠায় পরে দেওয়া অতিরিক্ত আচরণ ও বিকল্প দেখুন।

Swift


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_MODEL_NAME",
  // 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 = "<var>GEMINI_MODEL_NAME</var>",
    // 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("<var>GEMINI_MODEL_NAME</var>",
                        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_MODEL_NAME",
  // 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_MODEL_NAME',
       // 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_MODEL_NAME",
  // 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) জন্য প্রয়োজনীয় ইনপুট প্যারামিটার মডেলটি অনুমান করেছে।

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

ধাপ ৫: চূড়ান্ত উত্তর জেনারেট করতে মডেলকে ফাংশনের আউটপুট প্রদান করুন

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: "user", 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("user") {
    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("user",
  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.");

অতিরিক্ত আচরণ ও বিকল্প

ফাংশন কলিংয়ের কিছু অতিরিক্ত আচরণ এখানে দেওয়া হল যা আপনাকে নিজের কোডে অ্যাডজাস্ট করতে হবে এবং আপনি কন্ট্রোল করতে পারবেন এমন বিকল্প।

মডেলটি কোনও ফাংশন বা অন্য কোনও ফাংশন আবার কল করতে বলতে পারে।

কোনও ফাংশন কলের উত্তর যদি মডেলের চূড়ান্ত উত্তর জেনারেট করার জন্য যথেষ্ট না হয়, তাহলে মডেল অতিরিক্ত ফাংশন কলের অনুরোধ করতে পারে অথবা সম্পূর্ণ আলাদা ফাংশন কলের অনুরোধ করতে পারে। এটি তখনই সম্ভব যখন আপনার ফাংশন ডিক্লারেশন তালিকায় মডেলকে একাধিক ফাংশন প্রদান করেন।

আপনার অ্যাপকে এটিও মাথায় রাখতে হবে যে মডেলটি অতিরিক্ত ফাংশন কল করার জন্য অনুরোধ করতে পারে।

মডেলটি একই সাথে একাধিক ফাংশন কল করতে বলতে পারে।

আপনি মডেলকে ফাংশন ঘোষণা করার তালিকায় সর্বাধিক ১২৮টি ফাংশন প্রদান করতে পারবেন। এটি বিবেচনা করে, মডেলটি সিদ্ধান্ত নিতে পারে যে চূড়ান্ত উত্তর জেনারেট করার জন্য একাধিক ফাংশনের প্রয়োজন হবে। এটি একই সাথে এই ফাংশনগুলির মধ্যে কিছু কল করার সিদ্ধান্ত নিতে পারে – এটিকে প্যারালাল ফাংশন কলিং বলা হয়।

আপনার অ্যাপকে এটি মানিয়ে নিতে হবে যে মডেলটি একই সাথে একাধিক ফাংশন চালানোর জন্য অনুরোধ করতে পারে এবং আপনার অ্যাপকে ফাংশন থেকে পাওয়া সব উত্তর মডেলকে ফেরত দিতে হবে।

মডেল কীভাবে এবং কল ফাংশন করার জন্য অনুরোধ করতে পারবে কিনা তা আপনি কন্ট্রোল করতে পারবেন।

প্রদত্ত ফাংশন ঘোষণাগুলি কীভাবে এবং মডেলটি ব্যবহার করবে কিনা সেই বিষয়ে আপনি কিছু বিধিনিষেধ আরোপ করতে পারেন। এটি হল ফাংশন কলিং মোড সেট করা। কয়েকটি উদাহরণ দেখুন:

  • মডেলকে তাৎক্ষণিক স্বাভাবিক ভাষায় উত্তর ও ফাংশন কলের মধ্যে থেকে বেছে নেওয়ার অনুমতি দেওয়ার পরিবর্তে, আপনি এটিকে সবসময় ফাংশন কল ব্যবহার করতে বাধ্য করতে পারেন। এটি বাধ্যতামূলক ফাংশন কলিং নামে পরিচিত।

  • আপনি একাধিক ফাংশন ঘোষণা করলে, মডেলকে আপনার দেওয়া ফাংশনের সাবসেট ব্যবহার করার মধ্যে সীমাবদ্ধ রাখতে পারবেন।

আপনি প্রম্পট ও ফাংশন ঘোষণার সাথে টুল কনফিগারেশন (toolConfig) যোগ করে এইসব বিধিনিষেধ (বা মোড) প্রয়োগ করেন। টুল কনফিগারেশনে, আপনি নিম্নলিখিত মোডগুলির মধ্যে একটি নির্দিষ্ট করতে পারবেন। সবচেয়ে বেশি উপযোগী মোড হল ANY।

মোড বিবরণ
AUTO মডেলের ডিফল্ট আচরণ। মডেলটি সিদ্ধান্ত নেয় যে কোনও ফাংশন কল ব্যবহার করবে নাকি স্বাভাবিক ভাষায় উত্তর দেবে।
ANY মডেলকে অবশ্যই ফাংশন কল ব্যবহার করতে হবে ("বাধ্যতামূলক ফাংশন কলিং")। ফাংশনের সাবসেটে মডেলকে সীমাবদ্ধ করতে, allowedFunctionNames-এ অনুমোদিত ফাংশনের নাম উল্লেখ করুন।
NONE মডেলটি যেন ফাংশন কল ব্যবহার না করে। এই আচরণটি কোনও সংশ্লিষ্ট ফাংশন ঘোষণা ছাড়াই মডেল অনুরোধের সমতুল্য।



আপনি আর কী করতে পারেন?

অন্যান্য সুবিধা ব্যবহার করে দেখুন

কন্টেন্ট জেনারেশন কীভাবে নিয়ন্ত্রণ করতে হয় তা জানুন

এছাড়াও, আপনি প্রম্পট ও মডেল কনফিগারেশন নিয়ে এক্সপেরিমেন্ট করতে পারেন এবং এমনকি Google AI Studio ব্যবহার করে জেনারেট করা কোড স্নিপেট পেতে পারেন।

কাজ করে এমন মডেল সম্পর্কে আরও জানুন

বিভিন্ন ব্যবহারের ক্ষেত্রে উপলভ্য মডেল এবং সেগুলির কোটা ও দাম সম্পর্কে জানুন।


Firebase AI Logic-এর সাথে আপনার অভিজ্ঞতা সম্পর্কে মতামত জানান


অন্য কিছু উল্লেখ না করা থাকলে, এই পৃষ্ঠার কন্টেন্ট Creative Commons Attribution 4.0 License-এর অধীনে এবং কোডের নমুনাগুলি Apache 2.0 License-এর অধীনে লাইসেন্স প্রাপ্ত। আরও জানতে, Google Developers সাইট নীতি দেখুন। Java হল Oracle এবং/অথবা তার অ্যাফিলিয়েট সংস্থার রেজিস্টার্ড ট্রেডমার্ক।

2026-10-09 UTC-তে শেষবার আপডেট করা হয়েছে।