Gemini API এর সাথে ফাংশন কলিং, Gemini API এর সাথে ফাংশন কলিং

ফাংশন কলিং আপনাকে মডেলগুলিকে বহিরাগত সরঞ্জাম এবং API-এর সাথে সংযুক্ত করতে দেয়। টেক্সট প্রতিক্রিয়া তৈরি করার পরিবর্তে, মডেলটি নির্দিষ্ট ফাংশনগুলিকে কখন কল করতে হবে তা নির্ধারণ করে এবং বাস্তব-বিশ্বের ক্রিয়াগুলি সম্পাদন করার জন্য প্রয়োজনীয় পরামিতি সরবরাহ করে। এটি মডেলটিকে প্রাকৃতিক ভাষা এবং বাস্তব-বিশ্বের ক্রিয়া এবং ডেটার মধ্যে একটি সেতু হিসাবে কাজ করতে দেয়। ফাংশন কলিংয়ের 3টি প্রাথমিক ব্যবহারের ক্ষেত্রে রয়েছে:

  • জ্ঞান বৃদ্ধি: ডাটাবেস, এপিআই এবং জ্ঞান ভিত্তির মতো বহিরাগত উৎস থেকে তথ্য অ্যাক্সেস করুন।
  • ক্ষমতা বৃদ্ধি করুন: গণনা সম্পাদন করতে এবং মডেলের সীমাবদ্ধতা বাড়াতে বাহ্যিক সরঞ্জাম ব্যবহার করুন, যেমন ক্যালকুলেটর ব্যবহার করা বা চার্ট তৈরি করা।
  • পদক্ষেপ নিন: API ব্যবহার করে বহিরাগত সিস্টেমের সাথে ইন্টারঅ্যাক্ট করুন, যেমন অ্যাপয়েন্টমেন্টের সময় নির্ধারণ করা, ইনভয়েস তৈরি করা, ইমেল পাঠানো, অথবা স্মার্ট হোম ডিভাইস নিয়ন্ত্রণ করা।

তৈরি করুন,

পাইথন

from google import genai
from google.genai import types

# Define the function declaration for the model
schedule_meeting_function = {
    "name": "schedule_meeting",
    "description": "Schedules a meeting with specified attendees at a given time and date.",
    "parameters": {
        "type": "object",
        "properties": {
            "attendees": {
                "type": "array",
                "items": {"type": "string"},
                "description": "List of people attending the meeting.",
            },
            "date": {
                "type": "string",
                "description": "Date of the meeting (e.g., '2024-07-29')",
            },
            "time": {
                "type": "string",
                "description": "Time of the meeting (e.g., '15:00')",
            },
            "topic": {
                "type": "string",
                "description": "The subject or topic of the meeting.",
            },
        },
        "required": ["attendees", "date", "time", "topic"],
    },
}

# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[schedule_meeting_function])
config = types.GenerateContentConfig(tools=[tools])

# Send request with function declarations
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about the Q3 planning.",
    config=config,
)

# Check for a function call
if response.candidates[0].content.parts[0].function_call:
    function_call = response.candidates[0].content.parts[0].function_call
    print(f"Function to call: {function_call.name}")
    print(f"Arguments: {function_call.args}")
    #  In a real app, you would call your function here:
    #  result = schedule_meeting(**function_call.args)
else:
    print("No function call found in the response.")
    print(response.text)

জাভাস্ক্রিপ্ট

import { GoogleGenAI, Type } from '@google/genai';

// Configure the client
const ai = new GoogleGenAI({});

// Define the function declaration for the model
const scheduleMeetingFunctionDeclaration = {
  name: 'schedule_meeting',
  description: 'Schedules a meeting with specified attendees at a given time and date.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      attendees: {
        type: Type.ARRAY,
        items: { type: Type.STRING },
        description: 'List of people attending the meeting.',
      },
      date: {
        type: Type.STRING,
        description: 'Date of the meeting (e.g., "2024-07-29")',
      },
      time: {
        type: Type.STRING,
        description: 'Time of the meeting (e.g., "15:00")',
      },
      topic: {
        type: Type.STRING,
        description: 'The subject or topic of the meeting.',
      },
    },
    required: ['attendees', 'date', 'time', 'topic'],
  },
};

// Send request with function declarations
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.',
  config: {
    tools: [{
      functionDeclarations: [scheduleMeetingFunctionDeclaration]
    }],
  },
});

// Check for function calls in the response
if (response.functionCalls && response.functionCalls.length > 0) {
  const functionCall = response.functionCalls[0]; // Assuming one function call
  console.log(`Function to call: ${functionCall.name}`);
  console.log(`Arguments: ${JSON.stringify(functionCall.args)}`);
  // In a real app, you would call your actual function here:
  // const result = await scheduleMeeting(functionCall.args);
} else {
  console.log("No function call found in the response.");
  console.log(response.text);
}

বিশ্রাম

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning."
          }
        ]
      }
    ],
    "tools": [
      {
        "functionDeclarations": [
          {
            "name": "schedule_meeting",
            "description": "Schedules a meeting with specified attendees at a given time and date.",
            "parameters": {
              "type": "object",
              "properties": {
                "attendees": {
                  "type": "array",
                  "items": {"type": "string"},
                  "description": "List of people attending the meeting."
                },
                "date": {
                  "type": "string",
                  "description": "Date of the meeting (e.g., '2024-07-29')"
                },
                "time": {
                  "type": "string",
                  "description": "Time of the meeting (e.g., '15:00')"
                },
                "topic": {
                  "type": "string",
                  "description": "The subject or topic of the meeting."
                }
              },
              "required": ["attendees", "date", "time", "topic"]
            }
          }
        ]
      }
    ]
  }'

ফাংশন কলিং কীভাবে কাজ করে

ফাংশন কলিং ওভারভিউ

