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

קריאה לפונקציות, שנקראת גם שימוש בכלים, מספקת למודל LLM הגדרות של כלים חיצוניים (לדוגמה, פונקציית get_current_weather). כשמעבדים הנחיה, המודל קובע בצורה חכמה אם צריך כלי, ואם כן, הוא מפיק נתונים מוּבְנִים שמציינים את הכלי שצריך להפעיל ואת הפרמטרים שלו (לדוגמה, get_current_weather(location='Boston')). לאחר מכן, האפליקציה מפעילה את הכלי הזה, מעבירה את התוצאה בחזרה למודל, וכך המודל יכול להשלים את התגובה שלו עם מידע דינמי מהעולם האמיתי או עם תוצאה של פעולה. כך נוצר גשר בין מודל ה-LLM לבין המערכות שלכם, והיכולות שלו מתרחבות.

דיאגרמה שממחישה את זרימת האינטראקציה של בקשה להפעלת פונקציה 

הבקשה להפעלת פונקציה מאפשרת שני תרחישי שימוש עיקריים:

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

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

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

תכונות ומגבלות

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

כדי להשתמש בהפעלת פונקציות, צריך לבצע את המשימות הבאות:

  1. שולחים למודל הצהרות על פונקציות והנחיה.
  2. מספקים את הפלט של ה-API למודל.

שלב 1: שולחים את ההנחיה ואת ההצהרות על הפונקציות למודל

מצהירים על Tool בפורמט סכימה שתואם לסכימת OpenAPI. מידע נוסף זמין במאמר בנושא דוגמאות לסכימה.

בדוגמאות הבאות מועברת הנחיה והצהרת פונקציה למודלים של Gemini:

REST

PROJECT_ID=myproject
LOCATION=us-central1
MODEL_ID=gemini-2.5-flash

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "What is the weather in Boston?"
      }]
    }],
    "tools": [{
      "functionDeclarations": [
        {
          "name": "get_current_weather",
          "description": "Get the current weather in a given location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city name of the location for which to get the weather.",
                "default": {
                  "string_value": "Boston, MA"
                }
              }
            },
            "required": [
              "location"
            ]
          }
        }
      ]
    }]
  }'

Gen AI SDK ל-Python

from google import genai
from google.genai.types import GenerateContentConfig, Part

# The project and location are passed directly to the client,
# and vertexai=True is added to specify the use of the Vertex AI backend.
client = genai.Client(vertexai=True, project="PROJECT_ID", location="global")

def get_current_weather(location: str) -> str:
  """Returns the current weather.

  Args:
    location: The city and state, e.g. San Francisco, CA
  """
  return 'sunny'

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="What is the weather in boston?",
    config=GenerateContentConfig(tools=[get_current_weather]),
)

‫Vertex AI SDK ל-Python

אפשר לציין את הסכימה באופן ידני באמצעות מילון Python או באופן אוטומטי באמצעות פונקציית העזר from_func. בדוגמה הבאה אפשר לראות איך להצהיר על פונקציה באופן ידני:

import vertexai
from vertexai.generative_models import (
    Content,
    FunctionDeclaration,
    GenerationConfig,
    GenerativeModel,
    Part,
    Tool,
    ToolConfig
)

# Initialize Vertex AI
# TODO(developer): Update the project
vertexai.init(project="PROJECT_ID", location="us-central1")

# Initialize Gemini model
model = GenerativeModel(model_name="gemini-2.5-flash")

# Manual function declaration
get_current_weather_func = FunctionDeclaration(
    name="get_current_weather",
    description="Get the current weather in a given location",
    # Function parameters are specified in JSON schema format
    parameters={
        "type": "object",
        "properties": {
            "location": {
              "type": "string",
              "description": "The city name of the location for which to get the weather.",
              "default": {
                "string_value": "Boston, MA"
              }
           }
        },
    },
)

response = model.generate_content(
    contents = [
      Content(
        role="user",
          parts=[
              Part.from_text("What is the weather like in Boston?"),
          ],
      )
    ],
    generation_config = GenerationConfig(temperature=0),
    tools = [
      Tool(
        function_declarations=[get_current_weather_func],
      )
    ]
)

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

def get_current_weather(location: str = "Boston, MA"):
  """
  Get the current weather in a given location

  Args:
      location: The city name of the location for which to get the weather.

  """
  # This example uses a mock implementation.
  # You can define a local function or import the requests library to call an API
  return {
    "location": "Boston, MA",
    "temperature": 38,
    "description": "Partly Cloudy",
    "icon": "partly-cloudy",
    "humidity": 65,
    "wind": {
        "speed": 10,
        "direction": "NW"
    }
  }
get_current_weather_func = FunctionDeclaration.from_func(get_current_weather)

Node.js

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

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה במאמר Vertex AI quickstart using client libraries. מידע נוסף מופיע במאמרי העזרה של Vertex AI Node.js API.

כדי לבצע אימות ב-Vertex AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

const {
  VertexAI,
  FunctionDeclarationSchemaType,
} = require('@google-cloud/vertexai');

const functionDeclarations = [
  {
    function_declarations: [
      {
        name: 'get_current_weather',
        description: 'get weather in a given location',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            location: {type: FunctionDeclarationSchemaType.STRING},
            unit: {
              type: FunctionDeclarationSchemaType.STRING,
              enum: ['celsius', 'fahrenheit'],
            },
          },
          required: ['location'],
        },
      },
    ],
  },
];

const functionResponseParts = [
  {
    functionResponse: {
      name: 'get_current_weather',
      response: {name: 'get_current_weather', content: {weather: 'super nice'}},
    },
  },
];

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function functionCallingStreamContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-2.0-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const request = {
    contents: [
      {role: 'user', parts: [{text: 'What is the weather in Boston?'}]},
      {
        role: 'ASSISTANT',
        parts: [
          {
            functionCall: {
              name: 'get_current_weather',
              args: {location: 'Boston'},
            },
          },
        ],
      },
      {role: 'USER', parts: functionResponseParts},
    ],
    tools: functionDeclarations,
  };
  const streamingResp = await generativeModel.generateContentStream(request);
  for await (const item of streamingResp.stream) {
    console.log(item.candidates[0].content.parts[0].text);
  }
}

