فراخوانی تابع با Gemini API

«فراخوانی تابع» به شما امکان می‌دهد مدل‌ها را به ابزارها و میاناهای برنامه‌سازی کاربردی خارجی متصل کنید. این مدل به‌جای تولید پاسخ‌های نوشتاری، تعیین می‌کند که چه زمانی توابع خاصی را فراخوانی کند و پارامترهای لازم را برای اجرای کنش‌های دنیای واقعی ارائه می‌دهد. این کار به مدل امکان می‌دهد به‌عنوان پلی بین زبان طبیعی و کنش‌ها و داده‌های دنیای واقعی عمل کند. فراخوانی تابع ۳ مورد استفاده اصلی دارد:

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

می‌توانید نمونه‌هایی از این موارد استفاده را در زیر مرور کنید:

زمان‌بندی جلسه

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

Python

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-3.8-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"ID: {function_call.id}")
    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)

JavaScript

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-3.8-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(`ID: ${functionCall.id}`);
  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);
}

رفتن

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    // Define the function declaration for the model
    scheduleMeetingFunc := &genai.FunctionDeclaration{
        Name:        "schedule_meeting",
        Description: "Schedules a meeting with specified attendees at a given time and date.",
        Parameters: &genai.Schema{
            Type: genai.TypeObject,
            Properties: map[string]*genai.Schema{
                "attendees": {
                    Type:        genai.TypeArray,
                    Items:       &genai.Schema{Type: genai.TypeString},
                    Description: "List of people attending the meeting.",
                },
                "date": {
                    Type:        genai.TypeString,
                    Description: "Date of the meeting (e.g., '2024-07-29')",
                },
                "time": {
                    Type:        genai.TypeString,
                    Description: "Time of the meeting (e.g., '15:00')",
                },
                "topic": {
                    Type:        genai.TypeString,
                    Description: "The subject or topic of the meeting.",
                },
            },
            Required: []string{"attendees", "date", "time", "topic"},
        },
    }

    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {FunctionDeclarations: []*genai.FunctionDeclaration{scheduleMeetingFunc}},
        },
    }

    // Send request with function declarations
    response, err := client.Models.GenerateContent(
        ctx,
        "gemini-3.8-flash",
        genai.Text("Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about the Q3 planning."),
        config,
    )
    if err != nil {
        log.Fatal(err)
    }

    // Check for a function call
    if len(response.FunctionCalls()) > 0 {
        functionCall := response.FunctionCalls()[0]
        fmt.Printf("Function to call: %s\n", functionCall.Name)
        fmt.Printf("ID: %s\n", functionCall.ID)
        fmt.Printf("Arguments: %v\n", functionCall.Args)
        // In a real app, you would call your function here:
        // result := scheduleMeeting(functionCall.Args)
    } else {
        fmt.Println("No function call found in the response.")
        fmt.Println(response.Text())
    }
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-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"]
            }
          }
        ]
      }
    ]
  }'

دریافت آب‌وهوا

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

Python

from google import genai
from google.genai import types

# Define the function declaration for the model
weather_function = {
    "name": "get_current_temperature",
    "description": "Gets the current temperature for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city name, e.g. San Francisco",
            },
        },
        "required": ["location"],
    },
}

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

# Send request with function declarations
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="What's the temperature in London?",
    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"ID: {function_call.id}")
    print(f"Arguments: {function_call.args}")
    #  In a real app, you would call your function here:
    #  result = get_current_temperature(**function_call.args)
else:
    print("No function call found in the response.")
    print(response.text)

JavaScript

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

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

// Define the function declaration for the model
const weatherFunctionDeclaration = {
  name: 'get_current_temperature',
  description: 'Gets the current temperature for a given location.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      location: {
        type: Type.STRING,
        description: 'The city name, e.g. San Francisco',
      },
    },
    required: ['location'],
  },
};

// Send request with function declarations
const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: "What's the temperature in London?",
  config: {
    tools: [{
      functionDeclarations: [weatherFunctionDeclaration]
    }],
  },
});

// 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(`ID: ${functionCall.id}`);
  console.log(`Arguments: ${JSON.stringify(functionCall.args)}`);
  // In a real app, you would call your actual function here:
  // const result = await getCurrentTemperature(functionCall.args);
} else {
  console.log("No function call found in the response.");
  console.log(response.text);
}

رفتن

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    // Define the function declaration for the model
    weatherFunc := &genai.FunctionDeclaration{
        Name:        "get_current_temperature",
        Description: "Gets the current temperature for a given location.",
        Parameters: &genai.Schema{
            Type: genai.TypeObject,
            Properties: map[string]*genai.Schema{
                "location": {
                    Type:        genai.TypeString,
                    Description: "The city name, e.g. San Francisco",
                },
            },
            Required: []string{"location"},
        },
    }

    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {FunctionDeclarations: []*genai.FunctionDeclaration{weatherFunc}},
        },
    }

    // Send request with function declarations
    response, err := client.Models.GenerateContent(
        ctx,
        "gemini-3.8-flash",
        genai.Text("What's the temperature in London?"),
        config,
    )
    if err != nil {
        log.Fatal(err)
    }

    // Check for a function call
    if len(response.FunctionCalls()) > 0 {
        functionCall := response.FunctionCalls()[0]
        fmt.Printf("Function to call: %s\n", functionCall.Name)
        fmt.Printf("ID: %s\n", functionCall.ID)
        fmt.Printf("Arguments: %v\n", functionCall.Args)
        // In a real app, you would call your function here:
        // result := getCurrentTemperature(functionCall.Args)
    } else {
        fmt.Println("No function call found in the response.")
        fmt.Println(response.Text())
    }
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "What'\''s the temperature in London?"
          }
        ]
      }
    ],
    "tools": [
      {
        "functionDeclarations": [
          {
            "name": "get_current_temperature",
            "description": "Gets the current temperature for a given location.",
            "parameters": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "The city name, e.g. San Francisco"
                }
              },
              "required": ["location"]
            }
          }
        ]
      }
    ]
  }'

ایجاد نمودار

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

Python

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

# Define the function declaration for the model
create_chart_function = {
    "name": "create_bar_chart",
    "description": "Creates a bar chart given a title, labels, and corresponding values.",
    "parameters": {
        "type": "object",
        "properties": {
            "title": {
                "type": "string",
                "description": "The title for the chart.",
            },
            "labels": {
                "type": "array",
                "items": {"type": "string"},
                "description": "List of labels for the data points (e.g., ['Q1', 'Q2', 'Q3']).",
            },
            "values": {
                "type": "array",
                "items": {"type": "number"},
                "description": "List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000]).",
            },
        },
        "required": ["title", "labels", "values"],
    },
}

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

# Send request with function declarations
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Create a bar chart titled 'Quarterly Sales' with data: Q1: 50000, Q2: 75000, Q3: 60000.",
    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"ID: {function_call.id}")
    print(f"Arguments: {function_call.args}")
    #  In a real app, you would call your function here using a charting library:
    #  result = create_bar_chart(**function_call.args)
else:
    print("No function call found in the response.")
    print(response.text)

JavaScript

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

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