ফাংশন কলিং আপনার অ্যাপ্লিকেশন, মডেল এবং বহিরাগত ফাংশনের মধ্যে একটি কাঠামোগত মিথস্ক্রিয়া জড়িত। এখানে প্রক্রিয়াটির একটি বিশদ বিবরণ দেওয়া হল:

  1. ফাংশন ডিক্লারেশন সংজ্ঞায়িত করুন: আপনার অ্যাপ্লিকেশন কোডে ফাংশন ডিক্লারেশন সংজ্ঞায়িত করুন। ফাংশন ডিক্লারেশনগুলি মডেলের ফাংশনের নাম, প্যারামিটার এবং উদ্দেশ্য বর্ণনা করে।
  2. ফাংশন ঘোষণা সহ LLM কল করুন: মডেলটিতে ফাংশন ঘোষণা(গুলি) সহ ব্যবহারকারীর প্রম্পট পাঠান। এটি অনুরোধ বিশ্লেষণ করে এবং নির্ধারণ করে যে একটি ফাংশন কল সহায়ক হবে কিনা। যদি তাই হয়, তবে এটি একটি কাঠামোগত JSON অবজেক্টের সাথে সাড়া দেয়।
  3. ফাংশন কোড কার্যকর করুন (আপনার দায়িত্ব): মডেল নিজেই ফাংশনটি কার্যকর করে না । প্রতিক্রিয়া প্রক্রিয়া করা এবং ফাংশন কল পরীক্ষা করা আপনার অ্যাপ্লিকেশনের দায়িত্ব, যদি
    • হ্যাঁ : ফাংশনের নাম এবং আর্গুমেন্টগুলি বের করুন এবং আপনার অ্যাপ্লিকেশনে সংশ্লিষ্ট ফাংশনটি কার্যকর করুন।
    • না: মডেলটি প্রম্পটে সরাসরি টেক্সট প্রতিক্রিয়া প্রদান করেছে (উদাহরণে এই প্রবাহের উপর কম জোর দেওয়া হয়েছে তবে এটি একটি সম্ভাব্য ফলাফল)।
  4. ব্যবহারকারী-বান্ধব প্রতিক্রিয়া তৈরি করুন: যদি কোনও ফাংশন কার্যকর করা হয়, তাহলে ফলাফলটি ক্যাপচার করুন এবং কথোপকথনের পরবর্তী ধাপে এটি মডেলের কাছে ফেরত পাঠান। এটি ফলাফলটি ব্যবহার করে একটি চূড়ান্ত, ব্যবহারকারী-বান্ধব প্রতিক্রিয়া তৈরি করবে যা ফাংশন কল থেকে তথ্য অন্তর্ভুক্ত করবে।

এই প্রক্রিয়াটি একাধিক পালায় পুনরাবৃত্তি করা যেতে পারে, যা জটিল মিথস্ক্রিয়া এবং কর্মপ্রবাহের সুযোগ করে দেয়। মডেলটি একক পালায় ( সমান্তরাল ফাংশন কলিং ) এবং ক্রমানুসারে ( কম্পোজিশনাল ফাংশন কলিং ) একাধিক ফাংশন কলিং সমর্থন করে।

ধাপ ১: একটি ফাংশন ঘোষণা সংজ্ঞায়িত করুন

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

পাইথন

# Define a function that the model can call to control smart lights
set_light_values_declaration = {
    "name": "set_light_values",
    "description": "Sets the brightness and color temperature of a light.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "integer",
                "description": "Light level from 0 to 100. Zero is off and 100 is full brightness",
            },
            "color_temp": {
                "type": "string",
                "enum": ["daylight", "cool", "warm"],
                "description": "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
            },
        },
        "required": ["brightness", "color_temp"],
    },
}

# This is the actual function that would be called based on the model's suggestion
def set_light_values(brightness: int, color_temp: str) -> dict[str, int | str]:
    """Set the brightness and color temperature of a room light. (mock API).

    Args:
        brightness: Light level from 0 to 100. Zero is off and 100 is full brightness
        color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.

    Returns:
        A dictionary containing the set brightness and color temperature.
    """
    return {"brightness": brightness, "colorTemperature": color_temp}

জাভাস্ক্রিপ্ট

import { Type } from '@google/genai';

// Define a function that the model can call to control smart lights
const setLightValuesFunctionDeclaration = {
  name: 'set_light_values',
  description: 'Sets the brightness and color temperature of a light.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      brightness: {
        type: Type.NUMBER,
        description: 'Light level from 0 to 100. Zero is off and 100 is full brightness',
      },
      color_temp: {
        type: Type.STRING,
        enum: ['daylight', 'cool', 'warm'],
        description: 'Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.',
      },
    },
    required: ['brightness', 'color_temp'],
  },
};

/**

*   Set the brightness and color temperature of a room light. (mock API)
*   @param {number} brightness - Light level from 0 to 100. Zero is off and 100 is full brightness
*   @param {string} color_temp - Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
*   @return {Object} A dictionary containing the set brightness and color temperature.
*/
function setLightValues(brightness, color_temp) {
  return {
    brightness: brightness,
    colorTemperature: color_temp
  };
}

ধাপ ২: ফাংশন ঘোষণা সহ মডেলটিকে কল করুন

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

পাইথন

from google.genai import types

# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])

# Define user prompt
contents = [
    types.Content(
        role="user", parts=[types.Part(text="Turn the lights down to a romantic level")]
    )
]

# Send request with function declarations
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=contents
    config=config,
)

print(response.candidates[0].content.parts[0].function_call)

জাভাস্ক্রিপ্ট

import { GoogleGenAI } from '@google/genai';

// Generation config with function declaration
const config = {
  tools: [{
    functionDeclarations: [setLightValuesFunctionDeclaration]
  }]
};

// Configure the client
const ai = new GoogleGenAI({});

// Define user prompt
const contents = [
  {
    role: 'user',
    parts: [{ text: 'Turn the lights down to a romantic level' }]
  }
];

// Send request with function declarations
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: contents,
  config: config
});

console.log(response.functionCalls[0]);

এরপর মডেলটি একটি OpenAPI সামঞ্জস্যপূর্ণ স্কিমায় একটি functionCall অবজেক্ট ফেরত দেয় যা ব্যবহারকারীর প্রশ্নের উত্তর দেওয়ার জন্য ঘোষিত এক বা একাধিক ফাংশনকে কীভাবে কল করতে হবে তা নির্দিষ্ট করে।

পাইথন

id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'

জাভাস্ক্রিপ্ট

{
  name: 'set_light_values',
  args: { brightness: 25, color_temp: 'warm' }
}

ধাপ ৩: set_light_values ​​ফাংশন কোড কার্যকর করুন

মডেলের রেসপন্স থেকে ফাংশন কল ডিটেইলস বের করুন, আর্গুমেন্টগুলো পার্স করুন এবং set_light_values ​​ফাংশনটি এক্সিকিউট করুন।

পাইথন

# Extract tool call details, it may not be in the first part.
tool_call = response.candidates[0].content.parts[0].function_call

if tool_call.name == "set_light_values":
    result = set_light_values(**tool_call.args)
    print(f"Function execution result: {result}")

জাভাস্ক্রিপ্ট

// Extract tool call details
const tool_call = response.functionCalls[0]

let result;
if (tool_call.name === 'set_light_values') {
  result = setLightValues(tool_call.args.brightness, tool_call.args.color_temp);
  console.log(`Function execution result: ${JSON.stringify(result)}`);
}

ধাপ ৪: ফাংশন ফলাফল সহ ব্যবহারকারী-বান্ধব প্রতিক্রিয়া তৈরি করুন এবং মডেলটিকে আবার কল করুন