Go

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

כך מתקינים או מעדכנים את Go.

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithFuncCall shows how to submit a prompt and a function declaration to the model,
// allowing it to suggest a call to the function to fetch external data. Returning this data
// enables the model to generate a text response that incorporates the data.
func generateWithFuncCall(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	weatherFunc := &genai.FunctionDeclaration{
		Description: "Returns the current weather in a location.",
		Name:        "getCurrentWeather",
		Parameters: &genai.Schema{
			Type: "object",
			Properties: map[string]*genai.Schema{
				"location": {Type: "string"},
			},
			Required: []string{"location"},
		},
	}
	config := &genai.GenerateContentConfig{
		Tools: []*genai.Tool{
			{FunctionDeclarations: []*genai.FunctionDeclaration{weatherFunc}},
		},
		Temperature: genai.Ptr(float32(0.0)),
	}

	modelName := "gemini-2.5-flash"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What is the weather like in Boston?"},
		},
			Role: genai.RoleUser},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	var funcCall *genai.FunctionCall
	for _, p := range resp.Candidates[0].Content.Parts {
		if p.FunctionCall != nil {
			funcCall = p.FunctionCall
			fmt.Fprint(w, "The model suggests to call the function ")
			fmt.Fprintf(w, "%q with args: %v\n", funcCall.Name, funcCall.Args)
			// Example response:
			// The model suggests to call the function "getCurrentWeather" with args: map[location:Boston]
		}
	}
	if funcCall == nil {
		return fmt.Errorf("model did not suggest a function call")
	}

	// Use synthetic data to simulate a response from the external API.
	// In a real application, this would come from an actual weather API.
	funcResp := &genai.FunctionResponse{
		Name: "getCurrentWeather",
		Response: map[string]any{
			"location":         "Boston",
			"temperature":      "38",
			"temperature_unit": "F",
			"description":      "Cold and cloudy",
			"humidity":         "65",
			"wind":             `{"speed": "10", "direction": "NW"}`,
		},
	}

	// Return conversation turns and API response to complete the model's response.
	contents = []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What is the weather like in Boston?"},
		},
			Role: genai.RoleUser},
		{Parts: []*genai.Part{
			{FunctionCall: funcCall},
		}},
		{Parts: []*genai.Part{
			{FunctionResponse: funcResp},
		}},
	}

	resp, err = client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)

	// Example response:
	// The weather in Boston is cold and cloudy with a temperature of 38 degrees Fahrenheit. The humidity is ...

	return nil
}

C#‎

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

C#

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי C#הוראות ההגדרה במאמר Vertex AI quickstart using client libraries. מידע נוסף מופיע במאמרי העזרה של Vertex AI C# API.

כדי לבצע אימות ב-Vertex AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


using Google.Cloud.AIPlatform.V1;
using System;
using System.Threading.Tasks;
using Type = Google.Cloud.AIPlatform.V1.Type;
using Value = Google.Protobuf.WellKnownTypes.Value;

public class FunctionCalling
{
    public async Task<string> GenerateFunctionCall(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-2.0-flash-001")
    {
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();

        // Define the user's prompt in a Content object that we can reuse in
        // model calls
        var userPromptContent = new Content
        {
            Role = "USER",
            Parts =
            {
                new Part { Text = "What is the weather like in Boston?" }
            }
        };

        // Specify a function declaration and parameters for an API request
        var functionName = "get_current_weather";
        var getCurrentWeatherFunc = new FunctionDeclaration
        {
            Name = functionName,
            Description = "Get the current weather in a given location",
            Parameters = new OpenApiSchema
            {
                Type = Type.Object,
                Properties =
                {
                    ["location"] = new()
                    {
                        Type = Type.String,
                        Description = "Get the current weather in a given location"
                    },
                    ["unit"] = new()
                    {
                        Type = Type.String,
                        Description = "The unit of measurement for the temperature",
                        Enum = {"celsius", "fahrenheit"}
                    }
                },
                Required = { "location" }
            }
        };

        // Send the prompt and instruct the model to generate content using the tool that you just created
        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            GenerationConfig = new GenerationConfig
            {
                Temperature = 0f
            },
            Contents =
            {
                userPromptContent
            },
            Tools =
            {
                new Tool
                {
                    FunctionDeclarations = { getCurrentWeatherFunc }
                }
            }
        };

        GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

        var functionCall = response.Candidates[0].Content.Parts[0].FunctionCall;
        Console.WriteLine(functionCall);

        string apiResponse = "";

        // Check the function name that the model responded with, and make an API call to an external system
        if (functionCall.Name == functionName)
        {
            // Extract the arguments to use in your API call
            string locationCity = functionCall.Args.Fields["location"].StringValue;

            // Here you can use your preferred method to make an API request to
            // fetch the current weather

            // In this example, we'll use synthetic data to simulate a response
            // payload from an external API
            apiResponse = @"{ ""location"": ""Boston, MA"",
                    ""temperature"": 38, ""description"": ""Partly Cloudy""}";
        }