// Define the function declaration for the model
const createChartFunctionDeclaration = {
  name: 'create_bar_chart',
  description: 'Creates a bar chart given a title, labels, and corresponding values.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      title: {
        type: Type.STRING,
        description: 'The title for the chart.',
      },
      labels: {
        type: Type.ARRAY,
        items: { type: Type.STRING },
        description: 'List of labels for the data points (e.g., ["Q1", "Q2", "Q3"]).',
      },
      values: {
        type: Type.ARRAY,
        items: { type: Type.NUMBER },
        description: 'List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000]).',
      },
    },
    required: ['title', 'labels', 'values'],
  },
};

// Send request with function declarations
const response = await ai.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: "Create a bar chart titled 'Quarterly Sales' with data: Q1: 50000, Q2: 75000, Q3: 60000.",
  config: {
    tools: [{
      functionDeclarations: [createChartFunctionDeclaration]
    }],
  },
});

// 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(`ID: ${functionCall.id}`);
  console.log(`Arguments: ${JSON.stringify(functionCall.args)}`);
  // In a real app, you would call your actual function here:
  // const result = await createBarChart(functionCall.args);
} else {
  console.log("No function call found in the response.");
  console.log(response.text);
}

رفتن

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    // Define the function declaration for the model
    createChartFunc := &genai.FunctionDeclaration{
        Name:        "create_bar_chart",
        Description: "Creates a bar chart given a title, labels, and corresponding values.",
        Parameters: &genai.Schema{
            Type: genai.TypeObject,
            Properties: map[string]*genai.Schema{
                "title": {
                    Type:        genai.TypeString,
                    Description: "The title for the chart.",
                },
                "labels": {
                    Type:        genai.TypeArray,
                    Items:       &genai.Schema{Type: genai.TypeString},
                    Description: "List of labels for the data points (e.g., ['Q1', 'Q2', 'Q3']).",
                },
                "values": {
                    Type:        genai.TypeArray,
                    Items:       &genai.Schema{Type: genai.TypeNumber},
                    Description: "List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000]).",
                },
            },
            Required: []string{"title", "labels", "values"},
        },
    }

    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {FunctionDeclarations: []*genai.FunctionDeclaration{createChartFunc}},
        },
    }

    // Send request with function declarations
    response, err := client.Models.GenerateContent(
        ctx,
        "gemini-3.8-flash",
        genai.Text("Create a bar chart titled 'Quarterly Sales' with data: Q1: 50000, Q2: 75000, Q3: 60000."),
        config,
    )
    if err != nil {
        log.Fatal(err)
    }

    // Check for a function call
    if len(response.FunctionCalls()) > 0 {
        functionCall := response.FunctionCalls()[0]
        fmt.Printf("Function to call: %s\n", functionCall.Name)
        fmt.Printf("ID: %s\n", functionCall.ID)
        fmt.Printf("Arguments: %v\n", functionCall.Args)
        // In a real app, you would call your function here using a charting library:
        // result := createBarChart(functionCall.Args)
    } else {
        fmt.Println("No function call found in the response.")
        fmt.Println(response.Text())
    }
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "Create a bar chart titled ''Quarterly Sales'' with data: Q1: 50000, Q2: 75000, Q3: 60000."
          }
        ]
      }
    ],
    "tools": [
      {
        "functionDeclarations": [
          {
            "name": "create_bar_chart",
            "description": "Creates a bar chart given a title, labels, and corresponding values.",
            "parameters": {
              "type": "object",
              "properties": {
                "title": {
                  "type": "string",
                  "description": "The title for the chart."
                },
                "labels": {
                  "type": "array",
                  "items": {"type": "string"},
                  "description": "List of labels for the data points (e.g., [''Q1'', ''Q2'', ''Q3''])."
                },
                "values": {
                  "type": "array",
                  "items": {"type": "number"},
                  "description": "List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000])."
                }
              },
              "required": ["title", "labels", "values"]
            }
          }
        ]
      }
    ]
  }'

نحوه عملکرد فراخوانی تابع

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

فراخوانی تابع شامل تعامل ساختاریافته بین برنامه شما، مدل، و توابع خارجی است. در اینجا خلاصه‌ای از این فرایند ارائه شده است:

  1. تعریف اعلان تابع: اعلان تابع را در کد برنامه‌تان تعریف کنید. «اعلامیه‌های تابع» نام، پارامترها، و هدف تابع را برای مدل شرح می‌دهند.
  2. فراخوانی API با بیانیه‌های تابع: پیام‌واره کاربر را به‌همراه بیانیه(های) تابع به مدل ارسال کنید. این ویژگی درخواست را تجزیه‌وتحلیل می‌کند و تعیین می‌کند که آیا تماس تابع مفید خواهد بود یا نه. درصورت وجود، با یک شیء JSON ساختاریافته که حاوی نام تابع، آرگومان‌ها، و یک id منحصربه‌فرد است پاسخ می‌دهد (این id اکنون همیشه توسط API برای مدل‌های Gemini 3 برگردانده می‌شود*).
  3. اجرای کد تابع (مسئولیت شما): «مدل» خود تابع را اجرا نمی‌کند. این مسئولیت برنامه شما است که پاسخ را پردازش کند و فراخوانی تابع را بررسی کند. اگر
    • بله: نام، آرگومان‌ها، و id تابع را استخراج کنید و تابع مربوطه را در برنامه‌تان اجرا کنید.
    • نه: مدل پاسخ نوشتاری مستقیمی به پیام‌واره ارائه کرده است (این جریان در مثال کمتر تأکید شده است اما نتیجه احتمالی است).
  4. پاسخ کاربرپسند ایجاد کن: اگر تابعی اجرا شد، نتیجه را ضبط کن و آن را به مدل برگردان و مطمئن شو که id منطبق را در نوبت بعدی مکالمه اضافه کنی. این مدل از نتیجه برای تولید پاسخ نهایی و کاربرپسندی که اطلاعات فراخوانی تابع را دربرمی‌گیرد استفاده خواهد کرد.

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

* همیشه شناسه‌های تابع را نگاشت کنید: Gemini 3 اکنون همیشه یک id منحصربه‌فرد با هر functionCall برمی‌گرداند. این id دقیق را در functionResponse خود بگنجانید تا مدل بتواند نتیجه شما را به‌درستی به درخواست اصلی برگرداند.

مرحله ۱: تعریف اعلان تابع

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

Python

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

JavaScript

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

رفتن

package main

import "google.golang.org/genai"

// Define a function declaration that the model can call to control smart lights
var setLightValuesDeclaration = &genai.FunctionDeclaration{
    Name:        "set_light_values",
    Description: "Sets the brightness and color temperature of a light.",
    Parameters: &genai.Schema{
        Type: genai.TypeObject,
        Properties: map[string]*genai.Schema{
            "brightness": {
                Type:        genai.TypeInteger,
                Description: "Light level from 0 to 100. Zero is off and 100 is full brightness",
            },
            "color_temp": {
                Type:        genai.TypeString,
                Enum:        []string{"daylight", "cool", "warm"},
                Description: "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
            },
        },
        Required: []string{"brightness", "color_temp"},
    },
}

// This is the actual function that would be called based on the model's suggestion
func setLightValues(brightness int, colorTemp string) map[string]any {
    return map[string]any{
        "brightness":       brightness,
        "colorTemperature": colorTemp,
    }
}

مرحله ۲: فراخوانی مدل با اظهارنامه‌های تابع

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

Python

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-3.8-flash",
    contents=contents,
    config=config,
)

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