অবশেষে, ফাংশন এক্সিকিউশনের ফলাফল মডেলের কাছে ফেরত পাঠান যাতে এটি ব্যবহারকারীর কাছে তার চূড়ান্ত প্রতিক্রিয়ায় এই তথ্য অন্তর্ভুক্ত করতে পারে।

পাইথন

from google import genai
from google.genai import types

# Create a function response part
function_response_part = types.Part.from_function_response(
    name=tool_call.name,
    response={"result": result},
)

# Append function call and result of the function execution to contents
contents.append(response.candidates[0].content) # Append the content from the model's response.
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response

client = genai.Client()
final_response = client.models.generate_content(
    model="gemini-2.5-flash",
    config=config,
    contents=contents,
)

print(final_response.text)

জাভাস্ক্রিপ্ট

// Create a function response part
const function_response_part = {
  name: tool_call.name,
  response: { result }
}

// Append function call and result of the function execution to contents
contents.push(response.candidates[0].content);
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });

// Get the final response from the model
const final_response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: contents,
  config: config
});

console.log(final_response.text);

এটি ফাংশন কলিং ফ্লো সম্পূর্ণ করে। মডেলটি ব্যবহারকারীর অনুরোধ ক্রিয়া সম্পাদনের জন্য set_light_values ​​ফাংশনটি সফলভাবে ব্যবহার করেছে।

ফাংশন ঘোষণা

যখন আপনি একটি প্রম্পটে ফাংশন কলিং বাস্তবায়ন করেন, তখন আপনি একটি tools অবজেক্ট তৈরি করেন, যার মধ্যে এক বা একাধিক function declarations থাকে। আপনি JSON ব্যবহার করে ফাংশন সংজ্ঞায়িত করেন, বিশেষ করে OpenAPI স্কিমা ফর্ম্যাটের একটি নির্বাচিত উপসেট দিয়ে। একটি একক ফাংশন ঘোষণায় নিম্নলিখিত পরামিতিগুলি অন্তর্ভুক্ত থাকতে পারে:

  • name (স্ট্রিং): ফাংশনের জন্য একটি অনন্য নাম ( get_weather_forecast , send_email )। স্পেস বা বিশেষ অক্ষর ছাড়াই বর্ণনামূলক নাম ব্যবহার করুন (আন্ডারস্কোর বা camelCase ব্যবহার করুন)।
  • description (স্ট্রিং): ফাংশনের উদ্দেশ্য এবং ক্ষমতা সম্পর্কে একটি স্পষ্ট এবং বিস্তারিত ব্যাখ্যা। ফাংশনটি কখন ব্যবহার করতে হবে তা মডেলের বুঝতে এটি অত্যন্ত গুরুত্বপূর্ণ। সুনির্দিষ্টভাবে বলুন এবং সহায়ক হলে উদাহরণ প্রদান করুন ("অবস্থানের উপর ভিত্তি করে থিয়েটার খুঁজে বের করে এবং ঐচ্ছিকভাবে সিনেমার শিরোনাম যা বর্তমানে থিয়েটারে চলছে।")।
  • parameters (অবজেক্ট): ফাংশনটি যে ইনপুট প্যারামিটারগুলি প্রত্যাশিত তা সংজ্ঞায়িত করে।
    • type (স্ট্রিং): সামগ্রিক ডেটা টাইপ নির্দিষ্ট করে, যেমন object
    • properties (বস্তু): পৃথক পরামিতি তালিকাভুক্ত করে, প্রতিটি সহ:
      • type (স্ট্রিং): প্যারামিটারের ডেটা টাইপ, যেমন string , integer , boolean, array
      • description (স্ট্রিং): প্যারামিটারের উদ্দেশ্য এবং বিন্যাসের বর্ণনা। উদাহরণ এবং সীমাবদ্ধতা প্রদান করুন ("শহর এবং রাজ্য, যেমন, 'সান ফ্রান্সিসকো, সিএ' অথবা একটি জিপ কোড যেমন, '95616'।")।
      • enum (অ্যারে, ঐচ্ছিক): যদি প্যারামিটারের মানগুলি একটি নির্দিষ্ট সেট থেকে হয়, তাহলে কেবল বর্ণনায় বর্ণনা করার পরিবর্তে অনুমোদিত মানগুলি তালিকাভুক্ত করতে "enum" ব্যবহার করুন। এটি নির্ভুলতা উন্নত করে ("enum": ["দিনের আলো", "ঠান্ডা", "উষ্ণ"])।
    • required (অ্যারে): ফাংশনটি পরিচালনার জন্য বাধ্যতামূলক প্যারামিটারের নাম তালিকাভুক্ত স্ট্রিংগুলির একটি অ্যারে।

আপনি types.FunctionDeclaration.from_callable(client=client, callable=your_function) ব্যবহার করে সরাসরি Python ফাংশন থেকে FunctionDeclarations তৈরি করতে পারেন।

চিন্তাভাবনার সাথে ফাংশন কলিং

" thinking " সক্ষম করলে ফাংশন কলের কার্যকারিতা উন্নত হতে পারে, ফাংশন কলের পরামর্শ দেওয়ার আগে মডেলটিকে একটি অনুরোধের মাধ্যমে যুক্তি করার অনুমতি দেওয়া হয়। জেমিনি API স্টেটলেস, একাধিক-পালা কথোপকথনের মধ্যে মডেলের যুক্তির প্রসঙ্গ হারিয়ে যাবে। এই প্রসঙ্গটি সংরক্ষণ করার জন্য, আপনি চিন্তার স্বাক্ষর ব্যবহার করতে পারেন। একটি চিন্তার স্বাক্ষর হল মডেলের অভ্যন্তরীণ চিন্তা প্রক্রিয়ার একটি এনক্রিপ্ট করা উপস্থাপনা যা আপনি পরবর্তী বাঁকগুলিতে মডেলের কাছে ফেরত পাঠান।

মাল্টি-টার্ন টুল ব্যবহারের জন্য স্ট্যান্ডার্ড প্যাটার্ন হল কথোপকথনের ইতিহাসে মডেলের সম্পূর্ণ পূর্ববর্তী প্রতিক্রিয়া যুক্ত করা। content অবজেক্টে স্বয়ংক্রিয়ভাবে thought_signatures অন্তর্ভুক্ত থাকে। আপনি যদি এই প্যাটার্নটি অনুসরণ করেন তবে কোনও কোড পরিবর্তনের প্রয়োজন নেই

চিন্তার স্বাক্ষর ম্যানুয়ালি পরিচালনা করা

যদি আপনি সম্পূর্ণ পূর্ববর্তী প্রতিক্রিয়া পাঠানোর পরিবর্তে কথোপকথনের ইতিহাস ম্যানুয়ালি পরিবর্তন করেন এবং চিন্তাভাবনা থেকে উপকৃত হতে চান তবে আপনাকে মডেলের পালাটিতে অন্তর্ভুক্ত thought_signature সঠিকভাবে পরিচালনা করতে হবে।