        // Return the API response to Gemini so it can generate a model response or request another function call
        generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            Contents =
            {
                userPromptContent, // User prompt
                response.Candidates[0].Content, // Function call response,
                new Content
                {
                    Parts =
                    {
                        new Part
                        {
                            FunctionResponse = new()
                            {
                                Name = functionName,
                                Response = new()
                                {
                                    Fields =
                                    {
                                        { "content", new Value { StringValue = apiResponse } }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            Tools =
            {
                new Tool
                {
                    FunctionDeclarations = { getCurrentWeatherFunc }
                }
            }
        };

        response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

        string responseText = response.Candidates[0].Content.Parts[0].Text;
        Console.WriteLine(responseText);

        return responseText;
    }
}

Java

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaהוראות ההגדרה במאמר Vertex AI quickstart using client libraries. מידע נוסף מופיע במאמרי העזרה של Vertex AI Java API.

כדי לבצע אימות ב-Vertex AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.Content;
import com.google.cloud.vertexai.api.FunctionDeclaration;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.api.Schema;
import com.google.cloud.vertexai.api.Tool;
import com.google.cloud.vertexai.api.Type;
import com.google.cloud.vertexai.generativeai.ChatSession;
import com.google.cloud.vertexai.generativeai.ContentMaker;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.PartMaker;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

public class FunctionCalling {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-2.5-flash";

    String promptText = "What's the weather like in Paris?";

    whatsTheWeatherLike(projectId, location, modelName, promptText);
  }

  // A request involving the interaction with an external tool
  public static String whatsTheWeatherLike(String projectId, String location,
                                           String modelName, String promptText)
      throws IOException {
    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    try (VertexAI vertexAI = new VertexAI(projectId, location)) {

      FunctionDeclaration functionDeclaration = FunctionDeclaration.newBuilder()
          .setName("getCurrentWeather")
          .setDescription("Get the current weather in a given location")
          .setParameters(
              Schema.newBuilder()
                  .setType(Type.OBJECT)
                  .putProperties("location", Schema.newBuilder()
                      .setType(Type.STRING)
                      .setDescription("location")
                      .build()
                  )
                  .addRequired("location")
                  .build()
          )
          .build();

      System.out.println("Function declaration:");
      System.out.println(functionDeclaration);

      // Add the function to a "tool"
      Tool tool = Tool.newBuilder()
          .addFunctionDeclarations(functionDeclaration)
          .build();

      // Start a chat session from a model, with the use of the declared function.
      GenerativeModel model = new GenerativeModel(modelName, vertexAI)
          .withTools(Arrays.asList(tool));
      ChatSession chat = model.startChat();

      System.out.println(String.format("Ask the question: %s", promptText));
      GenerateContentResponse response = chat.sendMessage(promptText);

      // The model will most likely return a function call to the declared
      // function `getCurrentWeather` with "Paris" as the value for the
      // argument `location`.
      System.out.println("\nPrint response: ");
      System.out.println(ResponseHandler.getContent(response));

      // Provide an answer to the model so that it knows what the result
      // of a "function call" is.
      Content content =
          ContentMaker.fromMultiModalData(
              PartMaker.fromFunctionResponse(
                  "getCurrentWeather",
                  Collections.singletonMap("currentWeather", "sunny")));
      System.out.println("Provide the function response: ");
      System.out.println(content);
      response = chat.sendMessage(content);

      // See what the model replies now
      System.out.println("Print response: ");
      String finalAnswer = ResponseHandler.getText(response);
      System.out.println(finalAnswer);

      return finalAnswer;
    }
  }
}

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

זוהי דוגמה לתשובה של מודל להנחיית המשתמש "מה מזג האוויר בבוסטון?". המודל מציע להפעיל את הפונקציה get_current_weather עם הפרמטר Boston, MA.

candidates {
  content {
    role: "model"
    parts {
      function_call {
        name: "get_current_weather"
        args {
          fields {
            key: "location"
            value {
              string_value: "Boston, MA"
            }
          }
        }
      }
    }
  }
  ...
}

שלב 2: מספקים את פלט ה-API למודל

מפעילים את ה-API החיצוני ומעבירים את הפלט של ה-API בחזרה למודל.

בדוגמה הבאה אנחנו משתמשים בנתונים סינתטיים כדי לדמות מטען ייעודי (payload) של תגובה מ-API חיצוני, ושולחים את הפלט בחזרה למודל:

REST

PROJECT_ID=myproject
MODEL_ID=gemini-2.5-flash
LOCATION="us-central1"

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
-d '{
"contents": [
{
  "role": "user",
  "parts": {
    "text": "What is the weather in Boston?"
  }
},
{
  "role": "model",
  "parts": [
    {
      "functionCall": {
        "name": "get_current_weather",
        "args": {
          "location": "Boston, MA"
        }
      }
    }
  ]
},
{
  "role": "user",
  "parts": [
    {
      "functionResponse": {
        "name": "get_current_weather",
        "response": {
          "temperature": 20,
          "unit": "C"
        }
      }
    }
  ]
}
],
"tools": [
{
  "function_declarations": [
    {
      "name": "get_current_weather",
      "description": "Get the current weather in a specific location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city name of the location for which to get the weather."
          }
        },
        "required": [
          "location"
        ]
      }
    }
  ]
}
]
}'

‫Vertex AI SDK ל-Python

function_response_contents = []
function_response_parts = []

# Iterates through the function calls in the response in case there are parallel function call requests
for function_call in response.candidates[0].function_calls:
    print(f"Function call: {function_call.name}")

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    if (function_call.args['location'] == "Boston, MA"):
      api_response = { "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy" }
    if (function_call.args['location'] == "San Francisco, CA"):
      api_response = { "location": "San Francisco, CA", "temperature": 58, "description": "Sunny" }

    function_response_parts.append(
        Part.from_function_response(
            name=function_call.name,
            response={"contents": api_response}
        )
    )
    # Add the function call response to the contents
    function_response_contents = Content(role="user", parts=function_response_parts)

# Submit the User's prompt, model's response, and API output back to the model
response = model.generate_content(
  [
    Content( # User prompt
      role="user",
      parts=[
          Part.from_text("What is the weather like in Boston?"),
      ],
    ),
    response.candidates[0].content,  # Function call response
    function_response_contents   # API output
  ],
  tools=[
    Tool(
      function_declarations=[get_current_weather_func],
    )
  ],
)
# Get the model summary response
print(response.text)

לשיטות מומלצות שקשורות להפעלת API, כדאי לעיין במאמר שיטות מומלצות – הפעלת API.

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

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

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

It is currently 38 degrees Fahrenheit in Boston, MA with partly cloudy skies.

בקשה להפעלת פונקציה עם מחשבות

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