JavaScript

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-3.8-flash',
  contents: contents,
  config: config
});

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

رفتن

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
    log.Fatal(err)
}

// Generation config with function declaration
config := &genai.GenerateContentConfig{
    Tools: []*genai.Tool{
        {FunctionDeclarations: []*genai.FunctionDeclaration{setLightValuesDeclaration}},
    },
}

// Define user prompt
contents := []*genai.Content{
    genai.NewContentFromText("Turn the lights down to a romantic level", genai.RoleUser),
}

// Send request with function declarations
response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, config)
if err != nil {
    log.Fatal(err)
}

fmt.Println(response.FunctionCalls()[0])

سپس مدل یک شیء functionCall را در یک طرح‌واره سازگار با OpenAPI برمی‌گرداند که نحوه فراخوانی یک یا چند تابع اعلام‌شده را برای پاسخ به سؤال کاربر مشخص می‌کند.

Python

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

JavaScript

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

رفتن

&{ID:8f2b1a3c Args:map[brightness:25 color_temp:warm] Name:set_light_values}

مرحله ۳: اجرای کد تابع set_light_values

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

Python

# 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}")

JavaScript

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

رفتن

// Extract tool call details
toolCall := response.FunctionCalls()[0]

var result map[string]any
if toolCall.Name == "set_light_values" {
    brightness := int(toolCall.Args["brightness"].(float64))
    colorTemp := toolCall.Args["color_temp"].(string)
    result = setLightValues(brightness, colorTemp)
    fmt.Printf("Function execution result: %v\n", result)
}

مرحله ۴: ایجاد پاسخ کاربرپسند با نتیجه تابع و فراخوانی مجدد مدل

درنهایت، نتیجه اجرای تابع را به مدل برگردانید تا بتواند این اطلاعات را در پاسخ نهایی خود به کاربر بگنجاند.

Python

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},
    id=tool_call.id,
)

# 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-3.8-flash",
    config=config,
    contents=contents,
)

print(final_response.text)

JavaScript

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

// 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-3.8-flash',
  contents: contents,
  config: config
});

console.log(final_response.text);

رفتن

// Create a function response part
functionResponsePart := &genai.Part{
    FunctionResponse: &genai.FunctionResponse{
        ID:       toolCall.ID,
        Name:     toolCall.Name,
        Response: result,
    },
}

// Append function call and result of the function execution to contents
contents = append(contents, response.Candidates[0].Content)
contents = append(contents, &genai.Content{
    Role:  genai.RoleUser,
    Parts: []*genai.Part{functionResponsePart},
})

// Get the final response from the model
finalResponse, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, config)
if err != nil {
    log.Fatal(err)
}

fmt.Println(finalResponse.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 (رشته): شرحی از هدف و قالب پارامتر. نمونه‌ها و محدودیت‌ها را ارائه دهید («شهر و ایالت، مثلاً، «San Francisco, CA» یا کد پستی مثلاً، «95616»»).
      • enum (آرایه، اختیاری): اگر مقادیر پارامتر از یک مجموعه ثابت هستند، از «enum» برای فهرست کردن مقادیر مجاز استفاده کنید، نه اینکه فقط آن‌ها را در شرح توضیح دهید. این کار دقت را بهبود می‌بخشد ("enum": ["daylight", "cool", "warm"]).
    • required (آرایه): آرایه‌ای از رشته‌ها که نام پارامترهای الزامی برای عملکرد تابع را فهرست می‌کند.

همچنین می‌توانید FunctionDeclarations را مستقیماً از توابع Python بااستفاده از types.FunctionDeclaration.from_callable(client=client, callable=your_function) بسازید.

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

مدل‌های سری Gemini 3 و 2.5 از فرایند «تفکر» داخلی برای استدلال کردن درخواست‌ها استفاده می‌کنند. این کار عملکرد فراخوانی تابع را به‌طور قابل‌توجهی بهبود می‌بخشد و به مدل اجازه می‌دهد تا بهتر تعیین کند چه زمانی تابع را فراخوانی کند و از کدام پارامترها استفاده کند. چون Gemini API بی‌وضعیت است، مدل‌ها از امضاهای فکری برای حفظ کردن بافت در مکالمه‌های چندنوبتی استفاده می‌کنند.

این بخش مدیریت پیشرفته امضاهای فکری را پوشش می‌دهد و فقط درصورتی لازم است که درخواست‌های API را به‌صورت دستی می‌سازید (مثلاً ازطریق REST) یا سابقه مکالمه را دستکاری می‌کنید.

اگر از کیت‌های توسعه نرم‌افزار هوش مصنوعی زایای Google (کتابخانه‌های رسمی ما) استفاده می‌کنید، نیازی به مدیریت این فرایند ندارید. کیت‌های توسعه نرم‌افزار به‌طور خودکار مراحل لازم را انجام می‌دهند، همان‌طور که در نمونه قبلی نشان داده شده است.

مدیریت کردن سابقه مکالمه به‌صورت دستی

اگر سابقه مکالمه را به‌صورت دستی اصلاح کنید، به‌جای ارسال پاسخ قبلی کامل، باید thought_signature گنجانده‌شده در نوبت مدل را به‌درستی مدیریت کنید.

برای اطمینان از حفظ بافت مدل، این قوانین را دنبال کنید:

  • همیشه thought_signature را در داخل Part اصلی‌اش به مدل برگردانید.
  • همیشه id دقیق را از function_call در function_response خود بگنجانید تا API بتواند نتیجه را به درخواست صحیح نگاشت کند.
  • ‫Part حاوی امضا را با فاقد امضا ادغام نکنید. این کار بافتار جایگاهی فکر را می‌شکند.
  • دو Parts را که هر دو حاوی امضا هستند ترکیب نکنید، زیرا رشته‌های امضا را نمی‌توان ادغام کرد.

امضاهای فکری Gemini 3

در Gemini 3، هر Part از پاسخ مدل ممکن است حاوی امضای فکری باشد. اگرچه به‌طورکلی توصیه می‌کنیم امضاها را از همه انواع Part برگردانید، برگرداندن امضاهای فکری برای فراخوانی تابع الزامی است. مگر اینکه سابقه مکالمه را به‌صورت دستی دستکاری کنید، Google GenAI SDK امضاهای فکری را به‌طور خودکار مدیریت خواهد کرد.

اگر سابقه مکالمه را به‌صورت دستی دستکاری می‌کنید، برای راهنمایی و جزئیات کامل درباره مدیریت امضاهای فکری برای Gemini 3، به صفحه امضاهای فکری مراجعه کنید.

درحال بررسی امضاهای فکری

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

Python

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"))

JavaScript

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

رفتن

// After receiving a response from a model with thinking enabled
// response, err := client.Models.GenerateContent(...)

// The signature is attached to the response part containing the function call
part := response.Candidates[0].Content.Parts[0]
if len(part.ThoughtSignature) > 0 {
    fmt.Println(string(part.ThoughtSignature))
}

در صفحه اندیشیدن، درباره محدودیت‌ها و کاربرد امضاهای فکری و به‌طور کلی درباره مدل‌های اندیشگر بیشتر بدانید.

فراخوانی موازی توابع

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

وقتی مدل چندین فراخوانی تابع را در یک نوبت آغاز می‌کند، لازم نیست اشیاء function_result را به همان ترتیبی که اشیاء function_call دریافت شده‌اند برگردانید. «میانای برنامه‌سازی کاربردی Gemini» هر نتیجه را بااستفاده از id از برونداد مدل به فراخوانی مربوطه آن برمی‌گرداند. این کار به شما امکان می‌دهد توابع خود را به‌صورت ناهمزمان اجرا کنید و نتایج را به‌محض تکمیل به فهرست خود اضافه کنید.

Python

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

JavaScript

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']
  }
};