মডেলের প্রেক্ষাপট সংরক্ষণ করা নিশ্চিত করতে এই নিয়মগুলি অনুসরণ করুন:

  • সর্বদা thought_signature মডেলটিকে তার মূল Part ভিতরে ফেরত পাঠান।
  • স্বাক্ষরযুক্ত Part স্বাক্ষরবিহীন অংশের সাথে একত্রিত করবেন না। এটি চিন্তার অবস্থানগত প্রেক্ষাপটকে ভেঙে দেয়।
  • স্বাক্ষরযুক্ত দুটি Parts একত্রিত করবেন না, কারণ স্বাক্ষর স্ট্রিংগুলি একত্রিত করা যাবে না।

চিন্তার স্বাক্ষর পরীক্ষা করা

বাস্তবায়নের জন্য প্রয়োজনীয় না হলেও, ডিবাগিং বা শিক্ষামূলক উদ্দেশ্যে thought_signature দেখতে আপনি প্রতিক্রিয়াটি পরীক্ষা করতে পারেন।

পাইথন

import base64
# After receiving a response from a model with thinking enabled
# response = client.models.generate_content(...)

# The signature is attached to the response part containing the function call
part = response.candidates[0].content.parts[0]
if part.thought_signature:
  print(base64.b64encode(part.thought_signature).decode("utf-8"))

জাভাস্ক্রিপ্ট

// After receiving a response from a model with thinking enabled
// const response = await ai.models.generateContent(...)

// The signature is attached to the response part containing the function call
const part = response.candidates[0].content.parts[0];
if (part.thoughtSignature) {
  console.log(part.thoughtSignature);
}

চিন্তার স্বাক্ষরের সীমাবদ্ধতা এবং ব্যবহার সম্পর্কে এবং সাধারণভাবে চিন্তাভাবনার মডেল সম্পর্কে আরও জানুন, চিন্তাভাবনা পৃষ্ঠায়।

সমান্তরাল ফাংশন কলিং

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

পাইথন

power_disco_ball = {
    "name": "power_disco_ball",
    "description": "Powers the spinning disco ball.",
    "parameters": {
        "type": "object",
        "properties": {
            "power": {
                "type": "boolean",
                "description": "Whether to turn the disco ball on or off.",
            }
        },
        "required": ["power"],
    },
}

start_music = {
    "name": "start_music",
    "description": "Play some music matching the specified parameters.",
    "parameters": {
        "type": "object",
        "properties": {
            "energetic": {
                "type": "boolean",
                "description": "Whether the music is energetic or not.",
            },
            "loud": {
                "type": "boolean",
                "description": "Whether the music is loud or not.",
            },
        },
        "required": ["energetic", "loud"],
    },
}

dim_lights = {
    "name": "dim_lights",
    "description": "Dim the lights.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "number",
                "description": "The brightness of the lights, 0.0 is off, 1.0 is full.",
            }
        },
        "required": ["brightness"],
    },
}

জাভাস্ক্রিপ্ট

import { Type } from '@google/genai';

const powerDiscoBall = {
  name: 'power_disco_ball',
  description: 'Powers the spinning disco ball.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      power: {
        type: Type.BOOLEAN,
        description: 'Whether to turn the disco ball on or off.'
      }
    },
    required: ['power']
  }
};

const startMusic = {
  name: 'start_music',
  description: 'Play some music matching the specified parameters.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      energetic: {
        type: Type.BOOLEAN,
        description: 'Whether the music is energetic or not.'
      },
      loud: {
        type: Type.BOOLEAN,
        description: 'Whether the music is loud or not.'
      }
    },
    required: ['energetic', 'loud']
  }
};

const dimLights = {
  name: 'dim_lights',
  description: 'Dim the lights.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      brightness: {
        type: Type.NUMBER,
        description: 'The brightness of the lights, 0.0 is off, 1.0 is full.'
      }
    },
    required: ['brightness']
  }
};

ফাংশন কলিং মোড কনফিগার করুন যাতে নির্দিষ্ট সমস্ত টুল ব্যবহার করা যায়। আরও জানতে, আপনি ফাংশন কলিং কনফিগার করার বিষয়ে পড়তে পারেন।

পাইথন

from google import genai
from google.genai import types

# Configure the client and tools
client = genai.Client()
house_tools = [
    types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]
config = types.GenerateContentConfig(
    tools=house_tools,
    automatic_function_calling=types.AutomaticFunctionCallingConfig(
        disable=True
    ),
    # Force the model to call 'any' function, instead of chatting.
    tool_config=types.ToolConfig(
        function_calling_config=types.FunctionCallingConfig(mode='ANY')
    ),
)

chat = client.chats.create(model="gemini-2.5-flash", config=config)
response = chat.send_message("Turn this place into a party!")

# Print out each of the function calls requested from this single call
print("Example 1: Forced function calling")
for fn in response.function_calls:
    args = ", ".join(f"{key}={val}" for key, val in fn.args.items())
    print(f"{fn.name}({args})")

জাভাস্ক্রিপ্ট

import { GoogleGenAI } from '@google/genai';

// Set up function declarations
const houseFns = [powerDiscoBall, startMusic, dimLights];

const config = {
    tools: [{
        functionDeclarations: houseFns
    }],
    // Force the model to call 'any' function, instead of chatting.
    toolConfig: {
        functionCallingConfig: {
            mode: 'any'
        }
    }
};

// Configure the client
const ai = new GoogleGenAI({});

// Create a chat session
const chat = ai.chats.create({
    model: 'gemini-2.5-flash',
    config: config
});
const response = await chat.sendMessage({message: 'Turn this place into a party!'});

// Print out each of the function calls requested from this single call
console.log("Example 1: Forced function calling");
for (const fn of response.functionCalls) {
    const args = Object.entries(fn.args)
        .map(([key, val]) => `${key}=${val}`)
        .join(', ');
    console.log(`${fn.name}(${args})`);
}

প্রতিটি মুদ্রিত ফলাফল মডেলটির অনুরোধ করা একটি একক ফাংশন কল প্রতিফলিত করে। ফলাফলগুলি ফেরত পাঠাতে, অনুরোধ করা ক্রমে প্রতিক্রিয়াগুলি অন্তর্ভুক্ত করুন।

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

পাইথন

from google import genai
from google.genai import types

# Actual function implementations
def power_disco_ball_impl(power: bool) -> dict:
    """Powers the spinning disco ball.

    Args:
        power: Whether to turn the disco ball on or off.

    Returns:
        A status dictionary indicating the current state.
    """
    return {"status": f"Disco ball powered {'on' if power else 'off'}"}