Python

# Call the model with function declarations
# ...Generation config, Configure the client, and Define user prompt (No changes)

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

# See thought signatures
for part in response.candidates[0].content.parts:
  if not part.text:
    continue
  if part.thought and part.thought_signature:
    print("Thought signature:")
    print(part.thought_signature)

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

Python

# Create user friendly response with function result and call the model again
# ...Create a function response part (No change)

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

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

print(final_response.text)

כשמחזירים חתימות של מחשבות, צריך לפעול לפי ההנחיות הבאות:

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

מידע נוסף על מגבלות השימוש בחתימות של תהליכי חשיבה ועל מודלים של תהליכי חשיבה

בקשות מקבילות להפעלת פונקציות

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

REST

בדוגמה הזו מוצג תרחיש עם פונקציה אחת של get_current_weather. ההנחיה למשתמש היא "קבלת פרטים על מזג האוויר בבוסטון ובסן פרנסיסקו". המודל מציע שתי קריאות מקבילות לפונקציה get_current_weather: אחת עם הפרמטר Boston והשנייה עם הפרמטר San Francisco.

מידע נוסף על פרמטרים של בקשות זמין במאמר בנושא Gemini API.

{
"candidates": [
  {
    "content": {
      "role": "model",
      "parts": [
        {
          "functionCall": {
            "name": "get_current_weather",
            "args": {
              "location": "Boston"
            }
          }
        },
        {
          "functionCall": {
            "name": "get_current_weather",
            "args": {
              "location": "San Francisco"
            }
          }
        }
      ]
    },
    ...
  }
],
...
}

בדוגמה הבאה אפשר לראות איך מספקים את פלט הפונקציה למודל. מחליפים את my-project בשם הפרויקט ב- Google Cloud .

בקשה למודל

PROJECT_ID=my-project
MODEL_ID=gemini-2.5-flash
LOCATION="us-central1"
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
-d '{
"contents": [
{
  "role": "user",
  "parts": {
    "text": "What is difference in temperature in Boston and San Francisco?"
  }
},
{
  "role": "model",
  "parts": [
    {
      "functionCall": {
        "name": "get_current_weather",
        "args": {
          "location": "Boston"
        }
      }
    },
    {
      "functionCall": {
        "name": "get_current_weather",
        "args": {
          "location": "San Francisco"
        }
      }
    }
  ]
},
{
  "role": "user",
  "parts": [
    {
      "functionResponse": {
        "name": "get_current_weather",
        "response": {
          "temperature": 30.5,
          "unit": "C"
        }
      }
    },
    {
      "functionResponse": {
        "name": "get_current_weather",
        "response": {
          "temperature": 20,
          "unit": "C"
        }
      }
    }
  ]
}
],
"tools": [
{
  "function_declarations": [
    {
      "name": "get_current_weather",
      "description": "Get the current weather in a specific location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city name of the location for which to get the weather."
          }
        },
        "required": [
          "location"
        ]
      }
    }
  ]
}
]
}'
  

התשובה בשפה טבעית שנוצרה על ידי המודל דומה לתשובה הבאה:

תשובה מהמודל

[
{
    "candidates": [
        {
            "content": {
                "parts": [
                    {
                        "text": "The temperature in Boston is 30.5C and the temperature in San Francisco is 20C. The difference is 10.5C. \n"
                    }
                ]
            },
            "finishReason": "STOP",
            ...
        }
    ]
    ...
}
]
  

Python

בדוגמה הזו מופיע תרחיש עם פונקציה אחת של get_current_weather. ההנחיה למשתמש היא "What is the weather like in Boston and San Francisco?" (מה מזג האוויר בבוסטון ובסן פרנסיסקו?).

מחליפים את my-project בשם הפרויקט ב- Google Cloud .

import vertexai
from vertexai.generative_models import (
    Content,
    FunctionDeclaration,
    GenerationConfig,
    GenerativeModel,
    Part,
    Tool,
    ToolConfig
)

# Initialize Vertex AI
# TODO(developer): Update the project
vertexai.init(project="my-project", location="us-central1")

# Initialize Gemini model
model = GenerativeModel(model_name="gemini-2.5-flash")

# Manual function declaration
get_current_weather_func = FunctionDeclaration(
    name="get_current_weather",
    description="Get the current weather in a given location",
    # Function parameters are specified in JSON schema format
    parameters={
        "type": "object",
        "properties": {
            "location": {
              "type": "string",
              "description": "The city name of the location for which to get the weather.",
              "default": {
                "string_value": "Boston, MA"
              }
          }
        },
    },
)

response = model.generate_content(
    contents = [
      Content(
        role="user",
          parts=[
              Part.from_text("What is the weather like in Boston and San Francisco?"),
          ],
      )
    ],
    generation_config = GenerationConfig(temperature=0),
    tools = [
      Tool(
        function_declarations=[get_current_weather_func],
      )
    ]
)

בדוגמה הבאה אפשר לראות איך מספקים את פלט הפונקציה למודל.

function_response_contents = []
function_response_parts = []

# You can have parallel function call requests for the same function type.
# For example, 'location_to_lat_long("London")' and 'location_to_lat_long("Paris")'
# In that case, collect API responses in parts and send them back to the model

for function_call in response.candidates[0].function_calls:
    print(f"Function call: {function_call.name}")

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    if (function_call.args['location'] == "Boston, MA"):
      api_response = { "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy" }
    if (function_call.args['location'] == "San Francisco, CA"):
      api_response = { "location": "San Francisco, CA", "temperature": 58, "description": "Sunny" }

    function_response_parts.append(
        Part.from_function_response(
            name=function_call.name,
            response={"contents": api_response}
        )
    )
    # Add the function call response to the contents
    function_response_contents = Content(role="user", parts=function_response_parts)

function_response_contents

