קריאה לפונקציות באמצעות Gemini API

קריאה לפונקציות מאפשרת לחבר מודלים לכלים חיצוניים ולממשקי API. במקום ליצור תשובות בטקסט, המודל מבין מתי להפעיל פונקציות ספציפיות ומספק את הפרמטרים הנדרשים לביצוע פעולות בעולם האמיתי. כך המודל יכול לשמש כגשר בין שפה טבעית לבין פעולות ונתונים בעולם האמיתי. לקריאה לפונקציה יש 3 תרחישים עיקריים של שימוש:

  • העשרת הידע: גישה למידע ממקורות חיצוניים כמו מסדי נתונים, ממשקי API ומאגרי ידע.
  • הרחבת היכולות: שימוש בכלים חיצוניים כדי לבצע חישובים ולהרחיב את המגבלות של המודל, למשל שימוש במחשבון או יצירת תרשימים.
  • ביצוע פעולות: אינטראקציה עם מערכות חיצוניות באמצעות ממשקי API, למשל תזמון פגישות, יצירה של חשבוניות, שליחת אימיילים או שליטה במכשירי בית חכם

איך פועלת קריאה לפונקציה

סקירה כללית על קריאה לפונקציות

קריאה לפונקציה כוללת אינטראקציה מובנית בין האפליקציה, המודל והפונקציות החיצוניות. זהו פירוט התהליך:

  1. הגדרת הצהרת הפונקציה: מגדירים את הצהרת הפונקציה בקוד האפליקציה. הצהרות הפונקציות מתארות את השם, הפרמטרים והמטרה של הפונקציה במודל.
  2. קריאה ל-LLM עם הצהרות פונקציה: שולחים למדגם את ההנחיה למשתמש יחד עם הצהרות הפונקציה. הוא מנתח את הבקשה ומחליט אם קריאה לפונקציה תהיה מועילה. אם כן, הוא יחזיר אובייקט JSON מובנה.
  3. קוד הפעלת הפונקציה (האחריות שלכם): המודל לא מפעיל את הפונקציה בעצמו. האפליקציה שלכם אחראית לעבד את התגובה ולבדוק אם יש קריאה לפונקציה, אם
    • כן: חילוץ השם והארגומנטים של הפונקציה והפעלת הפונקציה המתאימה באפליקציה.
    • לא: המודל סיפק תשובה ישירה בטקסט להנחיה (התהליך הזה מודגש פחות בדוגמה, אבל הוא תוצאה אפשרית).
  4. יצירת תשובה ידידותית למשתמש: אם הפונקציה בוצעה, מתעדים את התוצאה ושולחים אותה חזרה למודל בשלב מאוחר יותר של השיחה. הוא ישתמש בתוצאה כדי ליצור תשובה סופית ידידותית למשתמש, שכוללת את המידע מקריאת הפונקציה.

אפשר לחזור על התהליך הזה כמה פעמים, וכך ליצור אינטראקציות ותהליכי עבודה מורכבים. המודל תומך גם בקריאה לכמה פונקציות במהלך אחד (קריאה לפונקציות במקביל) וברצף (קריאה לפונקציות מורכבות).

שלב 1: הגדרת הצהרת הפונקציה

מגדירים פונקציה והצהרה עליה בקוד האפליקציה, שמאפשרת למשתמשים להגדיר ערכי תאורה ולשלוח בקשת API. הפונקציה הזו יכולה להפעיל שירותים חיצוניים או ממשקי API.

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: קריאה למודל באמצעות הצהרות פונקציה

אחרי שמגדירים את הצהרות הפונקציות, אפשר להנחות את המודל להשתמש בפונקציה. הוא מנתח את ההנחיה ואת הצהרות הפונקציות, ומחליט אם להשיב ישירות או להפעיל פונקציה. אם קוראים לפונקציה, אובייקט התגובה יכיל הצעה לקריאה לפונקציה.

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, שמציין איך להפעיל אחת או יותר מהפונקציות המוצגות כדי לענות על השאלה של המשתמש.

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 בקוד שלנו.

