استدعاء الدوالّ باستخدام Gemini API

تتيح لك طلبات البيانات ربط النماذج بالأدوات وواجهات برمجة التطبيقات الخارجية. بدلاً من إنشاء ردود نصية، يفهم النموذج الحالات التي يجب فيها استدعاء وظائف معيّنة ويقدّم المَعلمات اللازمة لتنفيذ الإجراءات في الواقع. ويسمح ذلك للنموذج بالعمل كجسر بين اللغة الطبيعية والواقع المتمثل في الإجراءات والبيانات. هناك 3 حالات استخدام أساسية لاستدعاء الدوالّ:

  • تعزيز المعرفة: يمكنك الوصول إلى المعلومات من مصادر خارجية، مثل قواعد البيانات وواجهات برمجة التطبيقات وقواعد المعلومات.
  • توسيع الإمكانات: يمكنك استخدام أدوات خارجية لإجراء العمليات الحسابية وتوسيع قيود النموذج، مثل استخدام آلة حاسبة أو إنشاء الرسوم البيانية.
  • اتّخاذ الإجراءات: التفاعل مع الأنظمة الخارجية باستخدام واجهات برمجة التطبيقات، مثل تحديد المواعيد أو إنشاء الفواتير أو إرسال الرسائل الإلكترونية أو التحكّم في الأجهزة المنزلية الذكية

آلية عمل "استدعاء الدوالّ البرمجية"

نظرة عامة على استدعاء الدوالّ

يتضمن استدعاء الدالة تفاعلًا منظَّمًا بين تطبيقك والنموذج والدوالّ الخارجية. في ما يلي تفاصيل العملية:

  1. تحديد تعريف الدالة: حدِّد تعريف الدالة في код التطبيق. تصف تعريفات الدوالّ اسم الدالة ومعلماتها والغرض منها للنموذج.
  2. استدعاء نموذج "التعلم الآلي للغة" باستخدام تعريفات الدوالّ: أرسِل طلب المستخدم مع تعريفات الدوالّ إلى النموذج. ويعمل هذا الإجراء على تحليل الطلب ويحدد ما إذا كان من المفيد استدعاء دالة. إذا كان الأمر كذلك، يتم الردّ باستخدام كائن ملف JSON منظَّم.
  3. رمز تنفيذ الدالة (مسؤوليتك): لا ينفِّذ النموذج الدالة نفسها. تقع على عاتق تطبيقك مسؤولية معالجة الردّ والتحقّق من طلب الوظيفة، إذا كان
    • نعم: استخرِج اسم الدالة ومَعلماتها ونفِّذ الدالة المقابلة في تطبيقك.
    • لا: قدّم النموذج ردًا نصيًا مباشرًا على الطلب (يتم التركيز على هذا المسار بشكل أقل في المثال، ولكنه نتيجة محتملة).
  4. إنشاء ردّ سهل على المستخدم: في حال تنفيذ وظيفة، عليك تسجيل النتيجة وإرسالها مرة أخرى إلى النموذج في جولة لاحقة من المحادثة. سيستخدم الإجراء النتيجة لإنشاء ردّ نهائي وسهل الاستخدام يضمّ المعلومات الواردة من طلب الدالة.

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

الخطوة 1: تحديد بيان الدالة

حدِّد دالة وبيانًا لها في رمز تطبيقك يتيحان للمستخدمين ضبط قيم الإضاءة وتقديم طلب لواجهة برمجة التطبيقات. يمكن أن تستدعي هذه الدالة خدمات خارجية أو واجهات برمجة تطبيقات.

PythonJavaScript
from google.genai import types

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

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

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

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

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

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

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

الخطوة 2: استدعاء النموذج باستخدام تعريفات الدوالّ

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

PythonJavaScript
from google import genai

# Generation Config with Function Declaration
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])

# Configure the client
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

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

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

print(response.candidates[0].content.parts[0].function_call)
import { GoogleGenAI } from '@google/genai';

// Generation Config with Function Declaration
const config = {
  tools: [{
    functionDeclarations: [setLightValuesFunctionDeclaration]
  }]
};

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

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

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

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

بعد ذلك، يعرض النموذج عنصرًا من النوع functionCall في ملف تعريف متوافق مع OpenAPI يحدّد كيفية طلب دالة واحدة أو أكثر من الدوال المُعلَن عنها من أجل الردّ على سؤال المستخدم.

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

الخطوة 3: تنفيذ رمز الدالة set_light_values

استخرِج تفاصيل طلب استدعاء الدالة من ردّ النموذج، وحلِّل الوسيطات ، ونفِّذ دالة set_light_values في الرمز البرمجي.