response = model.generate_content(
    contents = [
        Content(
        role="user",
          parts=[
              Part.from_text("What is the weather like in Boston and San Francisco?"),
          ],
        ),  # User prompt
        response.candidates[0].content,  # Function call response
        function_response_contents,  # Function response
    ],
    tools = [
      Tool(
        function_declarations=[get_current_weather_func],
      )
    ]
)
# Get the model summary response
print(response.text)

Go

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
)

// parallelFunctionCalling shows how to execute multiple function calls in parallel
// and return their results to the model for generating a complete response.
func parallelFunctionCalling(w io.Writer, projectID, location, modelName string) error {
	// location = "us-central1"
	// modelName = "gemini-2.0-flash-001"
	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("failed to create GenAI client: %w", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)
	// Set temperature to 0.0 for maximum determinism in function calling.
	model.SetTemperature(0.0)

	funcName := "getCurrentWeather"
	funcDecl := &genai.FunctionDeclaration{
		Name:        funcName,
		Description: "Get the current weather in a given location",
		Parameters: &genai.Schema{
			Type: genai.TypeObject,
			Properties: map[string]*genai.Schema{
				"location": {
					Type: genai.TypeString,
					Description: "The location for which to get the weather. " +
						"It can be a city name, a city name and state, or a zip code. " +
						"Examples: 'San Francisco', 'San Francisco, CA', '95616', etc.",
				},
			},
			Required: []string{"location"},
		},
	}
	// Add the weather function to our model toolbox.
	model.Tools = []*genai.Tool{
		{
			FunctionDeclarations: []*genai.FunctionDeclaration{funcDecl},
		},
	}

	prompt := genai.Text("Get weather details in New Delhi and San Francisco?")
	resp, err := model.GenerateContent(ctx, prompt)

	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}
	if len(resp.Candidates) == 0 {
		return errors.New("got empty response from model")
	} else if len(resp.Candidates[0].FunctionCalls()) == 0 {
		return errors.New("got no function call suggestions from model")
	}

	// In a production environment, consider adding validations for function names and arguments.
	for _, fnCall := range resp.Candidates[0].FunctionCalls() {
		fmt.Fprintf(w, "The model suggests to call the function %q with args: %v\n", fnCall.Name, fnCall.Args)
		// Example response:
		// The model suggests to call the function "getCurrentWeather" with args: map[location:New Delhi]
		// The model suggests to call the function "getCurrentWeather" with args: map[location:San Francisco]
	}

	// Use synthetic data to simulate responses from the external API.
	// In a real application, this would come from an actual weather API.
	mockAPIResp1, err := json.Marshal(map[string]string{
		"location":         "New Delhi",
		"temperature":      "42",
		"temperature_unit": "C",
		"description":      "Hot and humid",
		"humidity":         "65",
	})
	if err != nil {
		return fmt.Errorf("failed to marshal function response to JSON: %w", err)
	}

	mockAPIResp2, err := json.Marshal(map[string]string{
		"location":         "San Francisco",
		"temperature":      "36",
		"temperature_unit": "F",
		"description":      "Cold and cloudy",
		"humidity":         "N/A",
	})
	if err != nil {
		return fmt.Errorf("failed to marshal function response to JSON: %w", err)
	}

	// Note, that the function calls don't have to be chained. We can obtain both responses in parallel
	// and return them to Gemini at once.
	funcResp1 := &genai.FunctionResponse{
		Name: funcName,
		Response: map[string]any{
			"content": mockAPIResp1,
		},
	}
	funcResp2 := &genai.FunctionResponse{
		Name: funcName,
		Response: map[string]any{
			"content": mockAPIResp2,
		},
	}

	// Return both API responses to the model allowing it to complete its response.
	resp, err = model.GenerateContent(ctx, prompt, funcResp1, funcResp2)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}
	if len(resp.Candidates) == 0 || len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("got empty response from model")
	}

	fmt.Fprintln(w, resp.Candidates[0].Content.Parts[0])
	// Example response:
	// The weather in New Delhi is hot and humid with a humidity of 65 and a temperature of 42°C. The weather in San Francisco ...

	return nil
}

תשובות פונקציה מרובות מצבים

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

  • תמונות: image/png, image/jpeg, image/webp
  • מסמכים: application/pdf, text/plain

כדי לכלול נתונים מרובי-אופנים בתשובה של פונקציה, צריך לכלול אותם כחלק אחד או יותר שמוטמעים בחלק functionResponse. כל חלק מולטימודאלי חייב להכיל inlineData או fileData. אם אתם מפנים לחלק מולטי-מודאלי מתוך שדה response מובנה, הוא חייב להכיל displayName ייחודי.

אפשר גם להפנות לחלק מולטימודאלי מתוך השדה המובנה response של החלק functionResponse באמצעות פורמט ההפניה של JSON‏ {"$ref": "<displayName>"}. המודל מחליף את ההפניה בתוכן מולטימודאלי במהלך עיבוד התשובה. אפשר להפנות לכל displayName רק פעם אחת בשדה המובנה response.

בדוגמה הבאה מוצגת הודעה שמכילה functionResponse לפונקציה בשם get_image וחלק מוטמע שמכיל נתוני תמונה. השדה functionResponse's response מפנה לחלק הזה של התמונה:

Python

from google import genai
from google.genai import types

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., 'green shirt')."
          }
      },
      "required": ["item_name"],
  },
)
tool_config = types.Tool(function_declarations=[get_image_declaration])

# 2. Send a message that triggers the tool
prompt = "Show me the green shirt I ordered last month."
response_1 = client.models.generate_content(
  model="gemini-3.1-pro-preview",
  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": "dress.jpg"},
}

function_response_multimodal_data = types.FunctionResponsePart(
  file_data=types.FunctionResponseFileData(
    mime_type="image/png",
    display_name="dress.jpg",
    file_uri="gs://cloud-samples-data/generative-ai/image/dress.jpg",
  )
)

# 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="tool",
    parts=[
        types.Part.from_function_response(
          name=function_call.name,
          response=function_response_data,
          parts=[function_response_multimodal_data]
        )
    ],
  )
]

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

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

REST