def start_music_impl(energetic: bool, loud: bool) -> dict:
    """Play some music matching the specified parameters.

    Args:
        energetic: Whether the music is energetic or not.
        loud: Whether the music is loud or not.

    Returns:
        A dictionary containing the music settings.
    """
    music_type = "energetic" if energetic else "chill"
    volume = "loud" if loud else "quiet"
    return {"music_type": music_type, "volume": volume}

def dim_lights_impl(brightness: float) -> dict:
    """Dim the lights.

    Args:
        brightness: The brightness of the lights, 0.0 is off, 1.0 is full.

    Returns:
        A dictionary containing the new brightness setting.
    """
    return {"brightness": brightness}

# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
    tools=[power_disco_ball_impl, start_music_impl, dim_lights_impl]
)

# Make the request
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Do everything you need to this place into party!",
    config=config,
)

print("\nExample 2: Automatic function calling")
print(response.text)
# I've turned on the disco ball, started playing loud and energetic music, and dimmed the lights to 50% brightness. Let's get this party started!

কম্পোজিশনাল ফাংশন কলিং

কম্পোজিশনাল বা সিকোয়েন্সিয়াল ফাংশন কলিং জেমিনিকে একাধিক ফাংশন কল একসাথে চেইন করে একটি জটিল অনুরোধ পূরণ করতে সাহায্য করে। উদাহরণস্বরূপ, "আমার বর্তমান অবস্থানের তাপমাত্রা পান" উত্তর দেওয়ার জন্য, জেমিনি API প্রথমে একটি get_current_location() ফাংশন চালু করতে পারে এবং তারপরে একটি get_weather() ফাংশন ব্যবহার করতে পারে যা অবস্থানটিকে একটি প্যারামিটার হিসেবে গ্রহণ করে।

নিম্নলিখিত উদাহরণটি পাইথন SDK এবং স্বয়ংক্রিয় ফাংশন কলিং ব্যবহার করে কম্পোজিশনাল ফাংশন কলিং কীভাবে বাস্তবায়ন করতে হয় তা দেখায়।

পাইথন

এই উদাহরণে google-genai Python SDK-এর স্বয়ংক্রিয় ফাংশন কলিং বৈশিষ্ট্য ব্যবহার করা হয়েছে। SDK স্বয়ংক্রিয়ভাবে Python ফাংশনগুলিকে প্রয়োজনীয় স্কিমায় রূপান্তর করে, মডেলের অনুরোধে ফাংশন কলগুলি কার্যকর করে এবং কাজটি সম্পন্ন করার জন্য ফলাফলগুলি মডেলের কাছে ফেরত পাঠায়।

import os
from google import genai
from google.genai import types

# Example Functions
def get_weather_forecast(location: str) -> dict:
    """Gets the current weather temperature for a given location."""
    print(f"Tool Call: get_weather_forecast(location={location})")
    # TODO: Make API call
    print("Tool Response: {'temperature': 25, 'unit': 'celsius'}")
    return {"temperature": 25, "unit": "celsius"}  # Dummy response

def set_thermostat_temperature(temperature: int) -> dict:
    """Sets the thermostat to a desired temperature."""
    print(f"Tool Call: set_thermostat_temperature(temperature={temperature})")
    # TODO: Interact with a thermostat API
    print("Tool Response: {'status': 'success'}")
    return {"status": "success"}

# Configure the client and model
client = genai.Client()
config = types.GenerateContentConfig(
    tools=[get_weather_forecast, set_thermostat_temperature]
)

# Make the request
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
    config=config,
)

# Print the final, user-facing response
print(response.text)

প্রত্যাশিত আউটপুট

কোডটি রান করলে, আপনি দেখতে পাবেন যে SDK ফাংশন কলগুলি পরিচালনা করছে। মডেলটি প্রথমে get_weather_forecast কল করে, তাপমাত্রা গ্রহণ করে এবং তারপর প্রম্পটে থাকা লজিকের উপর ভিত্তি করে সঠিক মান সহ set_thermostat_temperature কল করে।

Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. I've set the thermostat to 20°C.

জাভাস্ক্রিপ্ট

এই উদাহরণে দেখানো হয়েছে কিভাবে জাভাস্ক্রিপ্ট/টাইপস্ক্রিপ্ট SDK ব্যবহার করে ম্যানুয়াল এক্সিকিউশন লুপ ব্যবহার করে কমোপজিশনাল ফাংশন কলিং করতে হয়।

import { GoogleGenAI, Type } from "@google/genai";

// Configure the client
const ai = new GoogleGenAI({});

// Example Functions
function get_weather_forecast({ location }) {
  console.log(`Tool Call: get_weather_forecast(location=${location})`);
  // TODO: Make API call
  console.log("Tool Response: {'temperature': 25, 'unit': 'celsius'}");
  return { temperature: 25, unit: "celsius" };
}

function set_thermostat_temperature({ temperature }) {
  console.log(
    `Tool Call: set_thermostat_temperature(temperature=${temperature})`,
  );
  // TODO: Make API call
  console.log("Tool Response: {'status': 'success'}");
  return { status: "success" };
}

const toolFunctions = {
  get_weather_forecast,
  set_thermostat_temperature,
};

const tools = [
  {
    functionDeclarations: [
      {
        name: "get_weather_forecast",
        description:
          "Gets the current weather temperature for a given location.",
        parameters: {
          type: Type.OBJECT,
          properties: {
            location: {
              type: Type.STRING,
            },
          },
          required: ["location"],
        },
      },
      {
        name: "set_thermostat_temperature",
        description: "Sets the thermostat to a desired temperature.",
        parameters: {
          type: Type.OBJECT,
          properties: {
            temperature: {
              type: Type.NUMBER,
            },
          },
          required: ["temperature"],
        },
      },
    ],
  },
];

// Prompt for the model
let contents = [
  {
    role: "user",
    parts: [
      {
        text: "If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
      },
    ],
  },
];

// Loop until the model has no more function calls to make
while (true) {
  const result = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    contents,
    config: { tools },
  });

  if (result.functionCalls && result.functionCalls.length > 0) {
    const functionCall = result.functionCalls[0];

    const { name, args } = functionCall;

    if (!toolFunctions[name]) {
      throw new Error(`Unknown function call: ${name}`);
    }

    // Call the function and get the response.
    const toolResponse = toolFunctions[name](args);

    const functionResponsePart = {
      name: functionCall.name,
      response: {
        result: toolResponse,
      },
    };

    // Send the function response back to the model.
    contents.push({
      role: "model",
      parts: [
        {
          functionCall: functionCall,
        },
      ],
    });
    contents.push({
      role: "user",
      parts: [
        {
          functionResponse: functionResponsePart,
        },
      ],
    });
  } else {
    // No more function calls, break the loop.
    console.log(result.text);
    break;
  }
}

