I modelli linguistici di grandi dimensioni (LLM) a pesi aperti hanno cambiato il modo in cui i team di ingegneria pensano all'infrastruttura AI. A differenza delle API chiuse, in cui il provider controlla l'hardware, i pesi del modello e il programma di rilascio, i modelli a pesi aperti restituiscono tali decisioni a te. Scegli tu dove risiede il modello, come viene ottimizzato e quando — se mai — aggiornarlo a un nuovo checkpoint. Questo livello di proprietà è potente, ma significa anche che il lavoro di integrazione ricade interamente sulle tue spalle.

Se provieni da un'API gestita come GPT-4 di OpenAI o Claude di Anthropic, la buona notizia è che molti provider di hosting e motori di inferenza per modelli a pesi aperti parlano ormai la stessa lingua: POST HTTP, payload JSON e autenticazione tramite bearer token. La meccanica sembra familiare, ma i dettagli contano di più perché sei tu, e non il provider, a essere responsabile dell'affidabilità, del controllo dei costi e della modellazione del comportamento.

Le basi della chiamata API

Al suo interno, l'integrazione è una richiesta POST. Ti autentichi con un normale bearer token nell'header Authorization. Il corpo è un oggetto JSON e il suo campo più importante è l'array messages. Quell'array segue il familiare formato chat: ruoli alternati di system, user e assistant.

Ecco come appare una struttura di richiesta minima in pratica:

  • Imposta l'header Authorization su Bearer <your-token>.
  • Invia un payload JSON contenente almeno un identificatore model e una lista messages.
  • Includi max_tokens e temperature se desideri un controllo deterministico o creativo.

La risposta arriva con un array choices e un oggetto usage. Non ignorare il blocco usage. Contiene prompt_tokens, completion_tokens e il totale. Se stai facendo self-hosting, questo è il segnale per capire se una particolare interazione dell'utente è costosa. Se stai pagando un provider di inferenza di terze parti, questi sono i tuoi dati di fatturazione. In ogni caso, registrali fin dal primo giorno.

Lo streaming e perché dovresti usarlo

A nessuno piace fissare uno spinner di caricamento per tre secondi prima che appaia un singolo blocco di testo. Lo streaming risolve questo problema. Invece di aspettare che il modello completi l'intera generazione, il server emette i token man mano che vengono generati. Il tuo client riceve Server-Sent Events o risposte HTTP chunked e può renderizzare le parole non appena arrivano.

Abilita lo streaming impostando un flag stream: true nel tuo payload JSON. Lato client, di solito analizzerai lo stream riga per riga, cercando i prefissi data:. Se la connessione cade durante lo streaming, preparati a riconnetterti o a riprovare con una modalità non streaming. La latenza percepita della tua app di chat diminuisce drasticamente e gli utenti avranno la sensazione che il sistema stia pensando insieme a loro, piuttosto che elaborare la loro richiesta in modalità batch.

Function Calling per workflow del mondo reale

Un modello che restituisce solo testo semplice è utile, ma un modello in grado di invocare strumenti (tools) è molto più utile. Il function calling ti permette di definire uno schema JSON che descrive le operazioni disponibili — ad esempio, search_orders o update_profile — e il modello decide quando usarle. Invece di porre all'utente una domanda di follow-up, emette una chiamata a funzione strutturata con argomenti estratti dalla conversazione.

Per esempio, se un utente chiede: "Qual è stato il mio ultimo ordine?", il tuo schema potrebbe definire una funzione get_recent_orders con un parametro limit. Il modello restituisce una chiamata a uno strumento (tool call), il tuo backend esegue la query sul tuo database e tu reinserisci il risultato nel modello come messaggio di risposta della funzione. Il modello sintetizzerà quindi una risposta in linguaggio naturale.

Per implementarlo:

  • Fornisci un array tools o functions nel tuo payload.
  • Definisci ogni strumento con un name, una description e uno schema parameters.
  • Ispeziona la risposta alla ricerca di un "finish reason" per le chiamate agli strumenti o di un segnale simile.
  • Esegui la funzione nel tuo backend con una validazione rigorosa. Non fidarti mai degli output grezzi del modello per interrogare il database senza sanitizzazione.
  • Aggiungi il risultato della funzione alla cronologia dei messaggi e invia una richiesta di follow-up in modo che il modello possa produrre la risposta finale.

Questo pattern colma il divario tra il testo generativo e i sistemi deterministici. La tua IA può leggere calendari, interrogare API o attivare webhook senza che tu debba codificare manualmente ogni ramo.

Hardening per la produzione

L'esecuzione di modelli a pesi aperti in produzione ti espone alle stesse modalità di guasto di qualsiasi sistema distribuito, oltre ad alcune uniche. L'inferenza del modello è intensiva dal punto di vista computazionale e gli endpoint possono cedere sotto carico. Ecco come mantenere stabile la tua applicazione.

Errori e tentativi di ripristino (Retries)

  • 429 Too Many Requests: This is a rate-limit signal. Implement exponential backoff with jitter. Start with a short delay, double it on repeated 429s, and cap it at a few seconds so you do not hammer the server.
  • 5xx Server Errors: These are usually transient, especially if you are routing to a pool of GPU workers. Retry them, but put a hard ceiling on the number of attempts—three is a common default.
  • 4xx Client Errors: Do not retry these blindly. A 400 means your payload is malformed, a 401 means your token is wrong, and a 404 means the model ID does not exist on that endpoint. Fix the request instead of looping.

Timeouts and Hanging Processes

Inference can lag when queues build up or when a worker crashes mid-generation. Always set a request timeout. If your HTTP client default is infinity, change it. A reasonable starting point is 30 to 60 seconds for standard completions, shorter for health checks. If the timeout fires, treat it as a failure, log it, and decide whether to show the user a graceful error or retry on a fallback model.

Budget Control

Token counts translate directly into money or GPU hours. Log both prompt and completion tokens for every request. Track them per user, per feature, and per model version. Open-weight models let you swap checkpoints, but each checkpoint has its own cost profile and context-window size. Without logs, you will not know which part of your product is bleeding compute.

Behavior Shaping with System Messages

The system message is your first line of control. Use it to set the tone, enforce constraints, and inject static context that every user conversation should respect. Because open-weight models behave differently depending on their fine-tuning and system prompts, treat this field as a variable you A/B test. A vague system prompt yields vague answers. A precise one keeps the model on track—for instance, telling the assistant it only handles billing and returns, and should politely decline everything else.

Infrastructure Freedom and Data Sovereignty

One of the quietest benefits of open-weight models is custody. Your prompts and completions do not need to leave your environment. If you run the model on-premises or inside a virtual private cloud, you eliminate third-party data processing agreements and reduce exposure to training-data controversies. That matters for healthcare, finance, and any domain where a data leak is a compliance event.

Even if you use an external inference host, open weights give you portability. If the host changes pricing or terms, you can move the same model files to another provider or bring them in-house. You are not locked into a single API because there is only one company that holds the weights.

A Practical Starting Point

If you are integrating today, begin with a single model and a single endpoint. Wrap your HTTP client in a small abstraction layer that handles authentication, retries, and token logging. Add streaming next, because the user experience payoff is immediate. Then introduce one function call for a high-value workflow—status lookups, content moderation, or form filling. Monitor latency, error rates, and token spend for a week before you broaden the rollout.

Open-weight models demand more setup than a fully managed API, but they repay that effort with transparency, flexibility, and control. Build the integration carefully, instrument everything, and you will have an AI layer that behaves exactly the way your application needs.

Sources and further reading