> ## Documentation Index
> Fetch the complete documentation index at: https://docs.venice.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Llamada a funciones

> Permite que los modelos de chat de Venice llamen a las herramientas de tu aplicación con llamada a funciones compatible con OpenAI y la API de chat completions.

La llamada a funciones permite que un modelo elija llamadas estructuradas a herramientas que tu aplicación puede ejecutar. El modelo no ejecuta la función por sí mismo. Devuelve el nombre de la función y sus argumentos, tu código ejecuta la función y luego envías el resultado de vuelta al modelo.

Usa la llamada a funciones cuando el modelo necesite datos en vivo, acciones de la aplicación, búsquedas en bases de datos o cálculos deterministas.

## Definición básica de herramientas

Define herramientas con el arreglo `tools` compatible con OpenAI:

<CodeGroup>
  ```python Python theme={"system"}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["VENICE_API_KEY"],
      base_url="https://api.venice.ai/api/v1",
  )

  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get the current weather in a location",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "location": {
                          "type": "string",
                          "description": "City and state, such as San Francisco, CA",
                      }
                  },
                  "required": ["location"],
              },
          },
      }
  ]

  response = client.chat.completions.create(
      model="zai-org-glm-5",
      messages=[{"role": "user", "content": "What is the weather in San Francisco?"}],
      tools=tools,
  )

  print(response.choices[0].message.tool_calls)
  ```

  ```javascript Node.js theme={"system"}
  import OpenAI from "openai";

  const client = new OpenAI({
    apiKey: process.env.VENICE_API_KEY,
    baseURL: "https://api.venice.ai/api/v1",
  });

  const tools = [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get the current weather in a location",
        parameters: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "City and state, such as San Francisco, CA",
            },
          },
          required: ["location"],
        },
      },
    },
  ];

  const response = await client.chat.completions.create({
    model: "zai-org-glm-5",
    messages: [{ role: "user", content: "What is the weather in San Francisco?" }],
    tools,
  });

  console.log(response.choices[0].message.tool_calls);
  ```

  ```bash cURL theme={"system"}
  curl https://api.venice.ai/api/v1/chat/completions \
    -H "Authorization: Bearer $VENICE_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "zai-org-glm-5",
      "messages": [
        {"role": "user", "content": "What is the weather in San Francisco?"}
      ],
      "tools": [
        {
          "type": "function",
          "function": {
            "name": "get_weather",
            "description": "Get the current weather in a location",
            "parameters": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "City and state, such as San Francisco, CA"
                }
              },
              "required": ["location"]
            }
          }
        }
      ]
    }'
  ```
</CodeGroup>

## Ejecutar la herramienta

Cuando el modelo elige una herramienta, inspecciona `message.tool_calls`, analiza los argumentos, ejecuta la función de tu aplicación y luego envía el resultado de vuelta como un mensaje `tool`.

```python Python theme={"system"}
import json

message = response.choices[0].message
tool_call = message.tool_calls[0]
arguments = json.loads(tool_call.function.arguments)

weather = get_weather(arguments["location"])

follow_up = client.chat.completions.create(
    model="zai-org-glm-5",
    messages=[
        {"role": "user", "content": "What is the weather in San Francisco?"},
        message.model_dump(),
        {
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(weather),
        },
    ],
    tools=tools,
)

print(follow_up.choices[0].message.content)
```

## Elige un modelo

El soporte para llamada a funciones depende del modelo. Usa la página de [Modelos de Texto](/models/text) o la [API de Modelos](/api-reference/endpoint/models/list) para encontrar modelos con `supportsFunctionCalling`.

<Warning>
  Trata los argumentos de las herramientas como entrada no confiable. Valida los argumentos antes de usarlos en consultas a bases de datos, comandos de shell, pagos u otras operaciones con efectos secundarios.
</Warning>

## Consejos de diseño

* Mantén los nombres y descripciones de las herramientas breves y literales.
* Usa JSON Schema para facilitar que el modelo produzca argumentos válidos.
* Prefiere herramientas específicas con entradas claras en lugar de una herramienta amplia con muchos comportamientos opcionales.
* Devuelve resultados de herramienta concisos para que la respuesta final tenga suficiente contexto sin desperdiciar tokens.

## Recursos relacionados

* [API de Chat Completions](/api-reference/endpoint/chat/completions)
* [Modelos de Texto](/models/text)
* [Guía de Respuestas Estructuradas](/guides/features/structured-responses)
* [Integración con LangChain](/guides/integrations/langchain#function-calling-with-agents)
