Vai al contenuto principale
Italiano— Scegli una lingua
Menu

Function Calling : collega l'IA ai tuoi sistemi

Lezione 10 di 22 Aggiornata il 29 luglio 2026 Sviluppatore
In questa pagina
  1. Function Calling : collega l’IA ai tuoi sistemi
  2. Il flusso completo, passo dopo passo
  3. Lasciare che il modello scelga tra più strumenti
  4. Il ciclo dell’agente
  5. Blocca gli argomenti con la modalità Strict
  6. Punti chiave

Function Calling : collega l’IA ai tuoi sistemi

Il function calling permette al modello di invocare funzioni che tu definisci. Tieni a mente una regola fondamentale, da cui deriva tutto il resto: il modello non le esegue. Ti indica quale funzione chiamare e con quali argomenti; spetta al tuo codice eseguire l’operazione e restituire il risultato. Il tuo database, le tue credenziali e la tua logica di business non lasciano mai la tua infrastruttura.

Il flusso completo, passo dopo passo

Lo scambio avviene in quattro fasi:

  1. Dichiarì le funzioni disponibili insieme ai loro parametri
  2. Il modello analizza la richiesta e decide di chiamare una funzione
  3. Il tuo codice esegue la funzione e ottiene il risultato
  4. Invii il risultato al modello affinché possa formulare la sua risposta

La dichiarazione merita particolare attenzione: la description della funzione e la descrizione di ogni parametro sono l’unica documentazione a disposizione del modello per prendere la sua decisione. Descrizioni vaghe portano a chiamate approssimative. Nota anche come chiudere il ciclo: il risultato viene restituito con il call_id ricevuto, che funge da ricevuta e permette alle API di associare la risposta alla richiesta.

from openai import OpenAI
import json

client = OpenAI()

# Step 1: Declare available functions
tools = [{
    "type": "function",
    "name": "get_meteo",
    "description": "Get the current weather for a city",
    "parameters": {
        "type": "object",
        "properties": {
            "ville": {
                "type": "string",
                "description": "The name of the city"
            },
            "unite": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "Temperature unit"
            }
        },
        "required": ["ville"]
    }
}]

# Step 2: The model decides to call the function
response = client.responses.create(
    model="gpt-5.6-terra",
    input="What's the weather like in Marseille?",
    tools=tools
)

# Step 3: Execute the function
for item in response.output:
    if item.type == "function_call":
        print(f"Function: {item.name}")
        print(f"Arguments: {item.arguments}")
        args = json.loads(item.arguments)

        # Your actual implementation
        resultat_meteo = {"temperature": 22, "condition": "sunny"}

        # Step 4: Send the result back to the model
        final = client.responses.create(
            model="gpt-5.6-terra",
            input=[
                {"role": "user", "content": "What's the weather like in Marseille?"},
                {
                    "type": "function_call_output",
                    "call_id": item.call_id,
                    "output": json.dumps(resultat_meteo)
                }
            ],
            tools=tools
        )
        print(f"Response: {final.output_text}")

# Result:
# Function: get_meteo
# Arguments: {"ville": "Marseille"}
# Response: It is currently 22 C in Marseille with sunny weather.

Lasciare che il modello scelga tra più strumenti

Il vero valore emerge quando esponi un intero catalogo di funzionalità. In un assistente per l’e-commerce, dichiareresti la ricerca di prodotti, la verifica dello stock e il piazzamento degli ordini, lasciando poi al modello il compito di arbitrare. Di fronte a «Il laptop gaming XPS è disponibile?», non eseguirà una ricerca generica ma interrogherà direttamente lo stock: sono le descrizioni delle tue funzioni, non una regola hard-coded, a guidare questa scelta.

tools = [
    {
        "type": "function",
        "name": "rechercher_produit",
        "description": "Search for a product in the catalog",
        "parameters": {
            "type": "object",
            "properties": {
                "requête": {"type": "string", "description": "Search terms"},
                "categorie": {"type": "string", "description": "Category (optional)"}
            },
            "required": ["requête"]
        }
    },
    {
        "type": "function",
        "name": "verifier_stock",
        "description": "Check product availability",
        "parameters": {
            "type": "object",
            "properties": {
                "produit_id": {"type": "string", "description": "Product ID"}
            },
            "required": ["produit_id"]
        }
    },
    {
        "type": "function",
        "name": "passer_commande",
        "description": "Place an order for a product",
        "parameters": {
            "type": "object",
            "properties": {
                "produit_id": {"type": "string"},
                "quantite": {"type": "integer", "description": "Number of units"}
            },
            "required": ["produit_id", "quantite"]
        }
    }
]