"contents": [
  ...,
  {
    "role": "user",
    "parts": [
      {
        "functionResponse": {
          "name": "get_image",
          "response": {
            "image_ref": {
              "$ref": "wakeupcat.jpg"
            }
          },
          "parts": [
            {
              "fileData": {
                "displayName": "wakeupcat.jpg",
                "mimeType": "image/jpeg",
                "fileUri": "gs://cloud-samples-data/vision/label/wakeupcat.jpg"
              }
            }
          ]
        }
      }
    ]
  }
]

העברת ארגומנטים של בקשה להפעלת פונקציה בסטרימינג

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

יש לתכונה הזו את המגבלות הבאות:

  • התכונה הזו זמינה בגרסאות API‏ v1 ו-v1beta1.

כדי להפעיל סטרימינג של ארגומנטים של בקשות להפעלת פונקציות, מגדירים את streamFunctionCallArguments ל-true בתוך toolConfig.functionCallingConfig כשקוראים ל-streamGenerateContent.

כשהאפשרות streamFunctionCallArguments מופעלת, תשובות ביניים יכילו אובייקט functionCall עם השדות partialArgs ו-willContinue. partialArgs מכיל מקטעי ארגומנטים כשהם נוצרים, ו-willContinue מציין אם צפויים עוד מקטעים לבקשה להפעלת פונקציה.

  • partialArgs: מערך של PartialArg אובייקטים, שכל אחד מהם מכיל:
    • jsonPath: מחרוזת JSONPath שמציינת את הנתיב לקטע הזה באובייקט הפרמטרים של הפונקציה. הנתיב יכול להצביע על ארגומנט (למשל $.location) או על רכיב בתוך ארגומנט אם הארגומנט הוא אובייקט (למשל $.location.latitude).
    • ערך לקטע, שיכול להיות numberValue,‏ stringValue,‏ boolValue או nullValue.
    • willContinue: ערך בוליאני באובייקט partialArgs. השדה הזה הוא true רק עבור קטעי stringValue כשערך המחרוזת מועבר בסטרימינג בחלקים, וצפויים עוד חלקים לארגומנט הזה.
  • willContinue: ערך בוליאני באובייקט functionCall. אם צפויים עוד true, more partialArgs לקריאה הכוללת לפונקציה בתגובות הבאות שמוזרמות. אם false או לא מופיע, זו התשובה הסופית שמועברת בסטרימינג לבקשה הנוכחית להפעלת פונקציה.

הדוגמה הבאה מציגה רצף של נתונים שמועברים בסטרימינג generateContent, שבהם הארגומנטים של בקשה להפעלת פונקציה יחידה מועברים בסטרימינג:

{
  "parts": [
    {
      "functionCall": {
        "name": "controlLight",
        "partialArgs": [
          {
            "jsonPath": "$.brightness",
            "numberValue": 50
          }
        ],
        "willContinue": true
      }
    }
  ],
  "role": "model"
}
{
  "parts": [
    {
      "functionCall": {
        "partialArgs": [
          {
            "jsonPath": "$.colorTemperature",
            "stringValue": "warm",
            "willContinue": true
          }
        ],
        "willContinue": true
      }
    }
  ],
  "role": "model"
}
{
  "parts": [
    {
      "functionCall": {
        "partialArgs": [
          {
            "jsonPath": "$.colorTemperature"
          }
        ],
        "willContinue": true
      }
    }
  ],
  "role": "model"
}
{
  "parts": [
    {
      "functionCall": {}
    }
  ],
  "role": "model"
}

בדוגמה הבאה מוצגות תשובות שונות שמתקבלות להנחיה "מה ההבדל בטמפרטורה בין ניו דלהי לסן פרנסיסקו?" כשהארגומנטים של קריאות מקבילות לפונקציה מועברים בסטרימינג:

{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{
        "functionCall": {
          "name": "get_current_weather",
          "willContinue": true
        },
      }]
    }
  }],
}
{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{
        "functionCall": {
          "partialArgs": [{
            "jsonPath": "$.location",
            "stringValue": "New Delhi",
            "willContinue": true
          }],
          "willContinue": true
        }
      }]
    }
  }],
}
{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{
        "functionCall": {
          "partialArgs": [{
            "jsonPath": "$.location",
            "stringValue": ""
          }],
          "willContinue": true
        }
      }]
    }
  }],
}
{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{
        "functionCall": {
        }
      }]
    }
  }],
}
{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{
        "functionCall": {
          "name": "get_current_weather",
          "willContinue": true
        },
      }]
    }
  }],
}
{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{
        "functionCall": {
          "partialArgs": [{
            "jsonPath": "$.location",
            "stringValue": "San Francisco",
            "willContinue": true
          }],
          "willContinue": true
        }
      }]
    }
  }],
}
{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{
        "functionCall": {
          "partialArgs": [{
            "jsonPath": "$.location",
            "stringValue": ""
          }],
          "willContinue": true
        }
      }]
    }
  }],
}
{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{
        "functionCall": {
        }
      }]
    }
  }],
}

Python

from google import genai
from google.genai import types

client = genai.Client()

get_weather_declaration = types.FunctionDeclaration(
  name="get_weather",
  description="Gets the current weather temperature for a given location.",
  parameters={
      "type": "object",
      "properties": {"location": {"type": "string"}},
      "required": ["location"],
  },
)
get_weather_tool = types.Tool(function_declarations=[get_weather_declaration])

for chunk in client.models.generate_content_stream(
  model="gemini-3.1-pro-preview",
  contents="What's the weather in London and New York?",
  config=types.GenerateContentConfig(
      tools=[get_weather_tool],
      tool_config = types.ToolConfig(
          function_calling_config=types.FunctionCallingConfig(
              mode=types.FunctionCallingConfigMode.AUTO,
              stream_function_call_arguments=True,
          )
      ),
  ),
):
  function_call = chunk.function_calls[0]
  if function_call and function_call.name:
      print(f"{function_call.name}")
      print(f"will_continue={function_call.will_continue}")