প্রত্যাশিত আউটপুট

কোডটি রান করলে, আপনি দেখতে পাবেন যে SDK ফাংশন কলগুলি পরিচালনা করছে। মডেলটি প্রথমে get_weather_forecast কল করে, তাপমাত্রা গ্রহণ করে এবং তারপর প্রম্পটে থাকা লজিকের উপর ভিত্তি করে সঠিক মান সহ set_thermostat_temperature কল করে।

Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. It's 25°C in London, so I've set the thermostat to 20°C.

কম্পোজিশনাল ফাংশন কলিং একটি নেটিভ লাইভ এপিআই বৈশিষ্ট্য। এর অর্থ হল লাইভ এপিআই পাইথন এসডিকে-র মতো ফাংশন কলিং পরিচালনা করতে পারে।

পাইথন

# Light control schemas
turn_on_the_lights_schema = {'name': 'turn_on_the_lights'}
turn_off_the_lights_schema = {'name': 'turn_off_the_lights'}

prompt = """
  Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
  """

tools = [
    {'code_execution': {}},
    {'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]}
]

await run(prompt, tools=tools, modality="AUDIO")

জাভাস্ক্রিপ্ট

// Light control schemas
const turnOnTheLightsSchema = { name: 'turn_on_the_lights' };
const turnOffTheLightsSchema = { name: 'turn_off_the_lights' };

const prompt = `
  Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
`;

const tools = [
  { codeExecution: {} },
  { functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] }
];

await run(prompt, tools=tools, modality="AUDIO")

ফাংশন কলিং মোড

জেমিনি এপিআই আপনাকে মডেলটি কীভাবে প্রদত্ত সরঞ্জামগুলি (ফাংশন ঘোষণা) ব্যবহার করে তা নিয়ন্ত্রণ করতে দেয়। বিশেষ করে, আপনি . function_calling_config এর মধ্যে মোড সেট করতে পারেন।

  • AUTO (Default) : মডেলটি সিদ্ধান্ত নেয় যে প্রম্পট এবং প্রসঙ্গের উপর ভিত্তি করে একটি প্রাকৃতিক ভাষার প্রতিক্রিয়া তৈরি করা হবে নাকি একটি ফাংশন কলের পরামর্শ দেওয়া হবে। এটি সবচেয়ে নমনীয় মোড এবং বেশিরভাগ পরিস্থিতিতে সুপারিশ করা হয়।
  • ANY : মডেলটি সর্বদা একটি ফাংশন কল পূর্বাভাস দিতে বাধ্য এবং ফাংশন স্কিমা আনুগত্যের নিশ্চয়তা দেয়। যদি allowed_function_names নির্দিষ্ট না করা থাকে, তাহলে মডেলটি প্রদত্ত যেকোনো ফাংশন ঘোষণা থেকে বেছে নিতে পারে। যদি allowed_function_names একটি তালিকা হিসাবে দেওয়া থাকে, তাহলে মডেলটি কেবল সেই তালিকার ফাংশনগুলি থেকে বেছে নিতে পারে। প্রতিটি প্রম্পটে (যদি প্রযোজ্য হয়) ফাংশন কল প্রতিক্রিয়ার প্রয়োজন হলে এই মোডটি ব্যবহার করুন।
  • NONE : মডেলটিতে ফাংশন কল করা নিষিদ্ধ । এটি কোনও ফাংশন ঘোষণা ছাড়াই একটি অনুরোধ পাঠানোর সমতুল্য। আপনার টুলের সংজ্ঞাগুলি অপসারণ না করেই ফাংশন কলিং অস্থায়ীভাবে অক্ষম করতে এটি ব্যবহার করুন।
  • VALIDATED (প্রিভিউ): মডেলটি ফাংশন কল বা প্রাকৃতিক ভাষা উভয়ের পূর্বাভাস দিতে বাধ্য, এবং ফাংশন স্কিমা আনুগত্য নিশ্চিত করে। যদি allowed_function_names প্রদান করা না হয়, তাহলে মডেলটি সমস্ত উপলব্ধ ফাংশন ঘোষণা থেকে নির্বাচন করে। যদি allowed_function_names প্রদান করা হয়, তাহলে মডেলটি অনুমোদিত ফাংশনের সেট থেকে নির্বাচন করে।

পাইথন

from google.genai import types

# Configure function calling mode
tool_config = types.ToolConfig(
    function_calling_config=types.FunctionCallingConfig(
        mode="ANY", allowed_function_names=["get_current_temperature"]
    )
)

# Create the generation config
config = types.GenerateContentConfig(
    tools=[tools],  # not defined here.
    tool_config=tool_config,
)

জাভাস্ক্রিপ্ট

import { FunctionCallingConfigMode } from '@google/genai';

// Configure function calling mode
const toolConfig = {
  functionCallingConfig: {
    mode: FunctionCallingConfigMode.ANY,
    allowedFunctionNames: ['get_current_temperature']
  }
};

// Create the generation config
const config = {
  tools: tools, // not defined here.
  toolConfig: toolConfig,
};

স্বয়ংক্রিয় ফাংশন কলিং (শুধুমাত্র পাইথন)

পাইথন SDK ব্যবহার করার সময়, আপনি পাইথন ফাংশনগুলিকে সরাসরি টুল হিসেবে প্রদান করতে পারেন। SDK এই ফাংশনগুলিকে ঘোষণায় রূপান্তর করে, ফাংশন কল এক্সিকিউশন পরিচালনা করে এবং আপনার জন্য প্রতিক্রিয়া চক্র পরিচালনা করে। টাইপ ইঙ্গিত এবং একটি ডকস্ট্রিং দিয়ে আপনার ফাংশনটি সংজ্ঞায়িত করুন। সর্বোত্তম ফলাফলের জন্য, Google-স্টাইল ডকস্ট্রিং ব্যবহার করার পরামর্শ দেওয়া হচ্ছে। SDK তখন স্বয়ংক্রিয়ভাবে করবে:

  1. মডেল থেকে ফাংশন কল প্রতিক্রিয়া সনাক্ত করুন।
  2. আপনার কোডে সংশ্লিষ্ট পাইথন ফাংশনটি কল করুন।
  3. ফাংশনের প্রতিক্রিয়া মডেলটিতে ফেরত পাঠান।
  4. মডেলের চূড়ান্ত টেক্সট প্রতিক্রিয়াটি ফেরত দিন।

SDK বর্তমানে জেনারেট করা ফাংশন ডিক্লারেশনের প্রোপার্টি ডেসক্রিপশন স্লটে আর্গুমেন্টের বর্ণনা পার্স করে না। পরিবর্তে, এটি সম্পূর্ণ ডকস্ট্রিংটিকে টপ-লেভেল ফাংশন ডেসক্রিপশন হিসেবে পাঠায়।

