Vai al contenuto principale
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:
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)
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);
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"]
          }
        }
      }
    ]
  }'

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
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 o l’API Modelli per trovare modelli con supportsFunctionCalling.
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.

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