رفتن

package main

import "google.golang.org/genai"

var powerDiscoBall = &genai.FunctionDeclaration{
    Name:        "power_disco_ball",
    Description: "Powers the spinning disco ball.",
    Parameters: &genai.Schema{
        Type: genai.TypeObject,
        Properties: map[string]*genai.Schema{
            "power": {
                Type:        genai.TypeBoolean,
                Description: "Whether to turn the disco ball on or off.",
            },
        },
        Required: []string{"power"},
    },
}

var startMusic = &genai.FunctionDeclaration{
    Name:        "start_music",
    Description: "Play some music matching the specified parameters.",
    Parameters: &genai.Schema{
        Type: genai.TypeObject,
        Properties: map[string]*genai.Schema{
            "energetic": {
                Type:        genai.TypeBoolean,
                Description: "Whether the music is energetic or not.",
            },
            "loud": {
                Type:        genai.TypeBoolean,
                Description: "Whether the music is loud or not.",
            },
        },
        Required: []string{"energetic", "loud"},
    },
}

var dimLights = &genai.FunctionDeclaration{
    Name:        "dim_lights",
    Description: "Dim the lights.",
    Parameters: &genai.Schema{
        Type: genai.TypeObject,
        Properties: map[string]*genai.Schema{
            "brightness": {
                Type:        genai.TypeNumber,
                Description: "The brightness of the lights, 0.0 is off, 1.0 is full.",
            },
        },
        Required: []string{"brightness"},
    },
}

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

Python

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-3.8-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}) - ID: {fn.id}")