পাইথন

from google import genai
from google.genai import types

# Define the function with type hints and docstring
def get_current_temperature(location: str) -> dict:
    """Gets the current temperature for a given location.

    Args:
        location: The city and state, e.g. San Francisco, CA

    Returns:
        A dictionary containing the temperature and unit.
    """
    # ... (implementation) ...
    return {"temperature": 25, "unit": "Celsius"}

# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
    tools=[get_current_temperature]
)  # Pass the function itself

# Make the request
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="What's the temperature in Boston?",
    config=config,
)

print(response.text)  # The SDK handles the function call and returns the final text

আপনি নিম্নলিখিত পদ্ধতি ব্যবহার করে স্বয়ংক্রিয় ফাংশন কলিং অক্ষম করতে পারেন:

পাইথন

config = types.GenerateContentConfig(
    tools=[get_current_temperature],
    automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)

স্বয়ংক্রিয় ফাংশন স্কিমা ঘোষণা

API নিম্নলিখিত যেকোনো ধরণের বর্ণনা করতে সক্ষম। Pydantic প্রকারগুলি অনুমোদিত, যতক্ষণ না তাদের উপর সংজ্ঞায়িত ক্ষেত্রগুলি অনুমোদিত প্রকারগুলি দিয়ে গঠিত হয়। Dict প্রকারগুলি (যেমন dict[str: int] ) এখানে ভালভাবে সমর্থিত নয়, সেগুলি ব্যবহার করবেন না।

পাইথন

AllowedType = (
  int | float | bool | str | list['AllowedType'] | pydantic.BaseModel)

অনুমানকৃত স্কিমাটি কেমন দেখাচ্ছে তা দেখতে, আপনি from_callable ব্যবহার করে এটি রূপান্তর করতে পারেন:

পাইথন

from google import genai
from google.genai import types

def multiply(a: float, b: float):
    """Returns a * b."""
    return a * b

client = genai.Client()
fn_decl = types.FunctionDeclaration.from_callable(callable=multiply, client=client)

# to_json_dict() provides a clean JSON representation.
print(fn_decl.to_json_dict())

মাল্টি-টুল ব্যবহার: ফাংশন কলিংয়ের সাথে নেটিভ টুল একত্রিত করুন

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

পাইথন

# Multiple tasks example - combining lights, code execution, and search
prompt = """
  Hey, I need you to do three things for me.

    1.  Turn on the lights.
    2.  Then compute the largest prime palindrome under 100000.
    3.  Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.

  Thanks!
  """

tools = [
    {'google_search': {}},
    {'code_execution': {}},
    {'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]} # not defined here.
]

# Execute the prompt with specified tools in audio modality
await run(prompt, tools=tools, modality="AUDIO")

জাভাস্ক্রিপ্ট

// Multiple tasks example - combining lights, code execution, and search
const prompt = `
  Hey, I need you to do three things for me.

    1.  Turn on the lights.
    2.  Then compute the largest prime palindrome under 100000.
    3.  Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.

  Thanks!
`;

const tools = [
  { googleSearch: {} },
  { codeExecution: {} },
  { functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] } // not defined here.
];

// Execute the prompt with specified tools in audio modality
await run(prompt, {tools: tools, modality: "AUDIO"});

পাইথন ডেভেলপাররা Live API Tool Use notebook- এ এটি ব্যবহার করে দেখতে পারেন।

মডেল কনটেক্সট প্রোটোকল (MCP)

মডেল কনটেক্সট প্রোটোকল (MCP) হল AI অ্যাপ্লিকেশনগুলিকে বহিরাগত সরঞ্জাম এবং ডেটার সাথে সংযুক্ত করার জন্য একটি উন্মুক্ত মান। MCP মডেলগুলিকে ফাংশন (টুল), ডেটা সোর্স (রিসোর্স) বা পূর্বনির্ধারিত প্রম্পটগুলির মতো প্রসঙ্গ অ্যাক্সেস করার জন্য একটি সাধারণ প্রোটোকল প্রদান করে।

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

এখানে, আপনি জেমিনি এবং mcp SDK এর সাথে স্থানীয় MCP সার্ভার কীভাবে ব্যবহার করবেন তার একটি উদাহরণ পেতে পারেন।

পাইথন

আপনার পছন্দের প্ল্যাটফর্মে mcp SDK- এর সর্বশেষ সংস্করণ ইনস্টল করা আছে কিনা তা নিশ্চিত করুন।

pip install mcp
import os
import asyncio
from datetime import datetime
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai

client = genai.Client()

# Create server parameters for stdio connection
server_params = StdioServerParameters(
    command="npx",  # Executable
    args=["-y", "@philschmid/weather-mcp"],  # MCP Server
    env=None,  # Optional environment variables
)

async def run():
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Prompt to get the weather for the current day in London.
            prompt = f"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?"

            # Initialize the connection between client and server
            await session.initialize()

            # Send request to the model with MCP function declarations
            response = await client.aio.models.generate_content(
                model="gemini-2.5-flash",
                contents=prompt,
                config=genai.types.GenerateContentConfig(
                    temperature=0,
                    tools=[session],  # uses the session, will automatically call the tool
                    # Uncomment if you **don't** want the SDK to automatically call the tool
                    # automatic_function_calling=genai.types.AutomaticFunctionCallingConfig(
                    #     disable=True
                    # ),
                ),
            )
            print(response.text)

# Start the asyncio event loop and run the main function
asyncio.run(run())

জাভাস্ক্রিপ্ট

আপনার পছন্দের প্ল্যাটফর্মে mcp SDK-এর সর্বশেষ সংস্করণ ইনস্টল করা আছে কিনা তা নিশ্চিত করুন।

npm install @modelcontextprotocol/sdk
import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai';
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

// Create server parameters for stdio connection
const serverParams = new StdioClientTransport({
  command: "npx", // Executable
  args: ["-y", "@philschmid/weather-mcp"] // MCP Server
});

const client = new Client(
  {
    name: "example-client",
    version: "1.0.0"
  }
);

// Configure the client
const ai = new GoogleGenAI({});

// Initialize the connection between client and server
await client.connect(serverParams);

