الجمع بين الأدوات المضمّنة واستدعاء الدوال

يتيح Gemini الجمع بين الأدوات المضمّنة، مثل google_search، وميزة استدعاء الدوال (المعروفة أيضًا باسم الأدوات المخصّصة) في تفاعل واحد من خلال الاحتفاظ بسجلّ سياق طلبات الأدوات وعرضه. تسمح مجموعات الأدوات المضمّنة والمخصّصة بسير عمل معقّد ومستقل، حيث يمكن للنموذج، على سبيل المثال، أن يستند إلى بيانات الويب في الوقت الفعلي قبل استدعاء منطق نشاطك التجاري المحدّد.

في ما يلي مثال يوضّح كيفية تفعيل مجموعات الأدوات المضمّنة والمخصّصة باستخدام google_search ودالة مخصّصة getWeather:

Python

# This will only work for SDK newer than 2.0.0
from google import genai

client = genai.Client()

getWeather = {
    "type": "function",
    "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"],
    },
}

# The Interactions API manages context automatically across tool calls.
# The model will first use Google Search, then call getWeather.
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="What is the northernmost city in the United States? What's the weather like there today?",
    tools=[
        {"type": "google_search"},
        getWeather,
    ],
)

# Process steps: the interaction contains search results and a function call
for step in interaction.steps:
    if step.type == "function_call":
        print(f"Function call: {step.name} with args: {step.arguments}")
        # In a real application, you would execute the function here
        # and provide the result back to the model.

JavaScript

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const getWeather = {
    type: "function",
    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"]
    }
};

// The Interactions API manages context automatically across tool calls.
// The model will first use Google Search, then call getWeather.
const interaction = await client.interactions.create({
    model: "gemini-3.8-flash",
    input: "What is the northernmost city in the United States? What's the weather like there today?",
    tools: [
        { type: "google_search" },
        getWeather,
    ],
});

// Process steps: the interaction contains search results and a function call
for (const step of interaction.steps) {
    if (step.type === "function_call") {
        console.log(`Function call: ${step.name} with args: ${JSON.stringify(step.arguments)}`);
        // In a real application, you would execute the function here
        // and provide the result back to the model.
    }
}

جافا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Function;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

Client client = new Client();

Map<String, Object> parameters = new HashMap<>();
parameters.put("type", "object");

Function customFunc =
    Function.builder()
        .name("get_user_location")
        .description("Retrieves user current location.")
        .parameters(parameters)
        .build();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("What is the weather like where I am right now?"))
        .tools(Arrays.asList(customFunc, new GoogleSearch()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

انتقال

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    customFunc := interactions.NewTool(interactions.Function{
        Name:        genai.Ptr("get_user_location"),
        Description: genai.Ptr("Retrieves user current location."),
        Parameters: map[string]any{
            "type": "object",
        },
    })

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3.8-flash"),
            Input: interactions.NewInteractionsInput("What is the weather like where I am right now?"),
            Tools: []interactions.Tool{
                customFunc,
                interactions.NewTool(interactions.GoogleSearch{}),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}

REST

# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
  "model": "gemini-3.8-flash",
  "input": "What is the northernmost city in the United States? What'\''s the weather like there today?",
  "tools": [
    { "type": "google_search" },
    {
      "type": "function",
      "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"]
      }
    }
  ]
}'

آلية العمل

تستخدم نماذج Gemini 3 ميزة تداول سياق الأداة لتفعيل مجموعات الأدوات المضمّنة والمخصّصة. تتيح ميزة تداول سياق الأداة الاحتفاظ بسياق الأدوات المضمّنة وعرضه ومشاركته مع الأدوات المخصّصة في التفاعل نفسه.

تفعيل ميزة الجمع بين الأدوات

  • لتفعيل سلوك الجمع بين الأدوات، عليك تضمين function_declarations بالإضافة إلى الأدوات المضمّنة التي تريد استخدامها.

الخطوات التي تعرضها واجهة برمجة التطبيقات

في ردّ التفاعل، تعرض واجهة برمجة التطبيقات خطوات منفصلة لطلبات الأدوات المضمّنة وطلبات الدوال (الأدوات المخصّصة):

  • خطوات الأداة المضمّنة: تدير واجهة برمجة التطبيقات هذه الخطوات تلقائيًا، مع الاحتفاظ بـ السياق خلال كل دورة.
  • خطوات استدعاء الدالة: تعرض واجهة برمجة التطبيقات خطوات function_call لدوالك المخصّصة. عليك تنفيذ الدالة وتقديم النتيجة مرة أخرى.