מצבים של בקשה להפעלת פונקציה

אתם יכולים לקבוע איך המודל ישתמש בכלים שסיפקתם (הצהרות פונקציה) על ידי הגדרת המצב בתוך function_calling_config.

מצב תיאור
AUTO התנהגות ברירת המחדל של המודל. המודל מחליט אם לחזות קריאות לפונקציות או להגיב בשפה טבעית על סמך ההקשר. זהו המצב הגמיש ביותר, והוא מומלץ לרוב התרחישים.
VALIDATED (תצוגה מקדימה) המודל מוגבל לחיזוי של קריאות לפונקציות או של שפה טבעית, והוא מוודא שהסכימה של הפונקציה תואמת. אם לא מספקים את allowed_function_names, המודל בוחר מתוך כל הצהרות הפונקציות הזמינות. אם מספקים את allowed_function_names, המודל בוחר מתוך קבוצת הפונקציות המותרות. החל מ-Gemini 3, במצב הזה נאכפת גם הנוכחות של פרמטרים נדרשים.
ANY המודל מוגבל כך שתמיד יחזיר קריאה אחת או יותר לפונקציה, ומוודא שהסכימה של הפונקציה תואמת. אם לא מספקים את allowed_function_names, המודל בוחר מתוך כל הצהרות הפונקציות הזמינות. אם מספקים את allowed_function_names, המודל בוחר מתוך קבוצת הפונקציות המותרות. משתמשים במצב הזה כשצריך לקבל תשובה לבקשה להפעלת פונקציה לכל הנחיה (אם רלוונטי).
NONE אסור למודל לבצע קריאות לפונקציות. זה שווה ערך לשליחת בקשה ללא הצהרות פונקציה. אפשר להשתמש במצב הזה כדי להשבית זמנית את השימוש בפונקציות בלי להסיר את ההגדרות של הכלים.

בקשה להפעלת פונקציה בכפייה

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

בדוגמה הבאה, המודל נאלץ לחזות רק קריאות לפונקציה get_weather.

Python

response = model.generate_content(
    contents = [
      Content(
        role="user",
          parts=[
              Part.from_text("What is the weather like in Boston?"),
          ],
      )
    ],
    generation_config = GenerationConfig(temperature=0),
    tools = [
      Tool(
        function_declarations=[get_weather_func, some_other_function],
      )
    ],
    tool_config=ToolConfig(
        function_calling_config=ToolConfig.FunctionCallingConfig(
            # ANY mode forces the model to predict only function calls
            mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
            # Allowed function calls to predict when the mode is ANY. If empty, any of
            # the provided function calls will be predicted.
            allowed_function_names=["get_weather"],
        )
    )
)

דוגמאות לסכימת פונקציות

הצהרות הפונקציות תואמות לסכימת OpenAPI. אנחנו תומכים במאפיינים הבאים: type,‏ nullable,‏ required,‏ format,‏ description,‏ properties,‏ items,‏ enum,‏ anyOf,‏ $ref ו-$defs. אין תמיכה במאפיינים הנותרים.

פונקציה עם פרמטרים של אובייקט ומערך

בדוגמה הבאה נעשה שימוש במילון Python כדי להצהיר על פונקציה שמקבלת פרמטרים של אובייקט ושל מערך:

extract_sale_records_func = FunctionDeclaration(
  name="extract_sale_records",
  description="Extract sale records from a document.",
  parameters={
      "type": "object",
      "properties": {
          "records": {
              "type": "array",
              "description": "A list of sale records",
              "items": {
                  "description": "Data for a sale record",
                  "type": "object",
                  "properties": {
                      "id": {"type": "integer", "description": "The unique id of the sale."},
                      "date": {"type": "string", "description": "Date of the sale, in the format of MMDDYY, e.g., 031023"},
                      "total_amount": {"type": "number", "description": "The total amount of the sale."},
                      "customer_name": {"type": "string", "description": "The name of the customer, including first name and last name."},
                      "customer_contact": {"type": "string", "description": "The phone number of the customer, e.g., 650-123-4567."},
                  },
                  "required": ["id", "date", "total_amount"],
              },
          },
      },
      "required": ["records"],
  },
)
  

פונקציה עם פרמטר מסוג enum

בדוגמה הבאה נעשה שימוש במילון Python כדי להצהיר על פונקציה שמקבלת פרמטר של מספר שלם enum:

set_status_func = FunctionDeclaration(
  name="set_status",
  description="set a ticket's status field",
  # Function parameters are specified in JSON schema format
  parameters={
      "type": "object",
      "properties": {
        "status": {
          "type": "integer",
          "enum": [ "10", "20", "30" ],   # Provide integer (or any other type) values as strings.
        }
      },
  },
)
  

פונקציה עם ref ו-def

ההצהרה הבאה על פונקציית JSON משתמשת במאפיינים ref ו-defs:

{
  "contents": ...,
  "tools": [
    {
      "function_declarations": [
        {
          "name": "get_customer",
          "description": "Search for a customer by name",
          "parameters": {
            "type": "object",
            "properties": {
              "first_name": { "ref": "#/defs/name" },
              "last_name": { "ref": "#/defs/name" }
            },
            "defs": {
              "name": { "type": "string" }
            }
          }
        }
      ]
    }
  ]
}
  

הערות שימוש:

  • בניגוד לסכימת OpenAPI, צריך לציין את ref ואת defs בלי הסמל $.
  • ref חייב להתייחס לצאצא ישיר של defs; אסור להשתמש בהפניות חיצוניות.
  • העומק המקסימלי של סכימה מקוננת הוא 32.
  • עומק הרקורסיה ב-defs (הפניה עצמית) מוגבל לשנייה.

from_func עם פרמטר מערך

בדוגמת הקוד הבאה מוצהרת פונקציה שמכפילה מערך של מספרים, ונעשה שימוש ב-from_func כדי ליצור את סכימת FunctionDeclaration.

from typing import List