# 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: יוצרים תגובה ידידותית למשתמש עם תוצאת הפונקציה ומפעילים שוב את המודל

לבסוף, שולחים את התוצאה של הפעלת הפונקציה חזרה למודל כדי שהוא יוכל לשלב את המידע הזה בתגובה הסופית שהוא נותן למשתמש.

# 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 schema. הצהרת פונקציה אחת יכולה לכלול את הפרמטרים הבאים:

  • name (מחרוזת): שם ייחודי לפונקציה (get_weather_forecast, ‏ send_email). מומלץ להשתמש בשמות תיאוריים ללא רווחים או תווים מיוחדים (אפשר להשתמש בקו תחתון או באותיות רישיות עם אותיות קטנות בתחילת המילה).
  • description (מחרוזת): הסבר ברור ומפורט על המטרה והיכולות של הפונקציה. זה חיוני כדי שהמודל יוכל להבין מתי להשתמש בפונקציה. חשוב להיות ספציפיים ולספק דוגמאות אם זה עוזר ('האפליקציה מאתרת בתי קולנוע על סמך המיקום, ואפשר גם לציין את שם הסרט שמוקרן כרגע בבתי הקולנוע').
  • parameters (אובייקט): מגדיר את פרמטרי הקלט שהפונקציה מצפה להם.
    • type (מחרוזת): מציין את סוג הנתונים הכולל, למשל object.
    • properties (אובייקט): רשימה של פרמטרים נפרדים, כל אחד עם:
      • type (מחרוזת): סוג הנתונים של הפרמטר, למשל string, ‏ integer, ‏ boolean, array.
      • description (מחרוזת): תיאור של המטרה והפורמט של הפרמטר. יש לציין דוגמאות ואילוצים ('העיר והמדינה, למשל, 'תל אביב' או מיקוד, למשל '95616'.").
      • enum (מערך, אופציונלי): אם ערכי הפרמטר הם מתוך קבוצה קבועה, צריך להשתמש ב-enum כדי לרשום את הערכים המותרים במקום רק לתאר אותם בתיאור. כך אפשר לשפר את הדיוק ("enum": ["daylight", "cool", "warm"]).
    • required (מערך): מערך של מחרוזות שמציג את שמות הפרמטרים שחייבים להזין כדי שהפונקציה תפעל.

קריאה לפונקציות במקביל

בנוסף לקריאה לפונקציה אחת, אפשר גם לקרוא לכמה פונקציות בו-זמנית. קריאה לפונקציות במקביל מאפשרת להריץ כמה פונקציות בו-זמנית, והיא משמשת כשהפונקציות לא תלויות זו בזו. האפשרות הזו שימושית בתרחישים כמו איסוף נתונים ממספר מקורות עצמאיים, למשל אחזור פרטי לקוחות ממסדי נתונים שונים, בדיקת רמות מלאי במחסנים שונים או ביצוע מספר פעולות, כמו המרת הדירה שלכם למועדון.

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. מידע נוסף זמין במאמר הגדרת קריאה לפונקציות.

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

כל אחת מהתוצאות המודפסות משקפת קריאה יחידה לפונקציה שהמודל ביקש. כדי לשלוח את התוצאות חזרה, צריך לכלול את התשובות באותו סדר שבו הן התבקשו.

‏Python SDK תומך בתכונה שנקראת automatic function calling (קריאה אוטומטית לפונקציות), שממירה את פונקציית Python להצהרות, מטפלת בביצוע הקריאה לפונקציה ובמחזור התשובה בשבילכם. בהמשך מופיעה דוגמה לתרחיש לדוגמה שלנו בנושא Disco.

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() שמקבלת את המיקום כפרמטר.

# 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: אסור לבצע קריאות לפונקציות במודל. זה שווה ערך לשליחת בקשה ללא הצהרות על פונקציות. אפשר להשתמש באפשרות הזו כדי להשבית באופן זמני את הקריאה לפונקציות בלי להסיר את הגדרות הכלים.

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 בלבד)