JavaScript

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-3.8-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}) - ID: ${fn.id}`);
}

رفتن

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
    log.Fatal(err)
}

houseTools := []*genai.Tool{
    {FunctionDeclarations: []*genai.FunctionDeclaration{powerDiscoBall, startMusic, dimLights}},
}

config := &genai.GenerateContentConfig{
    Tools: houseTools,
    // Force the model to call 'any' function, instead of chatting.
    ToolConfig: &genai.ToolConfig{
        FunctionCallingConfig: &genai.FunctionCallingConfig{
            Mode: genai.FunctionCallingConfigModeAny,
        },
    },
}

response, err := client.Models.GenerateContent(
    ctx,
    "gemini-3.8-flash",
    genai.Text("Turn this place into a party!"),
    config,
)
if err != nil {
    log.Fatal(err)
}

// Print out each of the function calls requested from this single call
fmt.Println("Example 1: Forced function calling")
for _, fn := range response.FunctionCalls() {
    fmt.Printf("%s(%v) - ID: %s\n", fn.Name, fn.Args, fn.ID)
}

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

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

Python

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-3.8-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!

فراخوانی تابع ترکیبی

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

مثال زیر نشان می‌دهد که چگونه می‌توان فراخوانی تابع ترکیبی را بااستفاده از کیت توسعه نرم‌افزار Python و فراخوانی خودکار تابع پیاده‌سازی کرد.

Python

این مثال از ویژگی فراخوانی تابع خودکار google-genai Python 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-3.8-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)

برونداد موردانتظار

وقتی کد را اجرا می‌کنید، کیت توسعه نرم‌افزار را درحال هماهنگ‌سازی تماس‌های تابع می‌بینید. ابتدا مدل با 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.

JavaScript

این مثال نشان می‌دهد که چگونه از کیت توسعه نرم‌افزار JavaScript/TypeScript برای انجام فراخوانی تابع ترکیبی بااستفاده از حلقه اجرای دستی استفاده کنید.

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-3.8-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,
      },
      id: functionCall.id,
    };

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

برونداد موردانتظار

وقتی کد را اجرا می‌کنید، خواهید دید که کیت توسعه نرم‌افزار فراخوانی‌های تابع را سازمان‌دهی می‌کند. ابتدا مدل با 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.

رفتن

این مثال نشان می‌دهد که چگونه از Go SDK برای انجام فراخوانی تابع ترکیبی بااستفاده از حلقه اجرای دستی استفاده کنید.

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func getWeatherForecast(location string) map[string]any {
    fmt.Printf("Tool Call: get_weather_forecast(location=%s)\n", location)
    fmt.Println("Tool Response: map[temperature:25 unit:celsius]")
    return map[string]any{"temperature": 25, "unit": "celsius"}
}

func setThermostatTemperature(temperature float64) map[string]any {
    fmt.Printf("Tool Call: set_thermostat_temperature(temperature=%v)\n", temperature)
    fmt.Println("Tool Response: map[status:success]")
    return map[string]any{"status": "success"}
}

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    tools := []*genai.Tool{
        {
            FunctionDeclarations: []*genai.FunctionDeclaration{
                {
                    Name:        "get_weather_forecast",
                    Description: "Gets the current weather temperature for a given location.",
                    Parameters: &genai.Schema{
                        Type: genai.TypeObject,
                        Properties: map[string]*genai.Schema{
                            "location": {Type: genai.TypeString},
                        },
                        Required: []string{"location"},
                    },
                },
                {
                    Name:        "set_thermostat_temperature",
                    Description: "Sets the thermostat to a desired temperature.",
                    Parameters: &genai.Schema{
                        Type: genai.TypeObject,
                        Properties: map[string]*genai.Schema{
                            "temperature": {Type: genai.TypeNumber},
                        },
                        Required: []string{"temperature"},
                    },
                },
            },
        },
    }

    config := &genai.GenerateContentConfig{Tools: tools}

    contents := []*genai.Content{
        genai.NewContentFromText("If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.", genai.RoleUser),
    }

    for {
        result, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, config)
        if err != nil {
            log.Fatal(err)
        }

        if len(result.FunctionCalls()) > 0 {
            functionCall := result.FunctionCalls()[0]
            var toolResponse map[string]any

            switch functionCall.Name {
            case "get_weather_forecast":
                location := functionCall.Args["location"].(string)
                toolResponse = getWeatherForecast(location)
            case "set_thermostat_temperature":
                temperature := functionCall.Args["temperature"].(float64)
                toolResponse = setThermostatTemperature(temperature)
            default:
                log.Fatalf("Unknown function call: %s", functionCall.Name)
            }

            contents = append(contents, result.Candidates[0].Content)
            contents = append(contents, &genai.Content{
                Role: genai.RoleUser,
                Parts: []*genai.Part{
                    {
                        FunctionResponse: &genai.FunctionResponse{
                            ID:       functionCall.ID,
                            Name:     functionCall.Name,
                            Response: toolResponse,
                        },
                    },
                },
            })
        } else {
            fmt.Println(result.Text())
            break
        }
    }
}

برونداد موردانتظار

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

فراخوانی تابع ترکیبی یکی از ویژگی‌های بومی Live API است. این یعنی Live API می‌تواند فراخوانی تابع را مشابه «کیت توسعه نرم‌افزار Python» مدیریت کند.

Python

# 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")

JavaScript

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

حالت‌های فراخوانی تابع

‫Gemini API به شما امکان می‌دهد نحوه استفاده مدل از ابزارهای ارائه‌شده (اعلام‌های تابع) را کنترل کنید. به‌طور دقیق، می‌توانید حالت را در function_calling_config تنظیم کنید.

  • ‫VALIDATED: حالت پیش‌فرض برای ترکیب ابزار (وقتی ابزارهای داخلی یا بروندادهای ساختاریافته نیز فعال باشند). این مدل محدود به پیش‌بینی یا فراخوانی تابع یا زبان طبیعی است و پایبندی به طرحواره تابع را تضمین می‌کند. اگر allowed_function_names ارائه نشود، مدل از بین همه اعلام‌های تابع موجود انتخاب می‌کند. اگر allowed_function_names ارائه شود، مدل از مجموعه توابع مجاز انتخاب می‌کند. این حالت فراخوانی‌های تابع بدشکل را کاهش می‌دهد (درمقایسه با حالت AUTO).
  • AUTO: حالت پیش‌فرض وقتی فقط ابزار function_declarations فعال باشد. مدل براساس پیام‌واره و زمینه تصمیم می‌گیرد که پاسخ زبان طبیعی تولید کند یا فراخوانی تابع پیشنهاد دهد.
  • ANY: مدل محدود شده است تا همیشه فراخوانی تابع را پیش‌بینی کند و از رعایت طرح‌واره تابع اطمینان حاصل کند. اگر allowed_function_names مشخص نشده باشد، مدل می‌تواند از میان هریک از بیانیه‌های تابع ارائه‌شده انتخاب کند. اگر allowed_function_names به‌صورت فهرست ارائه شود، مدل فقط می‌تواند از میان کارکردهای موجود در آن فهرست انتخاب کند. وقتی برای هر پیام‌واره به پاسخ فراخوانی تابع نیاز دارید (درصورت وجود)، از این حالت استفاده کنید.
  • ‫NONE: مدل از برقراری تماس‌های عملکرد منع شده است. این معادل ارسال درخواست بدون هیچ‌گونه اظهار عملکرد است. از این برای غیرفعال کردن موقت فراخوانی تابع بدون برداشتن تعاریف ابزارتان استفاده کنید.

Python

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

JavaScript

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

رفتن

// Configure function calling mode
toolConfig := &genai.ToolConfig{
    FunctionCallingConfig: &genai.FunctionCallingConfig{
        Mode:                 genai.FunctionCallingConfigModeAny,
        AllowedFunctionNames: []string{"get_current_temperature"},
    },
}

// Create the generation config
config := &genai.GenerateContentConfig{
    Tools:      tools, // not defined here.
    ToolConfig: toolConfig,
}

فراخوانی تابع خودکار (فقط Python)

هنگام استفاده از Python SDK، می‌توانید توابع Python را مستقیماً به‌عنوان ابزار ارائه دهید. کیت توسعه نرم‌افزار این توابع را به اعلامیه‌ها تبدیل می‌کند، اجرای فراخوانی تابع را مدیریت می‌کند، و چرخه پاسخ را برای شما اداره می‌کند. تابع خود را با نکات نوع و رشته مستندات تعریف کنید. برای نتایج بهینه، توصیه می‌شود از رشته‌های مستندسازی به سبک Google استفاده کنید. سپس «کیت توسعه نرم‌افزار» به‌طور خودکار:

  1. پاسخ‌های فراخوانی تابع را از مدل شناسایی کنید.
  2. تابع Python مربوطه را در کدتان فراخوانی کنید.
  3. پاسخ تابع را به مدل برگردانید.
  4. پاسخ نوشتاری نهایی مدل را برمی‌گرداند.

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

Python

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-3.8-flash",
    contents="What's the temperature in Boston?",
    config=config,
)

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

می‌توانید فراخوانی خودکار تابع را با این موارد غیرفعال کنید:

Python

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

اظهارنامه طرحواره تابع خودکار

این «میانای برنامه‌سازی کاربردی» می‌تواند هریک از انواع زیر را توصیف کند. انواع Pydantic مجاز هستند، به‌شرطی که فیلدهای تعریف‌شده در آن‌ها نیز از انواع مجاز تشکیل شده باشند. انواع دیکشنری (مثل dict[str: int]) در اینجا به‌خوبی پشتیبانی نمی‌شوند، از آن‌ها استفاده نکنید.

Python

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

برای دیدن اینکه طرحواره استنباط‌شده چگونه به‌نظر می‌رسد، می‌توانید آن را بااستفاده از from_callable تبدیل کنید:

Python

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())

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

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

مدل‌های Gemini 3 می‌توانند ابزارهای داخلی را با فراخوانی تابع به‌صورت آماده ترکیب کنند، که این امر به‌لطف ویژگی گردش بافت ابزار امکان‌پذیر شده است. برای کسب اطلاعات بیشتر، صفحه مربوط به ترکیب ابزارهای داخلی و فراخوانی تابع را بخوانید.

Python

from google import genai
from google.genai import types

client = genai.Client()

getWeather = {
    "name": "getWeather",
    "description": "Gets the weather for a requested city.",
    "parameters": {
        "type": "object",
        "properties": {
            "city": {
                "type": "string",
                "description": "The city and state, e.g. Utqiaġvik, Alaska",
            },
        },
        "required": ["city"],
    },
}

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="What is the northernmost city in the United States? What's the weather like there today?",
    config=types.GenerateContentConfig(
      tools=[
        types.Tool(
          google_search=types.ToolGoogleSearch(),  # Built-in tool
          function_declarations=[getWeather]       # Custom tool
        ),
      ],
      include_server_side_tool_invocations=True
    ),
)

history = [
    types.Content(
        role="user",
        parts=[types.Part(text="What is the northernmost city in the United States? What's the weather like there today?")]
    ),
    response.candidates[0].content,
    types.Content(
        role="user",
        parts=[types.Part(
            function_response=types.FunctionResponse(
                name="getWeather",
                response={"response": "Very cold. 22 degrees Fahrenheit."},
                id=response.candidates[0].content.parts[2].function_call.id
            )
        )]
    )
]

response_2 = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=history,
    config=types.GenerateContentConfig(
      tools=[
        types.Tool(
          google_search=types.ToolGoogleSearch(),
          function_declarations=[getWeather]
        ),
      ],
      include_server_side_tool_invocations=True
    ),
)

جاوا اسکریپت

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

const client = new GoogleGenAI({});

const getWeather = {
    name: "getWeather",
    description: "Get the weather in a given location",
    parameters: {
        type: "OBJECT",
        properties: {
            location: {
                type: "STRING",
                description: "The city and state, e.g. San Francisco, CA"
            }
        },
        required: ["location"]
    }
};

async function run() {
    const tools = [
      { googleSearch: {} },
      { functionDeclarations: [getWeather] }
    ];
    const toolConfig = { includeServerSideToolInvocations: true };

    const response1 = await client.models.generateContent({
        model: "gemini-3.8-flash",
        contents: [{role: "user", parts: [{text: "What is the northernmost city in the United States? What's the weather like there today?"}]}],
        config: {
            tools: tools,
            toolConfig: toolConfig,
        },
    });

    const functionCallId = response1.candidates[0].content.parts.find(p => p.functionCall)?.functionCall?.id;

    const history = [
        {
            role: "user",
            parts:[{text: "What is the northernmost city in the United States? What's the weather like there today?"}]
        },
        response1.candidates[0].content,
        {
            role: "user",
            parts: [{
                functionResponse: {
                    name: "getWeather",
                    response: {response: "Very cold. 22 degrees Fahrenheit."},
                    id: functionCallId
                }
            }]
        }
    ];

    const response2 = await client.models.generateContent({
        model: "gemini-3.8-flash",
        contents: history,
        config: {
            tools: tools,
            toolConfig: toolConfig,
        },
    });
}

run();

رفتن

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    getWeather := &genai.FunctionDeclaration{
        Name:        "getWeather",
        Description: "Get the weather in a given location",
        Parameters: &genai.Schema{
            Type: genai.TypeObject,
            Properties: map[string]*genai.Schema{
                "location": {
                    Type:        genai.TypeString,
                    Description: "The city and state, e.g. San Francisco, CA",
                },
            },
            Required: []string{"location"},
        },
    }

    tools := []*genai.Tool{
        {GoogleSearch: &genai.GoogleSearch{}},
        {FunctionDeclarations: []*genai.FunctionDeclaration{getWeather}},
    }

    config := &genai.GenerateContentConfig{
        Tools: tools,
    }

    prompt := "What is the northernmost city in the United States? What's the weather like there today?"
    response1, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", genai.Text(prompt), config)
    if err != nil {
        log.Fatal(err)
    }

    toolCall := response1.FunctionCalls()[0]

    history := []*genai.Content{
        genai.NewContentFromText(prompt, genai.RoleUser),
        response1.Candidates[0].Content,
        {
            Role: genai.RoleUser,
            Parts: []*genai.Part{
                {
                    FunctionResponse: &genai.FunctionResponse{
                        ID:       toolCall.ID,
                        Name:     toolCall.Name,
                        Response: map[string]any{"response": "Very cold. 22 degrees Fahrenheit."},
                    },
                },
            },
        },
    }

    response2, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", history, config)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(response2.Text())
}

برای مدل‌های قبل‌از سری Gemini 3، از Live API استفاده کنید.

پاسخ‌های عملکرد چندحالته

برای مدل‌های سری Gemini 3، می‌توانید محتوای چندحالتی را در بخش‌های پاسخ تابع که به مدل ارسال می‌کنید، بگنجانید. مدل می‌تواند این محتوای چندحالتی را در نوبت بعدی خود پردازش کند تا پاسخ آگاهانه‌تری تولید کند. انواع MIME زیر برای محتوای چندوجهی در پاسخ‌های تابع پشتیبانی می‌شوند:

  • تصاویر: image/png، image/jpeg، image/webp
  • سندها: application/pdf، text/plain

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

همچنین می‌توانید بااستفاده از قالب مرجع JSON {"$ref": "<displayName>"}، از داخل فیلد ساختاریافته response بخش functionResponse به بخش چندوجهی ارجاع دهید. مدل هنگام پردازش پاسخ، مرجع را با محتوای چندوجهی جایگزین می‌کند. هر displayName فقط یک‌بار می‌تواند در فیلد response ساختاری مورد ارجاع قرار گیرد.

مثال زیر پیامی را نشان می‌دهد که حاوی functionResponse برای تابعی به نام get_image و بخشی تودرتو حاوی داده‌های تصویر با displayName: "instrument.jpg" است. فیلد response در functionResponse به این بخش تصویر ارجاع می‌دهد:

Python

from google import genai
from google.genai import types

import requests

client = genai.Client()

# This is a manual, two turn multimodal function calling workflow:

# 1. Define the function tool
get_image_declaration = types.FunctionDeclaration(
  name="get_image",
  description="Retrieves the image file reference for a specific order item.",
  parameters={
      "type": "object",
      "properties": {
          "item_name": {
              "type": "string",
              "description": "The name or description of the item ordered (e.g., 'instrument')."
          }
      },
      "required": ["item_name"],
  },
)
tool_config = types.Tool(function_declarations=[get_image_declaration])

# 2. Send a message that triggers the tool
prompt = "Show me the instrument I ordered last month."
response_1 = client.models.generate_content(
  model="gemini-3.8-flash",
  contents=[prompt],
  config=types.GenerateContentConfig(
      tools=[tool_config],
  )
)

# 3. Handle the function call
function_call = response_1.function_calls[0]
requested_item = function_call.args["item_name"]
print(f"Model wants to call: {function_call.name}")

# Execute your tool (e.g., call an API)
# (This is a mock response for the example)
print(f"Calling external tool for: {requested_item}")

function_response_data = {
  "image_ref": {"$ref": "instrument.jpg"},
}
image_path = "https://goo.gle/instrument-img"
image_bytes = requests.get(image_path).content
function_response_multimodal_data = types.FunctionResponsePart(
  inline_data=types.FunctionResponseBlob(
    mime_type="image/jpeg",
    display_name="instrument.jpg",
    data=image_bytes,
  )
)

# 4. Send the tool's result back
# Append this turn's messages to history for a final response.
history = [
  types.Content(role="user", parts=[types.Part(text=prompt)]),
  response_1.candidates[0].content,
  types.Content(
    role="user",
    parts=[
        types.Part.from_function_response(
          id=function_call.id,
          name=function_call.name,
          response=function_response_data,
          parts=[function_response_multimodal_data]
        )
    ],
  )
]

response_2 = client.models.generate_content(
  model="gemini-3.8-flash",
  contents=history,
  config=types.GenerateContentConfig(
      tools=[tool_config],
      thinking_config=types.ThinkingConfig(include_thoughts=True)
  ),
)

print(f"\nFinal model response: {response_2.text}")

JavaScript

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

const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// This is a manual, two turn multimodal function calling workflow:
// 1. Define the function tool
const getImageDeclaration = {
  name: 'get_image',
  description: 'Retrieves the image file reference for a specific order item.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      item_name: {
        type: Type.STRING,
        description: "The name or description of the item ordered (e.g., 'instrument').",
      },
    },
    required: ['item_name'],
  },
};

const toolConfig = {
  functionDeclarations: [getImageDeclaration],
};

// 2. Send a message that triggers the tool
const prompt = 'Show me the instrument I ordered last month.';
const response1 = await client.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: prompt,
  config: {
    tools: [toolConfig],
  },
});

// 3. Handle the function call
const functionCall = response1.functionCalls[0];
const requestedItem = functionCall.args.item_name;
console.log(`Model wants to call: ${functionCall.name}`);

// Execute your tool (e.g., call an API)
// (This is a mock response for the example)
console.log(`Calling external tool for: ${requestedItem}`);

const functionResponseData = {
  image_ref: { $ref: 'instrument.jpg' },
};

const imageUrl = "https://goo.gle/instrument-img";
const response = await fetch(imageUrl);
const imageArrayBuffer = await response.arrayBuffer();
const base64ImageData = Buffer.from(imageArrayBuffer).toString('base64');

const functionResponseMultimodalData = {
  inlineData: {
    mimeType: 'image/jpeg',
    displayName: 'instrument.jpg',
    data: base64ImageData,
  },
};

// 4. Send the tool's result back
// Append this turn's messages to history for a final response.
const history = [
  { role: 'user', parts: [{ text: prompt }] },
  response1.candidates[0].content,
  {
    role: 'user',
    parts: [
      {
        functionResponse: {
          id: functionCall.id,
          name: functionCall.name,
          response: functionResponseData,
          parts: [functionResponseMultimodalData]
        },
      },
    ],
  },
];

const response2 = await client.models.generateContent({
  model: 'gemini-3.8-flash',
  contents: history,
  config: {
    tools: [toolConfig],
    thinkingConfig: { includeThoughts: true },
  },
});

console.log(`\nFinal model response: ${response2.text}`);

رفتن

package main

import (
    "context"
    "fmt"
    "io"
    "log"
    "net/http"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    // 1. Define the function tool
    getImageDeclaration := &genai.FunctionDeclaration{
        Name:        "get_image",
        Description: "Retrieves the image file reference for a specific order item.",
        Parameters: &genai.Schema{
            Type: genai.TypeObject,
            Properties: map[string]*genai.Schema{
                "item_name": {
                    Type:        genai.TypeString,
                    Description: "The name or description of the item ordered (e.g., 'instrument').",
                },
            },
            Required: []string{"item_name"},
        },
    }

    tools := []*genai.Tool{
        {FunctionDeclarations: []*genai.FunctionDeclaration{getImageDeclaration}},
    }

    // 2. Send a message that triggers the tool
    prompt := "Show me the instrument I ordered last month."
    response1, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", genai.Text(prompt), &genai.GenerateContentConfig{
        Tools: tools,
    })
    if err != nil {
        log.Fatal(err)
    }

    // 3. Handle the function call
    functionCall := response1.FunctionCalls()[0]
    requestedItem := functionCall.Args["item_name"]
    fmt.Printf("Model wants to call: %s\n", functionCall.Name)
    fmt.Printf("Calling external tool for: %v\n", requestedItem)

    resp, err := http.Get("https://goo.gle/instrument-img")
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    imageBytes, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    functionResponseData := map[string]any{
        "image_ref": map[string]any{"$ref": "instrument.jpg"},
    }

    functionResponseMultimodalData := &genai.FunctionResponsePart{
        InlineData: &genai.FunctionResponseBlob{
            MIMEType:    "image/jpeg",
            DisplayName: "instrument.jpg",
            Data:        imageBytes,
        },
    }

    // 4. Send the tool's result back
    history := []*genai.Content{
        genai.NewContentFromText(prompt, genai.RoleUser),
        response1.Candidates[0].Content,
        {
            Role: genai.RoleUser,
            Parts: []*genai.Part{
                {
                    FunctionResponse: &genai.FunctionResponse{
                        ID:       functionCall.ID,
                        Name:     functionCall.Name,
                        Response: functionResponseData,
                        Parts:    []*genai.FunctionResponsePart{functionResponseMultimodalData},
                    },
                },
            },
        },
    }

    response2, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", history, &genai.GenerateContentConfig{
        Tools: tools,
        ThinkingConfig: &genai.ThinkingConfig{
            IncludeThoughts: true,
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("\nFinal model response: %s\n", response2.Text())
}

REST

IMG_URL="https://goo.gle/instrument-img"

MIME_TYPE=$(curl -sIL "$IMG_URL" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\r$//' | head -n 1)
if [[ -z "$MIME_TYPE" || ! "$MIME_TYPE" == image/* ]]; then
  MIME_TYPE="image/jpeg"
fi

# Check for macOS
if [[ "$(uname)" == "Darwin" ]]; then
  IMAGE_B64=$(curl -sL "$IMG_URL" | base64 -b 0)
elif [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  IMAGE_B64=$(curl -sL "$IMG_URL" | base64)
else
  IMAGE_B64=$(curl -sL "$IMG_URL" | base64 -w0)
fi

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      ...,
      {
        "role": "user",
        "parts": [
        {
            "functionResponse": {
              "name": "get_image",
              "id": "UNIQUE_CALL_ID_HERE",
              "response": {
                "image_ref": {
                  "$ref": "instrument.jpg"
                }
              },
              "parts": [
                {
                  "inlineData": {
                    "displayName": "instrument.jpg",
                    "mimeType":"'"$MIME_TYPE"'",
                    "data": "'"$IMAGE_B64"'"
                  }
                }
              ]
            }
          }
        ]
      }
    ]
  }'

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

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

پروتکل زمینه‌ای مدل (MCP)

پروتکل بافتار مدل (MCP) یک استاندارد باز برای متصل کردن برنامه‌های هوش مصنوعی با ابزارها و داده‌های خارجی است. ‫MCP یک پروتکل مشترک برای مدل‌ها فراهم می‌کند تا به بافتار، مانند توابع (ابزارها)، منابع داده (منابع)، یا پیام‌واره‌های ازپیش‌تعریف‌شده دسترسی پیدا کنند.

کیت‌های توسعه نرم‌افزار Gemini از MCP پشتیبانی داخلی دارند که کد متن استاندارد را کاهش می‌دهد و فراخوانی خودکار ابزار را برای ابزارهای MCP ارائه می‌دهد. وقتی مدل یک فراخوانی ابزار MCP تولید می‌کند، SDK مشتری Python و JavaScript می‌تواند به‌طور خودکار ابزار MCP را اجرا کند و پاسخ را در یک درخواست بعدی به مدل ارسال کند، و این حلقه را تا زمانی که دیگر فراخوانی ابزاری توسط مدل انجام نشود ادامه دهد.

در اینجا می‌توانید نمونه‌ای از نحوه استفاده از سرور MCP محلی با Gemini و mcp SDK را ببینید.

Python

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

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-3.8-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())

JavaScript

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

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-3.8-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

پشتیبانی داخلی MCP یک ویژگی آزمایشی در کیت‌های توسعه نرم‌افزار ما است و محدودیت‌های زیر را دارد:

  • فقط از ابزارها پشتیبانی می‌شود، نه منابع یا پیام‌واره‌ها
  • این ویژگی برای کیت توسعه نرم‌افزار Python و JavaScript/TypeScript دردسترس است.
  • ممکن است در نسخه‌های پخش آتی تغییرات اساسی رخ دهد.

اگر این موارد آنچه را می‌سازید محدود می‌کند، ادغام دستی سرورهای MCP همیشه یک گزینه است.

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

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

مدل فراخوانی تابع فراخوانی موازی تابع فراخوانی تابع ترکیبی
Gemini 4 Argon ✔️ ✔️ ✔️
‫Gemini 3.8 Flash ✔️ ✔️ ✔️
Gemini 3.6 Flash ✔️ ✔️ ✔️
Gemini 3.5 Flash-Lite ✔️ ✔️ ✔️
پیش‌نمایش Gemini 3.1 Pro ✔️ ✔️ ✔️
Gemini 3.1 Flash-Lite ✔️ ✔️ ✔️
Gemini 2.5 Pro ✔️ ✔️ ✔️
Gemini 2.5 Flash ✔️ ✔️ ✔️
Gemini 2.5 Flash-Lite ✔️ ✔️ ✔️

روال‌های مطلوب

  • شرح عملکرد و پارامتر: در شرح‌هایتان بسیار واضح و دقیق باشید. مدل برای انتخاب تابع صحیح و ارائه آرگومان‌های مناسب به این موارد متکی است.
  • نام‌گذاری: از نام‌های تابع توصیفی (بدون فاصله، نقطه، یا خط تیره) استفاده کنید.
  • تایپ قوی: از انواع خاص (عدد صحیح، رشته، enum) برای پارامترها استفاده کنید تا خطاها کاهش یابد. اگر پارامتر مجموعه محدودی از مقادیر معتبر دارد، از enum استفاده کنید.
  • انتخاب ابزار: اگرچه مدل می‌تواند از تعداد دلخواهی ابزار استفاده کند، ارائه تعداد زیادی ابزار می‌تواند خطر انتخاب ابزار نادرست یا نامناسب را افزایش دهد. برای دریافت بهترین نتیجه، سعی کنید فقط ابزارهای مربوط به زمینه یا تکلیف را ارائه دهید، و در حالت ایده‌آل، مجموعه فعال را حداکثر در حد ۱۰ تا ۲۰ ابزار نگه دارید. اگر تعداد کل ابزارهای شما زیاد است، انتخاب ابزار پویا را براساس بافت مکالمه درنظر بگیرید.
  • مهندسی پیام‌واره:
    • بافت ارائه دهید: نقش مدل را به آن بگویید (برای مثال، «تو یک دستیار آب‌وهوای مفید هستی»).
    • دستورالعمل بدهید: مشخص کنید چگونه و چه زمانی از توابع استفاده شود (برای نمونه، «تاریخ‌ها را حدس نزن؛ همیشه از تاریخ آینده برای پیش‌بینی‌ها استفاده کن.»).
    • تشویق به شفاف‌سازی: به مدل دستور دهید درصورت نیاز سؤالات شفاف‌سازی بپرسد.
    • برای راهبردهای بیشتر درباره طراحی این پیام‌واره‌ها، گردش‌کارهای عاملی را ببینید. در اینجا نمونه‌ای از دستورالعمل سیستم آزمایش‌شده آورده شده است.
  • دما: از دمای پایین (مثلاً ۰) برای فراخوانی‌های تابع قطعی‌تر و قابل‌اعتمادتر استفاده کنید.

  • اعتبارسنجی: اگر فراخوانی تابع پیامدهای مهمی دارد (مثلاً ثبت سفارش)، قبل‌از اجرای فراخوانی، آن را با کاربر اعتبارسنجی کنید.

  • بررسی دلیل پایان: همیشه finishReason را در پاسخ مدل بررسی کنید تا مواردی را که مدل نتوانسته است یک فراخوانی تابع معتبر تولید کند مدیریت کنید.

  • مدیریت خطا: مدیریت خطای قوی را در توابع خود پیاده‌سازی کنید تا ورودی‌های غیرمنتظره یا خرابی‌های میانای برنامه‌سازی کاربردی را به‌خوبی مدیریت کنید. پیام‌های خطای آموزنده برگردانید تا مدل بتواند از آن‌ها برای تولید پاسخ‌های مفید برای کاربر استفاده کند.

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

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

  • ترکیبی از bash و ابزارهای سفارشی برای کسانی که با ترکیبی از bash و ابزارهای سفارشی می‌سازند، Gemini 3.1 Pro Preview با نقطه پایانی جداگانه‌ای که ازطریق API به‌نام gemini-3.1-pro-preview-customtools دردسترس است ارائه می‌شود.

راه‌حل‌های جایگزین برای الزامات نوشتاری پیش‌ابزار

مشکل: اگر پیام‌واره شما از مدل بخواهد نوشتار ساختاریافته (XML،‏ YAML،‏ JSON، و غیره) تولید کند (برای نمونه، <UPDATE>...</UPDATE>) بلافاصله قبل‌از فراخوانی ابزار، فراخوانی ابزار ممکن است گاهی با Malformed_Function_Call ناموفق باشد.

راه‌حل‌ها: راه‌حل‌های زیر این مشکل را برطرف می‌کند:

  • ترجیحاً: به مدل دستور دهید تا یادداشت‌های پیش‌ابزار خود را به‌جای نوشتار خام، در یک فراخوانی تابع update() اختصاصی قرار دهد (جزئیات در زیر).
  • به مدل دستور دهید یادداشت‌ها را به‌جای نوشتار ساختاریافته، به‌عنوان سرصفحه‌های Markdown (# UPDATE، ## PLAN) بنویسد.
  • مدل را ملزم نکنید که قبل‌از فراخوانی ابزار، نوشتار برونداد کند.

راهکار ترجیحی: پیچیدن یادداشت‌های کاری در فراخوانی تابع اختصاصی

به‌جای دستورالعمل اصلی:

Before calling a tool, in every response you MUST first output a single `<UPDATE>` part as specified, don't skip this part or any of required sub-tags within `<UPDATE>`.

از این دستورالعمل به‌روزشده استفاده کن:

Before calling any other tool, in every response you MUST first call `update` with all required parameters (previous_step, plan, next_step, external).

و همه ارجاع‌ها به قالب XML قدیمی <UPDATE> را در درخواست مشتری به‌روز کنید. سپس اعلان تابع مربوطه را برای تابع به‌روزرسانی اضافه کنید:

{
  "name": "update",
  "description": "Update working notes (previous step analysis, plan, next step, external note).",
  "parameters": {
    "type": "OBJECT",
    "properties": {
      "previous_step": {
        "type": "STRING",
        "description": "Key findings and outcomes since the previous step."
      },
      "plan": {
        "type": "STRING",
        "description": "The current status of the plan."
      },
      "next_step": {
        "type": "STRING",
        "description": "Brief explanation of the immediate next action according to the plan."
      },
      "external": {
        "type": "STRING",
        "description": "A short, plain-language note shown to the User about what you are ABOUT TO DO next."
      }
    },
    "required": [
      "previous_step",
      "plan",
      "next_step",
      "external"
    ]
  }
}

سپس مدل در همان مرحله دو تماس برقرار می‌کند: تماس update() که جایگزین XML ساختاریافته می‌شود، و تماس تابع واقعی که می‌خواهد برقرار کند.

یادداشت‌ها و محدودیت‌ها

  • موقعیت‌یابی بخش‌های فراخوانی تابع: هنگام استفاده از بیانیه‌های تابع سفارشی همراه با ابزارهای داخلی (مثل «جستجوی Google»)، مدل ممکن است ترکیبی از بخش‌های functionCall، toolCall، و toolResponse را در یک نوبت برگرداند. به‌همین دلیل، فرض نکنید که functionCall همیشه آخرین مورد در آرایه بخش‌ها خواهد بود. اگر پاسخ JSON را به‌صورت دستی تجزیه می‌کنید، همیشه به‌جای تکیه بر موقعیت، ازطریق آرایه بخش‌ها تکرار کنید.
  • فقط زیرمجموعه‌ای از طرح‌واره OpenAPI پشتیبانی می‌شود.
  • برای حالت ANY، ممکن است API طرحواره‌های بسیار بزرگ یا عمیقاً تودرتو را رد کند. اگر با خطا مواجه شدید، با کوتاه کردن نام‌های دارایی، کاهش تو در تو بودن، یا محدود کردن تعداد بیانیه‌های تابع، طرحواره‌های پارامتر تابع و پاسخ را ساده کنید.
  • انواع پارامترهای پشتیبانی‌شده در Python محدود است.
  • فراخوانی خودکار تابع فقط یکی از ویژگی‌های Python SDK است.