La chiamata di funzione consente di definire funzioni personalizzate e di fornire agli LLM la possibilità di chiamarle per recuperare informazioni in tempo reale o interagire con sistemi esterni come database SQL o strumenti di assistenza clienti.
Per ulteriori informazioni concettuali sulla chiamata di funzione, consulta Introduzione alla chiamata di funzione.
Prima di iniziare
Per utilizzare i modelli aperti con Gemini Enterprise Agent Platform, devi eseguire i seguenti passaggi. Per utilizzare i modelli aperti su Gemini Enterprise Agent Platform, è necessario abilitare l'API Agent Platform (aiplatform.googleapis.com) e l'API Cloud Commerce Consumer Procurement (cloudcommerceconsumerprocurement.googleapis.com). Se hai già un progetto esistente con queste API abilitate, puoi utilizzarlo anziché crearne uno nuovo.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Gemini Enterprise Agent Platform and Cloud Commerce Consumer Procurement APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.- Vai alla scheda del modello in Model Garden per il modello che vuoi utilizzare, quindi fai clic su Abilita per abilitare il modello da utilizzare nel tuo progetto.
Ruoli obbligatori
Per ottenere le autorizzazioni necessarie per abilitare e utilizzare i modelli aperti, chiedi all'amministratore di concederti i seguenti ruoli IAM nel progetto:
- Utente della piattaforma agente (
roles/aiplatform.user) - Consumer Procurement Entitlement Manager (
roles/consumerprocurement.entitlementManager)
Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.
Potresti anche riuscire a ottenere le autorizzazioni richieste tramite i ruoli personalizzati o altri ruoli predefiniti.
Per saperne di più sulla concessione delle autorizzazioni e sulla configurazione delle policy dell'organizzazione per i modelli aperti, consulta Concedi agli utenti l'accesso ai modelli aperti.
Usa la chiamata di funzione
Gli esempi seguenti mostrano come utilizzare la chiamata di funzione.
Python
Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di Agent Platform per l'utilizzo delle librerie client.
Per eseguire l'autenticazione in Agent Platform, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
Prima di eseguire questo esempio, assicurati di impostare la variabile di ambiente OPENAI_BASE_URL.
Per saperne di più, consulta Autenticazione e credenziali.
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="MODEL", messages=[ {"role": "user", "content": "CONTENT"} ], tools=[ { "type": "function", "function": { "name": "FUNCTION_NAME", "description": "FUNCTION_DESCRIPTION", "parameters": PARAMETERS_OBJECT, } } ], tool_choice="auto", )
- MODEL: il nome del modello che vuoi utilizzare, ad esempio
zai-org/glm-5.2-maas. - CONTENT: il prompt dell'utente da inviare al modello.
- FUNCTION_NAME: il nome della funzione da chiamare.
- FUNCTION_DESCRIPTION: una descrizione della funzione.
- PARAMETERS_OBJECT: un dizionario che definisce i parametri della funzione, ad esempio:
{"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}
REST
Dopo aver configurato l'ambiente, puoi utilizzare REST per testare un prompt testuale. L'esempio seguente invia una richiesta all'endpoint del modello del publisher.
Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:
- PROJECT_ID: l'ID del tuo progetto Google Cloud.
- MODEL: il nome del modello che vuoi utilizzare, ad esempio
zai-org/glm-5.2-maas. - CONTENT: il prompt dell'utente da inviare al modello.
- FUNCTION_NAME: il nome della funzione da chiamare.
- FUNCTION_DESCRIPTION: una descrizione della funzione.
- PARAMETERS_OBJECT: un oggetto schema JSON che definisce i parametri della funzione, ad esempio:
{"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}
Metodo HTTP e URL:
POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions
Corpo JSON della richiesta:
{
"model": "MODEL",
"messages": [
{
"role": "user",
"content": "CONTENT"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "FUNCTION_NAME",
"description": "FUNCTION_DESCRIPTION",
"parameters": PARAMETERS_OBJECT
}
}
],
"tool_choice": "auto"
}
Per inviare la richiesta, scegli una di queste opzioni:
curl
Salva il corpo della richiesta in un file denominato request.json,
quindi esegui il comando seguente:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions"
PowerShell
Salva il corpo della richiesta in un file denominato request.json,
quindi esegui il comando seguente:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions" | Select-Object -Expand Content
Dovresti ricevere un codice di stato riuscito (2xx) e una risposta vuota.
Esempio
Di seguito è riportato l'output completo che potresti aspettarti dopo aver utilizzato la funzione get_current_weather per recuperare informazioni meteorologiche.
Python
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="zai-org/glm-5.2-maas", messages=[ { "role": "user", "content": "Which city has a higher temperature, Boston or new Delhi and by how much in F?" }, { "role": "assistant", "content": "I'll check the current temperatures for Boston and New Delhi in Fahrenheit and compare them. I'll call the weather function for both cities.", "tool_calls": [{"function":{"arguments":"{\"location\":\"Boston, MA\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"},{"function":{"arguments":"{\"location\":\"New Delhi, India\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"}] }, { "role": "tool", "content": "The temperature in Boston is 75 degrees Fahrenheit.", "tool_call_id": "get_current_weather" }, { "role": "tool", "content": "The temperature in New Delhi is 50 degrees Fahrenheit.", "tool_call_id": "get_current_weather" } ], tools=[ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } } ], tool_choice="auto" )
curl
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://aiplatform.googleapis.com/v1/projects/sample-project/locations/global/endpoints/openapi/chat/completions -d \ '{ "model": "zai-org/glm-5.2-maas", "messages": [ { "role": "user", "content": "Which city has a higher temperature, Boston or new Delhi and by how much in F?" }, { "role": "assistant", "content": "I'll check the current temperatures for Boston and New Delhi in Fahrenheit and compare them. I'll call the weather function for both cities.", "tool_calls": [{"function":{"arguments":"{\"location\":\"Boston, MA\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"},{"function":{"arguments":"{\"location\":\"New Delhi, India\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"}] }, { "role": "tool", "content": "The temperature in Boston is 75 degrees Fahrenheit.", "tool_call_id": "get_current_weather" }, { "role": "tool", "content": "The temperature in New Delhi is 50 degrees Fahrenheit.", "tool_call_id": "get_current_weather" } ], "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } } ], "tool_choice": "auto" }'
{ "choices": [ { "finish_reason": "stop", "index": 0, "logprobs": null, "message": { "content": "Based on the current weather data:\n\n- **Boston, MA**: 75°F \n- **New Delhi, India**: 50°F \n\n**Comparison**: \nBoston is **25°F warmer** than New Delhi. \n\n**Answer**: \nBoston has a higher temperature than New Delhi by 25 degrees Fahrenheit.", "role": "assistant" } } ], "created": 1750450289, "id": "2025-06-20|13:11:29.240295-07|6.230.75.101|-987540014", "model": "zai-org/glm-5.2-maas", "object": "chat.completion", "system_fingerprint": "", "usage": { "completion_tokens": 66, "prompt_tokens": 217, "total_tokens": 283 } }
Indicazioni specifiche per il modello
Le sezioni seguenti forniscono indicazioni specifiche per i modelli per la chiamata di funzione.
DeepSeek
I modelli DeepSeek non funzionano altrettanto bene con la chiamata di funzione se utilizzi un prompt di sistema. Per prestazioni ottimali, ometti il prompt di sistema quando utilizzi la chiamata di funzione con i modelli DeepSeek.
Llama
meta/llama3-405b-instruct-maas non supporta tool_choice = 'required'.
OpenAI
Quando utilizzi openai/gpt-oss-120b-maas, inserisci le definizioni degli strumenti nel
system prompt per prestazioni ottimali. Ad esempio:
{"messages": [ {"role": "system", "content": "You are a helpful assistant with access to the following functions. Use them if required:\n..."}, {"role": "user", "content": "What's the weather like in Boston?"}, ... ]}
Questo modello non supporta tool_choice = 'required' o la chiamata allo strumento con nome.
Passaggi successivi
- Scopri di più sull'output strutturato.
- Scopri di più su Ragionamento.
- Scopri di più sulle previsioni in batch.