// Send request to the model with MCP tools
const response = await ai.models.generateContent({
  model: "gemini-2.5-flash",
  contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`,
  config: {
    tools: [mcpToTool(client)],  // uses the session, will automatically call the tool
    // Uncomment if you **don't** want the sdk to automatically call the tool
    // automaticFunctionCalling: {
    //   disable: true,
    // },
  },
});
console.log(response.text)

// Close the connection
await client.close();

অন্তর্নির্মিত MCP সমর্থনের সীমাবদ্ধতা

আমাদের SDK-তে বিল্ট-ইন MCP সাপোর্ট একটি পরীক্ষামূলক বৈশিষ্ট্য এবং এর নিম্নলিখিত সীমাবদ্ধতা রয়েছে:

  • শুধুমাত্র সরঞ্জামগুলি সমর্থিত, সম্পদ বা প্রম্পট নয়
  • এটি পাইথন এবং জাভাস্ক্রিপ্ট/টাইপস্ক্রিপ্ট SDK-এর জন্য উপলব্ধ।
  • ভবিষ্যতের রিলিজগুলিতে উল্লেখযোগ্য পরিবর্তন ঘটতে পারে।

যদি MCP সার্ভারগুলি আপনার তৈরি করা জিনিসকে সীমাবদ্ধ করে, তাহলে ম্যানুয়াল ইন্টিগ্রেশন সবসময়ই একটি বিকল্প।

সমর্থিত মডেল

এই বিভাগে মডেল এবং তাদের ফাংশন কলিং ক্ষমতা তালিকাভুক্ত করা হয়েছে। পরীক্ষামূলক মডেলগুলি অন্তর্ভুক্ত করা হয়নি। আপনি মডেল ওভারভিউ পৃষ্ঠায় একটি বিস্তৃত ক্ষমতা ওভারভিউ পেতে পারেন।

মডেল ফাংশন কলিং সমান্তরাল ফাংশন কলিং কম্পোজিশনাল ফাংশন কলিং
জেমিনি ২.৫ প্রো ✔️ ✔️ ✔️
জেমিনি 2.5 ফ্ল্যাশ ✔️ ✔️ ✔️
জেমিনি ২.৫ ফ্ল্যাশ-লাইট ✔️ ✔️ ✔️
জেমিনি ২.০ ফ্ল্যাশ ✔️ ✔️ ✔️
জেমিনি ২.০ ফ্ল্যাশ-লাইট এক্স এক্স এক্স

সেরা অনুশীলন

  • ফাংশন এবং প্যারামিটারের বর্ণনা: আপনার বর্ণনায় অত্যন্ত স্পষ্ট এবং সুনির্দিষ্ট থাকুন। মডেলটি সঠিক ফাংশন নির্বাচন করতে এবং উপযুক্ত যুক্তি প্রদান করতে এগুলোর উপর নির্ভর করে।
  • নামকরণ: বর্ণনামূলক ফাংশনের নাম ব্যবহার করুন (স্পেস, পিরিয়ড বা ড্যাশ ছাড়া)।
  • শক্তিশালী টাইপিং: ত্রুটি কমাতে প্যারামিটারের জন্য নির্দিষ্ট প্রকার (পূর্ণসংখ্যা, স্ট্রিং, এনাম) ব্যবহার করুন। যদি কোনও প্যারামিটারে বৈধ মানের সীমিত সেট থাকে, তাহলে একটি এনাম ব্যবহার করুন।
  • টুল নির্বাচন: মডেলটি ইচ্ছামত সংখ্যক টুল ব্যবহার করতে পারে, কিন্তু অনেক বেশি টুল ব্যবহার করলে ভুল বা অপ্রতুল টুল নির্বাচনের ঝুঁকি বেড়ে যেতে পারে। সেরা ফলাফলের জন্য, কেবলমাত্র প্রসঙ্গ বা কাজের জন্য প্রাসঙ্গিক টুলগুলি সরবরাহ করার লক্ষ্য রাখুন, আদর্শভাবে সক্রিয় সেটটি সর্বোচ্চ ১০-২০-এর মধ্যে রাখুন। যদি আপনার কাছে প্রচুর সংখ্যক টুল থাকে তবে কথোপকথনের প্রেক্ষাপটের উপর ভিত্তি করে গতিশীল টুল নির্বাচন বিবেচনা করুন।
  • প্রম্পট ইঞ্জিনিয়ারিং:
    • প্রেক্ষাপট প্রদান করুন: মডেলকে তার ভূমিকা বলুন (যেমন, "আপনি একজন সহায়ক আবহাওয়া সহকারী।")।
    • নির্দেশনা দিন: কীভাবে এবং কখন ফাংশন ব্যবহার করবেন তা নির্দিষ্ট করুন (যেমন, "তারিখ অনুমান করবেন না; পূর্বাভাসের জন্য সর্বদা ভবিষ্যতের তারিখ ব্যবহার করুন।")।
    • স্পষ্টীকরণ উৎসাহিত করুন: প্রয়োজনে মডেলকে স্পষ্টীকরণমূলক প্রশ্ন জিজ্ঞাসা করার নির্দেশ দিন।
  • তাপমাত্রা: আরও নির্ধারক এবং নির্ভরযোগ্য ফাংশন কলের জন্য কম তাপমাত্রা (যেমন, 0) ব্যবহার করুন।
  • বৈধকরণ: যদি কোনও ফাংশন কলের উল্লেখযোগ্য পরিণতি হয় (যেমন, অর্ডার দেওয়া), তাহলে এটি কার্যকর করার আগে ব্যবহারকারীর সাথে কলটি যাচাই করুন।
  • সমাপ্তির কারণ পরীক্ষা করুন: মডেলটি একটি বৈধ ফাংশন কল তৈরি করতে ব্যর্থ হলে, মডেলের প্রতিক্রিয়ায় সর্বদা finishReason পরীক্ষা করুন।
  • ত্রুটি পরিচালনা : অপ্রত্যাশিত ইনপুট বা API ব্যর্থতাগুলিকে সুন্দরভাবে পরিচালনা করার জন্য আপনার ফাংশনগুলিতে শক্তিশালী ত্রুটি পরিচালনা বাস্তবায়ন করুন। তথ্যপূর্ণ ত্রুটি বার্তাগুলি ফেরত দিন যা মডেলটি ব্যবহারকারীর কাছে সহায়ক প্রতিক্রিয়া তৈরি করতে ব্যবহার করতে পারে।
  • নিরাপত্তা: বহিরাগত API গুলিতে কল করার সময় নিরাপত্তার বিষয়ে সচেতন থাকুন। যথাযথ প্রমাণীকরণ এবং অনুমোদন প্রক্রিয়া ব্যবহার করুন। ফাংশন কলগুলিতে সংবেদনশীল ডেটা প্রকাশ করা এড়িয়ে চলুন।
  • টোকেন লিমিট: ফাংশনের বর্ণনা এবং প্যারামিটারগুলি আপনার ইনপুট টোকেন লিমিটের মধ্যে গণনা করা হবে। যদি আপনি টোকেন লিমিট অতিক্রম করেন, তাহলে ফাংশনের সংখ্যা বা বর্ণনার দৈর্ঘ্য সীমিত করার কথা বিবেচনা করুন, জটিল কাজগুলিকে ছোট, আরও কেন্দ্রীভূত ফাংশন সেটে ভাগ করুন।

নোট এবং সীমাবদ্ধতা