> ## 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.

# Function Calling

> Permetti ai modelli di chat Venice di richiamare gli strumenti della tua applicazione con function calling compatibile con OpenAI e l'API chat completions.

Il function calling permette a un modello di scegliere chiamate strutturate a strumenti che la tua applicazione può eseguire. Il modello non esegue direttamente la funzione. Restituisce il nome della funzione e gli argomenti, il tuo codice esegue la funzione e tu invii il risultato al modello.

Usa il function calling quando il modello ha bisogno di dati in tempo reale, azioni applicative, ricerche in un database o calcoli deterministici.

## Definizione di Base di uno Strumento

Definisci gli strumenti con l'array `tools` compatibile 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>

## Esecuzione dello Strumento

Quando il modello sceglie uno strumento, analizza `message.tool_calls`, effettua il parsing degli argomenti, esegui la funzione della tua applicazione e poi invia il risultato come messaggio `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)
```

## Scelta di un Modello

Il supporto al function calling dipende dal modello. Usa la pagina [Modelli di Testo](/models/text) o l'[API Modelli](/api-reference/endpoint/models/list) per trovare modelli con `supportsFunctionCalling`.

<Warning>
  Considera gli argomenti degli strumenti come input non attendibile. Convalida gli argomenti prima di usarli in query al database, comandi shell, pagamenti o altre operazioni con effetti collaterali.
</Warning>

## Consigli di Progettazione

* Mantieni i nomi e le descrizioni degli strumenti brevi e letterali.
* Usa JSON Schema per rendere semplice al modello la produzione di argomenti validi.
* Preferisci strumenti specifici con input chiari rispetto a un unico strumento generico con molti comportamenti opzionali.
* Restituisci risultati degli strumenti concisi affinché la risposta finale abbia contesto sufficiente senza sprecare token.

## Risorse Correlate

* [API Chat Completions](/api-reference/endpoint/chat/completions)
* [Modelli di Testo](/models/text)
* [Guida alle Risposte Strutturate](/guides/features/structured-responses)
* [Integrazione LangChain](/guides/integrations/langchain#function-calling-with-agents)
