La función de llamada a funciones te permite definir funciones personalizadas y proporcionar a los LLMs la capacidad de llamarlas para obtener información en tiempo real o interactuar con sistemas externos, como bases de datos SQL o herramientas de atención al cliente.
Para obtener más información conceptual sobre la llamada a funciones, consulta el artículo Introducción a la llamada a funciones.
Usar llamadas de función
En los siguientes ejemplos se muestra cómo usar la llamada a funciones.
Python
Antes de probar este ejemplo, sigue las Python instrucciones de configuración de la guía de inicio rápido de Vertex AI con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python de Vertex AI.
Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.
Antes de ejecutar este ejemplo, asegúrate de definir la variable de entorno OPENAI_BASE_URL
.
Para obtener más información, consulta Autenticación y credenciales.
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: el nombre del modelo que quieras usar, por ejemplo,
qwen/qwen3-next-80b-a3b-instruct-maas
. - CONTENT: la petición del usuario que se envía al modelo.
- FUNCTION_NAME: el nombre de la función a la que se debe llamar.
- FUNCTION_DESCRIPTION: una descripción de la función.
- PARAMETERS_OBJECT: diccionario que define los parámetros de la función. Por ejemplo:
{"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}
REST
Después de configurar tu entorno, puedes usar REST para probar una petición de texto. En el siguiente ejemplo se envía una solicitud al endpoint del modelo del editor.
Antes de usar los datos de la solicitud, haz las siguientes sustituciones:
- PROJECT_ID: tu ID de proyecto de Google Cloud.
- LOCATION: una región que admite modelos abiertos.
- MODEL: el nombre del modelo que quieras usar, por ejemplo,
qwen/qwen3-next-80b-a3b-instruct-maas
. - CONTENT: la petición del usuario que se envía al modelo.
- FUNCTION_NAME: el nombre de la función a la que se debe llamar.
- FUNCTION_DESCRIPTION: una descripción de la función.
- PARAMETERS_OBJECT: objeto de esquema JSON que define los parámetros de la función. Por ejemplo:
{"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}
Método HTTP y URL:
POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions
Cuerpo JSON de la solicitud:
{ "model": "MODEL", "messages": [ { "role": "user", "content": "CONTENT" } ], "tools": [ { "type": "function", "function": { "name": "FUNCTION_NAME", "description": "FUNCTION_DESCRIPTION", "parameters": PARAMETERS_OBJECT } } ], "tool_choice": "auto" }
Para enviar tu solicitud, elige una de estas opciones:
curl
Guarda el cuerpo de la solicitud en un archivo llamado request.json
y ejecuta el siguiente comando:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions"
PowerShell
Guarda el cuerpo de la solicitud en un archivo llamado request.json
y ejecuta el siguiente comando:
$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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions" | Select-Object -Expand Content
Deberías recibir un código de estado que indique que la operación se ha realizado correctamente (2xx) y una respuesta vacía.
Ejemplo
A continuación, se muestra el resultado completo que puedes obtener después de usar la función get_current_weather
para obtener información meteorológica.
Python
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="qwen/qwen3-next-80b-a3b-instruct-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://us-central1-aiplatform.googleapis.com/v1/projects/sample-project/locations/us-central1/endpoints/openapi/chat/completions -d \ '{ "model": "qwen/qwen3-next-80b-a3b-instruct-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": "qwen/qwen3-next-80b-a3b-instruct-maas", "object": "chat.completion", "system_fingerprint": "", "usage": { "completion_tokens": 66, "prompt_tokens": 217, "total_tokens": 283 } }
Información específica de modelos
En las siguientes secciones se ofrecen directrices específicas para cada modelo sobre las llamadas a funciones.
DeepSeek
Los modelos de DeepSeek no funcionan tan bien en las llamadas a funciones si usas una petición del sistema. Para obtener un rendimiento óptimo, omite la petición del sistema cuando uses la función de llamada con modelos de DeepSeek.
Llama
meta/llama3-405b-instruct-maas
no admite tool_choice = 'required'
.
OpenAI
Cuando uses openai/gpt-oss-120b-instruct-maas
y openai/gpt-oss-20b-instruct-maas
, coloca las definiciones de tus herramientas en la petición del sistema para obtener un rendimiento óptimo. Por ejemplo:
{"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?"}, ... ]}
Estos modelos no admiten tool_choice = 'required'
ni la llamada a herramientas con nombre.
Qwen
Los modelos de Qwen funcionan mejor cuando tool_choice
se define explícitamente como auto
o none
. Si no se define tool_choice
, es posible que el modelo no funcione tan bien.
Siguientes pasos
- Consulta información sobre la salida estructurada.
- Consulta información sobre Pensamiento.
- Consulta información sobre las predicciones por lotes.