כשמשתמשים ב-Python SDK, אפשר לספק פונקציות Python ישירות ככלים. ה-SDK ממיר באופן אוטומטי את פונקציית Python להצהרות, מטפל בהפעלת קריאת הפונקציה ובמחזור התגובה בשבילכם. לאחר מכן, ה-Python SDK יבצע באופן אוטומטי את הפעולות הבאות:

  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 לא פועל בכל המקרים. לדוגמה: הוא לא מטפל במקרים שבהם מתארים את השדות של אובייקט מילון בתצוגת עץ. ה-API יכול לתאר כל אחד מהסוגים הבאים:

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 והרצת קוד, בבקשה באמצעות ממשק API בזמן אמת.

# 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 יכולים לנסות את זה במחברת הקוד של הכלי לשימוש ב-API בזמן אמת.

מודלים נתמכים

מודלים ניסיוניים לא נכללים. היכולות שלהם מפורטות בדף סקירה כללית של המודל.

דגם קריאה לפונקציות קריאה לפונקציות במקביל קריאה לפונקציות מורכבות
(API פעיל בלבד)
Gemini 2.0 Flash ✔️ ✔️ ✔️
Gemini 2.0 Flash-Lite X X X
Gemini 1.5 Flash ✔️ ✔️ ✔️
Gemini 1.5 Pro ✔️ ✔️ ✔️

שיטות מומלצות

  • תיאורים של פונקציות ופרמטרים: חשוב שהתיאורים יהיו ברורים ומפורטים מאוד. המודל מסתמך עליהם כדי לבחור את הפונקציה הנכונה ולספק את הארגומנטים המתאימים.
  • בחירת שמות: כדאי להשתמש בשמות פונקציות תיאוריים (ללא רווחים, נקודות או מקפים).
  • Strong Typing: שימוש בסוגי פרמטרים ספציפיים (integer, ‏ string, ‏ enum) כדי לצמצם את מספר השגיאות. אם לפרמטר יש קבוצה מוגבלת של ערכים תקינים, צריך להשתמש ב-enum.
  • הנדסת הנחיות:
    • לספק הקשר: מציינים למודל את התפקיד שלו (למשל, "You are a helpful weather assistant").
    • נותנים הוראות: מציינים איך ומתי להשתמש בפונקציות (למשל: "אל תנחשו תאריכים, תמיד צריך להשתמש בתאריך עתידי בתחזיות").
    • מעודדים הבהרה: מורים למודל לשאול שאלות הבהרה במקרה הצורך.
  • טמפרטורה: מומלץ להשתמש בטמפרטורה נמוכה (למשל, 0) כדי לקבל קריאות פונקציה דטרמיניסטיות ואמינות יותר.
  • אימות: אם לקריאה לפונקציה יש השלכות משמעותיות (למשל, ביצוע הזמנה), צריך לאמת את הקריאה עם המשתמש לפני שמבצעים אותה.
  • טיפול בשגיאות: הטמעת טיפול חזק בשגיאות בפונקציות כדי לטפל בצורה חלקה בקלט לא צפוי או בכשלים ב-API. להחזיר הודעות שגיאה מפורטות שהמודל יכול להשתמש בהן כדי ליצור תשובות מועילות למשתמש.
  • אבטחה: חשוב לשים לב לאבטחה כשקוראים לממשקי API חיצוניים. שימוש במנגנוני אימות והרשאה מתאימים. הימנעו מחשיפת מידע אישי רגיש בקריאות לפונקציות.
  • מגבלות על אסימונים: תיאורים ופרמטרים של פונקציות נספרים במסגרת המגבלה על אסימוני הקלט. אם אתם נתקלים במגבלות על האסימונים, כדאי להגביל את מספר הפונקציות או את אורך התיאורים, ולחלק משימות מורכבות לקבוצות פונקציות קטנות יותר וממוקדות יותר.

הערות ומגבלות