الحقول المهمة في الخطوات المعروضة

تُعدّ بعض الحقول في الخطوات المعروضة مهمة للحفاظ على سياق الأداة وتفعيل مجموعات الأدوات:

  • id: يظهر في خطوات function_call وfunction_response. وهو معرّف فريد يربط طلبًا بردّه.
  • signature: يظهر في خطوات thought، بالإضافة إلى جميع خطوات طلب الأداة (مثل function_call) وخطوات النتيجة (مثل function_response) لنماذج Gemini 3 والإصدارات الأحدث. يتيح هذا السياق المشفّر تداول سياق الأداة بين التفاعلات.

إدارة هذه الحقول:

  • الوضع الذي يحفظ الحالة (مُقترَح): عند استخدام previous_interaction_id، يعالج الخادم تلقائيًا كلاً من الحقلَين id وsignature.
  • الوضع الذي لا يحفظ الحالة: عند إدارة سجلّ المحادثات يدويًا، عليك التأكّد من إعادة كل من الحقلَين id وsignature إلى النموذج في الطلبات اللاحقة للتحقّق من صحة السياق والحفاظ عليه. تتولّى حِزم SDK الرسمية هذه العملية تلقائيًا إذا أعدت كائن الردّ الكامل إلى السجلّ.

البيانات الخاصة بالأداة

تعرض بعض الأدوات المضمّنة وسيطات بيانات مرئية للمستخدم خاصة بنوع الأداة.

الأداة وسيطات طلب الأداة المرئية للمستخدم (إن وُجدت) ردّ الأداة المرئي للمستخدم (إن وُجد)
google_search queries search_suggestions
google_maps queries places
google_maps_widget_context_token
url_context urls
عناوين URL التي سيتم تصفّحها
status: حالة التصفّح
retrieved_url: عناوين URL التي تم تصفّحها
file_search بدون بدون

الرموز والأسعار

يُرجى العِلم أنّ أجزاء طلبات الأدوات المضمّنة في الطلبات يتم احتسابها ضمن prompt_token_count. بما أنّ خطوات الأداة الوسيطة هذه أصبحت مرئية ومعروضة لك، فهي جزء من سجلّ المحادثات. لا ينطبق ذلك إلا على حالة الطلبات، وليس الردود.

تُستثنى أداة "بحث Google" من هذه القاعدة. تطبّق "بحث Google" نموذج التسعير الخاص بها على مستوى طلب البحث، لذا لا يتم تحصيل رسوم مضاعفة على الرموز (راجِع صفحة الأسعار).

لمزيد من المعلومات، يُرجى قراءة صفحة الرموز.

القيود

  • يتم تلقائيًا استخدام وضع validated (لا يتوفّر وضع auto) عند تفعيل ميزة تداول سياق الأداة.
  • تعتمد الأدوات المضمّنة، مثل google_search، على معلومات الموقع الجغرافي والوقت الحالي، لذا إذا كانت system_instruction أو function_declaration.description تتضمّن معلومات متضاربة عن الموقع الجغرافي والوقت، قد لا تعمل ميزة الجمع بين الأدوات بشكل جيد.

الأدوات المتوافقة

ينطبق تداول سياق الأداة العادي على الأدوات من جهة الخادم (المضمّنة). تُعدّ ميزة "تنفيذ الرموز البرمجية" أيضًا أداة من جهة الخادم، ولكنها تتضمّن حلاً خاصًا بها لتداول السياق. تُعدّ ميزتا "استخدام الكمبيوتر" و"استدعاء الدوال" أداتَين من جهة العميل، وتتضمّنان أيضًا حلولاً مضمّنة لتداول السياق.

الأداة جهة التنفيذ إتاحة تداول السياق
بحث Google من جهة الخادم متاح
خرائط Google من جهة الخادم متاح
سياق عنوان URL من جهة الخادم متاح
البحث عن الملفات من جهة الخادم متاح
تنفيذ الرموز البرمجية من جهة الخادم متاح (مضمّن، يستخدم خطوات code_execution وcode_execution_result)
استخدام الكمبيوتر من جهة العميل متاح (مضمّن، يستخدم خطوات function_call وfunction_response)
الدوال المخصّصة من جهة العميل متاح (مضمّن، يستخدم خطوات function_call وfunction_response)

الخطوات التالية