PythonJavaScript
# Extract tool call details
tool_call = response.candidates[0].content.parts[0].function_call

if tool_call.name == "set_light_values":
    result = set_light_values(**tool_call.args)
    print(f"Function execution result: {result}")
// Extract tool call details
const tool_call = response.functionCalls[0]

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

الخطوة 4: إنشاء ردّ سهل على المستخدم مع نتيجة الدالة واستدعاء النموذج مرة أخرى

أخيرًا، أرسِل نتيجة تنفيذ الدالة إلى النموذج حتى يتمكّن من دمج هذه المعلومات في ردّه النهائي على المستخدم.

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

# Append function call and result of the function execution to contents
contents.append(types.Content(role="model", parts=[types.Part(function_call=tool_call)])) # Append the model's function call message
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response

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

print(final_response.text)
// Create a function response part
const function_response_part = {
  name: tool_call.name,
  response: { result }
}

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

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

console.log(final_response.text);

وبذلك، تكتمل عملية استدعاء الدالة. استخدم النموذج الدالة set_light_values بنجاح لتنفيذ إجراء الطلب الذي قدّمه المستخدم.

تعريفات الدوالّ

عند تنفيذ طلب دالة في طلب، يتم إنشاء عنصر tools يحتوي على عنصر function declarations واحد أو أكثر. يمكنك تحديد الدوالّ باستخدام تنسيق JSON، وتحديدًا باستخدام مجموعة فرعية محدّدة من تنسيق مخطّط OpenAPI. يمكن أن يتضمّن بيان دالة واحد المَعلمات التالية:

  • name (سلسلة): اسم فريد للدالة (get_weather_forecast أو send_email). استخدِم أسماء وصفية بدون مسافات أو أحرف خاصة (استخدِم الواصلات السفلية أو أسلوب camelCase).
  • description (سلسلة): شرح واضح ومفصّل لهدف الدالة وإمكاناتها وهذا أمر مهمّ ليتمكّن النموذج من فهم وقت استخدام الدالة. يجب أن تكون دقيقًا وأن تقدّم أمثلة إذا كان ذلك مفيدًا ("يبحث عن دور السينما استنادًا إلى الموقع الجغرافي وعنوان الفيلم المعروض حاليًا في دور السينما اختياريًا").
  • parameters (كائن): يحدِّد مَعلمات الإدخال التي تتوقّعها الدالة.
    • type (سلسلة): لتحديد نوع البيانات العام، مثل object
    • properties (عنصر): يسرد المَعلمات الفردية، وكل منها يتضمّن ما يلي:
      • type (سلسلة): نوع بيانات المَعلمة، مثل string وinteger وboolean, array
      • description (سلسلة): وصف لغرض المَعلمة وتنسيقها تقديم أمثلة والقيود ("المدينة والولاية، على سبيل المثال، "القاهرة، مصر" أو رمز بريدي، مثلاً ‎'95616'.").
      • enum (مصفوفة، اختيارية): إذا كانت قيم المَعلمة من مجموعة ثابتة، استخدِم "enum" لسرد القيم المسموح بها بدلاً من وصفها في الوصف فقط. ويؤدي ذلك إلى تحسين الدقة ("enum": ["daylight", "cool", "warm"]).
    • required (مصفوفة): مصفوفة من السلاسل التي تسرد أسماء المَعلمات الإلزامية لكي تعمل الدالة

استدعاء الدوالّ بشكل موازٍ

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

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

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

dim_lights = {
    "name": "dim_lights",
    "description": "Dim the lights.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "number",
                "description": "The brightness of the lights, 0.0 is off, 1.0 is full.",
            }
        },
        "required": ["brightness"],
    },
}
import { Type } from '@google/genai';

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

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

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

استدعاء النموذج باستخدام تعليمات يمكنها استخدام جميع الأدوات المحدّدة يستخدم هذا المثال tool_config. لمزيد من المعلومات، يمكنك الاطّلاع على ضبط استدعاء الدوال.

PythonJavaScript
from google import genai
from google.genai import types

# Set up function declarations
house_tools = [
    types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]

config = {
    "tools": house_tools,
    "automatic_function_calling": {"disable": True},
    # Force the model to call 'any' function, instead of chatting.
    "tool_config": {"function_calling_config": {"mode": "any"}},
}

# Configure the client
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

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

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

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

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

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

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

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

تعكس كل نتيجة من النتائج المطبوعة طلب دالة واحدة طلبه النموذج. لإرسال النتائج مرة أخرى، يجب تضمين الردود بالترتيب نفسه الذي تم طلبه.