# Define a function. Could be a local function or you can import the requests library to call an API
def multiply_numbers(numbers: List[int] = [1, 1]) -> int:
  """
  Calculates the product of all numbers in an array.

  Args:
      numbers: An array of numbers to be multiplied.

  Returns:
      The product of all the numbers. If the array is empty, returns 1.
  """

  if not numbers:  # Handle empty array
      return 1

  product = 1
  for num in numbers:
      product *= num

  return product

multiply_number_func = FunctionDeclaration.from_func(multiply_numbers)

"""
multiply_number_func contains the following schema:

{'name': 'multiply_numbers',
  'description': 'Calculates the product of all numbers in an array.',
  'parameters': {'properties': {'numbers': {'items': {'type': 'INTEGER'},
    'description': 'list of numbers',
    'default': [1.0, 1.0],
    'title': 'Numbers',
    'type': 'ARRAY'}},
  'description': 'Calculates the product of all numbers in an array.',
  'title': 'multiply_numbers',
  'property_ordering': ['numbers'],
  'type': 'OBJECT'}}
"""
  

שיטות מומלצות להפעלת פונקציות

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

לכתוב שמות ברורים ומפורטים של פונקציות, תיאורים של פרמטרים והוראות

  • שמות של פונקציות צריכים להתחיל באות או בקו תחתון, ולהכיל רק את התווים a-z,‏ A-Z,‏ 0-9, קווים תחתונים, נקודות או מקפים, באורך של עד 64 תווים.

  • חשוב לנסח את התיאורים של הפונקציות והפרמטרים בצורה ברורה ומדויקת. המודל מסתמך על הנתונים האלה כדי לבחור את הפונקציה הנכונה ולספק ארגומנטים מתאימים. לדוגמה, לפונקציה book_flight_ticket יכול להיות התיאור book flight tickets after confirming users' specific requirements, such as time, departure, destination, party size and preferred airline

שימוש בפרמטרים עם הקלדה חזקה

אם ערכי הפרמטרים הם מתוך קבוצה סופית, מוסיפים שדה enum במקום להוסיף את קבוצת הערכים לתיאור. אם ערך הפרמטר הוא תמיד מספר שלם, צריך להגדיר את הסוג כ-integer ולא כ-number.

בחירת כלי

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

אם תספקו כלים גנריים ברמה נמוכה (כמו bash), יכול להיות שהמודל ישתמש בכלי לעיתים קרובות יותר, אבל עם פחות דיוק. אם תספקו כלי ספציפי ברמה גבוהה (כמו get_weather), המודל יוכל להשתמש בכלי בצורה מדויקת יותר, אבל יכול להיות שהוא לא ישתמש בכלי לעיתים קרובות.

שימוש בהוראות המערכת

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

הנדסת הנחיות

כדי לקבל את התוצאות הטובות ביותר, כדאי להוסיף לפני ההנחיה למשתמש את הפרטים הבאים:

  • הקשר נוסף למודל – לדוגמה, You are a flight API assistant to help with searching flights based on user preferences.
  • פרטים או הוראות לגבי אופן השימוש בפונקציות ומתי להשתמש בהן – לדוגמה, Don't make assumptions on the departure or destination airports. Always use a future date for the departure or destination time.
  • הוראות לשאילת שאלות הבהרה אם שאילתות המשתמשים לא ברורות – לדוגמה, Ask clarifying questions if not enough information is available.

שימוש בהגדרות של הדור

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

שימוש בפלט מובנה

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

אימות הקריאה ל-API

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

שימוש בחתימות מחשבה

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

תמחור

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

במקרה הזה, קלט טקסט (הנחיה) מתייחס להנחיית המשתמש בתור הנוכחי של השיחה, להצהרות הפונקציה בתור הנוכחי של השיחה ולהיסטוריית השיחה. היסטוריית השיחה כוללת את השאילתות, הקריאות לפונקציות והתשובות לפונקציות של תורות קודמות בשיחה. ‫Vertex AI מקצר את היסטוריית השיחות ל-32,000 תווים.

פלט טקסט (תגובה) מתייחס לקריאות לפונקציות ולתגובות הטקסטואליות של תור השיחה הנוכחי.

תרחישים לדוגמה לשימוש בהפעלת פונקציות

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

תרחיש לדוגמה תיאור לדוגמה קישור לדוגמה
שילוב עם ממשקי API חיצוניים קבלת מידע על מזג האוויר באמצעות API מטאורולוגי מדריך ל-Notebook
המרת כתובות לקואורדינטות של קו רוחב/אורך מדריך ל-Notebook
המרת מטבעות באמצעות API של שער חליפין Codelab
יצירת צ'אט בוטים מתקדמים לענות על שאלות של לקוחות לגבי מוצרים ושירותים מדריך ל-Notebook
יצירת עוזר וירטואלי שיענה על שאלות בנושאים פיננסיים וחדשותיים לגבי חברות מדריך ל-Notebook
מבנה ושליטה בבקשות להפעלת פונקציות חילוץ ישויות מובְנות מנתוני יומן גולמיים מדריך ל-Notebook
חילוץ פרמטר אחד או יותר מקלט של משתמש מדריך ל-Notebook
טיפול ברשימות ובמבני נתונים מקוננים בהפעלות של פונקציות מדריך ל-Notebook
איך מטפלים בהתנהגות של בקשות להפעלת פונקציה טיפול בקריאות לפונקציות מקבילות ובתשובות מדריך ל-Notebook
ניהול הפונקציות שהמודל יכול להפעיל ומתי מדריך ל-Notebook
שאילתות במסדי נתונים בשפה טבעית המרת שאלות בשפה טבעית לשאילתות SQL ב-BigQuery אפליקציה לדוגמה
בקשה להפעלת פונקציה מולטי-מודאלית שימוש בתמונות, בסרטונים, באודיו ובקובצי PDF כקלט להפעלת קריאות לפונקציות מדריך ל-Notebook

הנה עוד כמה תרחישי שימוש:

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

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

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

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

המאמרים הבאים