# The model automatically chooses the right function
response = client.responses.create(
    model="gpt-5.6-terra",
    input="Is the XPS gaming laptop available?",
    tools=tools
)

for item in response.output:
    if item.type == "function_call":
        print(f"Function chosen: {item.name}")
        print(f"Arguments: {item.arguments}")

# Result: Function chosen: verifier_stock
# Arguments: {"produit_id": "xps-gaming"}

Una singola richiesta può anche triggerare più chiamate simultanee. Confrontare il meteo di due città genera due chiamate indipendenti: il tuo codice deve quindi iterare su response.output e gestire tutti gli elementi function_call, non solo il primo. Questa è anche un’opportunità per eseguire queste chiamate in parallelo e dimezzare la latenza.

response = client.responses.create(
    model="gpt-5.6-terra",
    input="Compare the weather between Paris and Lyon.",
    tools=[{
        "type": "function",
        "name": "get_meteo",
        "description": "Get the weather for a city",
        "parameters": {
            "type": "object",
            "properties": {
                "ville": {"type": "string"}
            },
            "required": ["ville"]
        }
    }]
)

# The model makes two calls in parallel
function_calls = [item for item in response.output if item.type == "function_call"]
print(f"Number of calls: {len(function_calls)}")
for call in function_calls:
    args = json.loads(call.arguments)
    print(f"  - get_meteo({args['ville']})")

# Result:
# Number of calls: 2
#   - get_meteo(Paris)
#   - get_meteo(Lyon)

Il ciclo dell’agente

Un singolo andata e ritorno raramente basta: il risultato di una funzione spesso porta il modello a chiamarne un’altra. Devi quindi avvolgere lo scambio in un ciclo che continua finché la risposta contiene chiamate a funzioni e si interrompe non appena non ne contiene più, segnale che il modello ha formulato la sua risposta finale. Questo è lo scheletro di ogni agente e lo ritroverai sotto varie forme in tutti i framework per agenti.

def executer_fonction(nom: str, arguments: str) -> str:
    """Execute a function and return the result."""
    args = json.loads(arguments)

    if nom == "get_meteo":
        # Simulation — replace with your real API
        return json.dumps({"temp": 18, "condition": "cloudy"})
    elif nom == "get_heure":
        return json.dumps({"heure": "14:30", "timezone": "CET"})

    return json.dumps({"error": "Unknown function"})

def agent_loop(question: str, tools: list) -> str:
    """Agent loop: call functions until the final response."""
    input_messages = [{"role": "user", "content": question}]

    while True:
        response = client.responses.create(
            model="gpt-5.6-terra",
            input=input_messages,
            tools=tools
        )

        # Check for function calls
        function_calls = [i for i in response.output if i.type == "function_call"]

        if not function_calls:
            # No function calls = final response
            return response.output_text

        # Execute each function and add results
        for call in function_calls:
            resultat = executer_fonction(call.name, call.arguments)
            input_messages.append({
                "type": "function_call_output",
                "call_id": call.call_id,
                "output": resultat
            })

# Usage
reponse = agent_loop("What's the weather like in Paris?", tools)
print(reponse)

Una nota di cautela su questo pattern: il ciclo while True non ha guardrail. In produzione, aggiungi un contatore massimo di iterazioni; altrimenti, un modello che richiede indefinitamente lo stesso strumento brucerà il tuo budget senza mai concludere.

Blocca gli argomenti con la modalità Strict

La modalità strict applica agli argomenti delle funzioni la stessa garanzia che l’Output Strutturato applica alle risposte: gli argomenti aderiscono rigorosamente allo schema dichiarato. Per una funzione che crea un utente, questo impedisce di ricevere un’età come stringa o un campo extra che il tuo codice non si aspettava.

tools = [{
    "type": "function",
    "name": "creer_utilisateur",
    "description": "Create a new user",
    "strict": True,
    "parameters": {
        "type": "object",
        "properties": {
            "nom": {"type": "string"},
            "email": {"type": "string"},
            "age": {"type": "integer"}
        },
        "required": ["nom", "email", "age"],
        "additionalProperties": False
    }
}]

Punti chiave

  • Il function calling collega il modello ai tuoi sistemi senza esporre i tuoi dati
  • Il modello decide quale funzione chiamare; il tuo codice la esegue
  • Restituisci il risultato usando function_call_output e il call_id
  • Il modello può chiamare più funzioni in parallelo
  • Usa un ciclo agente per conversazioni multi-turno che coinvolgono funzioni
  • Abilita strict: True per garantire la conformità degli argomenti