تتيح حزمة تطوير البرامج (SDK) لـ Python ميزة تُعرف باسم استدعاء الدالة تلقائيًا، وهي تحوّل دالة Python إلى بيانات تعريف، وتتعامل مع تنفيذ استدعاء الدالة ودورة الاستجابة نيابةً عنك. في ما يلي مثال على حالة استخدامنا لميزة "الحفلة الموسيقية".

Python
from google import genai
from google.genai import types

# Actual implementation functions
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}

config = {
    "tools": [power_disco_ball_impl, start_music_impl, dim_lights_impl],
}

chat = client.chats.create(model="gemini-2.0-flash", config=config)
response = chat.send_message("Do everything you need to this place into party!")

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 2.0 استدعاء الدوالّ التركيبية، ما يعني أنّه يمكن للنموذج ربط طلبات استدعاء الدوالّ المتعدّدة معًا. على سبيل المثال، للإجابة عن طلب "الحصول على درجة الحرارة في موقعي الجغرافي الحالي"، قد تستدعي Gemini API كلّ من دالة get_current_location() ودالة get_weather() التي تأخذ الموقع الجغرافي كمَعلمة.

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

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

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

await run(prompt, tools=tools, modality="AUDIO")
// Light control schemas
const turnOnTheLightsSchema = { name: 'turn_on_the_lights' };
const turnOffTheLightsSchema = { name: 'turn_off_the_lights' };

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

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

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

أوضاع استدعاء الدوالّ

تتيح لك Gemini API التحكّم في كيفية استخدام النموذج للأدوات المقدَّمة (بيانات الدوالّ). ويمكنك تحديد الوضع ضمن function_calling_config.

  • AUTO (Default): يقرّر النموذج ما إذا كان سينشئ ردًا باللغة الطبيعية أو يقترح طلب استدعاء دالة استنادًا إلى الطلب والسياق. هذا هو الوضع الأكثر مرونةً ويُنصح به في معظم السيناريوهات.
  • ANY: يتم تقييد النموذج دائمًا بتوقع استدعاء دالة وضمان الالتزام بمخطّط الدالة. في حال عدم تحديد allowed_function_names، يمكن للنموذج الاختيار من بين أيّ من تعريفات الدوالّ المقدّمة. إذا تم تقديم allowed_function_names كقائمة، لا يمكن للنموذج الاختيار إلا من بين الدوالّ الواردة في تلك القائمة. استخدِم هذا الوضع عندما تحتاج إلى طلب دالة استجابةً لكل طلب (إن أمكن).
  • NONE: محظور على النموذج إجراء استدعاءات للوظائف. ويعادل ذلك إرسال طلب بدون أيّ تعريفات وظائف. استخدِم هذا الخيار لإيقاف استدعاء الدوال مؤقتًا بدون إزالة تعريفات الأدوات.

PythonJavaScript
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(
    temperature=0,
    tools=[tools],  # not defined here.
    tool_config=tool_config,
)
import { FunctionCallingConfigMode } from '@google/genai';

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

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

استدعاء الدالة التلقائي (Python فقط)

عند استخدام حزمة تطوير البرامج (SDK) لـ Python، يمكنك توفير دوال Python مباشرةً كأدوات. تحوِّل حزمة SDK دالة Python تلقائيًا إلى بيانات تعريف، وتتعامل مع دورة استدعاء الدالة والاستجابة نيابةً عنك. بعد ذلك، تُجري حزمة تطوير البرامج (SDK) لـ Python ما يلي تلقائيًا:

  1. يرصد استجابات استدعاء الدوال من النموذج.
  2. استخدِم دالة Python المقابلة في الرمز البرمجي.
  3. تُرسِل استجابة الدالة مرة أخرى إلى النموذج.
  4. تعرِض هذه السمة الردّ النصي النهائي للنموذج.

لاستخدام هذه الطريقة، حدِّد الدالة باستخدام تلميحات النوع ونص وصفي، ثم مرِّر الدالة نفسها (وليس بيان JSON) كأداة:

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 and model
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))  # Replace with your actual API key setup
config = types.GenerateContentConfig(
    tools=[get_current_temperature]
)  # Pass the function itself

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

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

يمكنك إيقاف استدعاء الدوالّ التلقائي باستخدام:

Python
# To disable automatic function calling:
config = types.GenerateContentConfig(
    tools=[get_current_temperature],
    automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)

بيان مخطّط الدالة التلقائية

لا تعمل عملية استخراج المخطّط التلقائية من وظائف Python في جميع الحالات. على سبيل المثال، لا يعالج هذا الإجراء الحالات التي تصف فيها حقول عنصر قاموس متداخل. يمكن لواجهة برمجة التطبيقات وصف أيٍّ من الأنواع التالية:

Python
AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])

للاطّلاع على شكل المخطّط المستنِد، يمكنك تحويله باستخدام from_callable:

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

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 2.0، يمكنك تفعيل أدوات متعددة تجمع بين الأدوات الأصلية وطلب الدوالّ في الوقت نفسه. في ما يلي مثال يتيح أداتَين، هما التحقّق من صحة البيانات باستخدام "بحث Google" وتنفيذ الرموز البرمجية، في طلب باستخدام Live API.

PythonJavaScript

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

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

  Thanks!
  """

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

# Execute the prompt with specified tools in audio modality
await run(prompt, tools=tools, modality="AUDIO")
// Multiple tasks example - combining lights, code execution, and search
const prompt = `
  Hey, I need you to do three things for me.

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

  Thanks!
`;

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

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

يمكن لمطوّري Python تجربة ذلك في دفتر ملاحظات استخدام أداة Live API.

النماذج المتوافقة

ولا يتم تضمين النماذج التجريبية. يمكنك الاطّلاع على ميزاتها في صفحة نظرة عامة على النموذج.

الطراز استدعاء الدوالّ استدعاء الدوالّ بشكل موازٍ استدعاء الدوال التركيبية
(واجهة برمجة التطبيقات المنشورة فقط)
نموذج Gemini 2.0 Flash ✔️ ✔️ ✔️
‫Gemini 2.0 Flash-Lite X X X
Gemini 1.5 Flash ✔️ ✔️ ✔️
Gemini 1.5 Pro ✔️ ✔️ ✔️

أفضل الممارسات

  • أوصاف الدوال والمَعلمات: يجب أن تكون أوصافك واضحة ومحددة للغاية. يعتمد النموذج على هذه العناصر لاختيار الدالة الصحيحة وتقديم الوسيطات المناسبة.
  • التسمية: استخدِم أسماء دوالّ وصفية (بدون مسافات أو نقاط أو شرطات).
  • الكتابة القوية: استخدِم أنواعًا محدّدة (عدد صحيح أو سلسلة أو قائمة أرقام) للمَعلمات للحدّ من الأخطاء. إذا كانت المَعلمة تحتوي على مجموعة محدودة من القيم الصالحة، استخدِم مصنّفًا.
  • هندسة الطلبات:
    • تقديم سياق: أخبِر النموذج بدوره (مثل "أنت مساعد مفيد بشأن الطقس").
    • تقديم تعليمات: حدِّد كيفية استخدام الدوالّ وحالات استخدامها (مثل "لا تخمن التواريخ، بل استخدِم دائمًا تاريخًا مستقبليًا للتوقّعات").
    • تشجيع التوضيح: يمكنك توجيه النموذج لطرح أسئلة توضيحية إذا لزم الأمر.
  • درجة الحرارة: استخدِم درجة حرارة منخفضة (مثل 0) لطلبات الدوالّ الأكثر تحديدًا وموثوقية.
  • التحقّق من الصحة: إذا كانت هناك عواقب مهمة ناتجة عن طلب دالة (مثل تقديم طلب)، عليك التحقّق من صحته مع المستخدم قبل تنفيذه.
  • معالجة الأخطاء: نفِّذ معالجة أخطاء فعّالة في دوالّك للتعامل بنجاح مع الإدخالات غير المتوقّعة أو حالات تعذُّر الاتصال بواجهة برمجة التطبيقات. عرض رسائل خطأ إعلامية يمكن للنموذج استخدامها لإنشاء ردود مفيدة للمستخدم
  • الأمان: يجب الانتباه إلى الأمان عند استدعاء واجهات برمجة التطبيقات الخارجية. استخدِم آليات المصادقة والتفويض المناسبة. تجنَّب عرض البيانات الحسّاسة في طلبات الدالة.
  • الحدود القصوى للرموز المميّزة: يتم احتساب أوصاف الدوالّ ومعلماتها ضمن الحدّ الأقصى لرموز الإدخال المميّزة. إذا كنت تتجاوز حدود الرموز المميّزة، ننصحك بالحد من عدد الدوال أو طول الأوصاف، وتقسيم المهام المعقّدة إلى مجموعات دوال أصغر حجمًا وأكثر تركيزًا.

الملاحظات والقيود

  • لا يتوافق سوى مجموعة فرعية من مخطّط OpenAPI.
  • أنواع المَعلمات المتوافقة في بايثون محدودة.
  • إنّ استدعاء الدوالّ تلقائيًا هو ميزة حزمة تطوير البرامج (SDK) لـ Python فقط.