Riepilogo in 30 secondi
Un agente è un modello che gira in un ciclo: decide, chiama uno strumento, legge il risultato, e ripete finché ritiene l’obiettivo raggiunto. Il ciclo è codice tuo, poche decine di righe.
Parti dalla soluzione più semplice: una chiamata sola, poi una catena di passi fissi. Passa a un agente solo quando i passi da fare dipendono da ciò che si scopre strada facendo.
I problemi tipici sono quattro: cicli che non finiscono, errori che si accumulano passo dopo passo, costi che crescono a ogni giro, azioni che non si possono annullare.
Le difese sono poche e concrete: un tetto ai passi, l’approvazione umana per le azioni con conseguenze, strumenti con i permessi minimi, un log di tutto.
Ogni risultato di uno strumento è testo non fidato che entra nel prompt dell’agente: la sicurezza è quella di Prompt injection , con la posta più alta.
Nella lezione sul tool use
hai visto un giro: il modello chiede uno strumento, tu lo esegui, lui risponde.
Alla fine ti ho detto che in un caso reale diventa un ciclo. Un agente è
esattamente quel ciclo, lasciato andare avanti per più giri. Tutto il resto
si costruisce attorno a quel ciclo.
Un agente Un programma in cui un modello sceglie da solo i passi successivi, chiamando strumenti, finché decide di aver finito o raggiunge un limite.
è un modello che chiama strumenti in un ciclo finché l’obiettivo è raggiunto. Tu
gli dai un obiettivo («scopri perché l’ordine 4471 è in ritardo e dimmi cosa
fare») e un insieme di strumenti. Lui decide quale usare per primo, guarda cosa
torna, decide il passo dopo. Nessuno ha scritto in anticipo la sequenza.
Il ciclo ha tre mosse che si ripetono. Pianifica : il modello ragiona su cosa
manca per arrivare all’obiettivo. Agisce : chiede uno strumento. Osserva :
tu esegui e gli rimandi il risultato, che diventa parte della conversazione. Poi
si ricomincia, e il ciclo si ferma quando il modello risponde senza chiedere
altri strumenti (stop_reason vale end_turn) o quando lo fermi tu.
Questo è un agente completo per un assistente ordini. Ha due strumenti: uno che
legge (cerca_ordine) e uno con conseguenze reali (rimborsa_ordine). Le
funzioni cerca_ordine e rimborsa_ordine sono tue, qui non le scrivo.
client = anthropic. Anthropic ()
RICHIEDONO_OK = { " rimborsa_ordine " } # azioni con conseguenze
" description " : " Restituisce stato e dettagli di un ordine dato il suo id. " ,
" input_schema " : { " type " : " object " ,
" properties " : { " id " : { " type " : " string " }},
{ " name " : " rimborsa_ordine " ,
" description " : " Rimborsa un ordine. Azione irreversibile. " ,
" input_schema " : { " type " : " object " ,
" properties " : { " id " : { " type " : " string " }},
funzioni = { " cerca_ordine " : cerca_ordine, " rimborsa_ordine " : rimborsa_ordine}
messages = [ { " role " : " user " , " content " : " L'ordine 4471 è in ritardo: sistemalo. " } ]
for passo in range ( MAX_PASSI ):
risposta = client.messages. create (
model = " claude-sonnet-5-5 " , max_tokens = 1024 ,
tools = tools , messages = messages ,
messages. append ( { " role " : " assistant " , " content " : risposta.content} )
if risposta.stop_reason != " tool_use " : # il modello ha finito
print ( risposta.content [ 0 ] .text )
for blocco in risposta.content:
if blocco.type != " tool_use " :
print ( f "[passo {passo} ] {blocco.name} ( {blocco.input} )" ) # log
if blocco.name in RICHIEDONO_OK and input ( " Procedo? [s/N] " ) != " s " :
esito, errore = " L'utente ha negato l'azione. " , True
esito, errore = str ( funzioni [ blocco.name ]( ** blocco.input )), False
risultati. append ( { " type " : " tool_result " , " tool_use_id " : blocco.id,
" content " : esito, " is_error " : errore} )
messages. append ( { " role " : " user " , " content " : risultati} )
print ( " Fermato: raggiunto il limite di passi. " )
import Anthropic from " @anthropic-ai/sdk " ;
import * as readline from " node:readline/promises " ;
const client = new Anthropic ();
const RICHIEDONO_OK = new Set ([ " rimborsa_ordine " ]); // azioni con conseguenze
const rl = readline . createInterface ( { input: process . stdin , output: process . stdout } );
const tools : Anthropic. Tool [] = [
description: " Restituisce stato e dettagli di un ordine dato il suo id. " ,
input_schema: { type: " object " , properties: { id: { type: " string " } }, required: [ " id " ] } },
{ name: " rimborsa_ordine " ,
description: " Rimborsa un ordine. Azione irreversibile. " ,
input_schema: { type: " object " , properties: { id: { type: " string " } }, required: [ " id " ] } },
const funzioni : Record < string , ( args : any ) => Promise < string >> = { cerca_ordine , rimborsa_ordine } ;
const messages : Anthropic. MessageParam [] = [
{ role: " user " , content: " L'ordine 4471 è in ritardo: sistemalo. " },
for ( let passo = 0 ; passo < MAX_PASSI && ! finito; passo ++ ) {
const risposta = await client . messages . create ( {
model: " claude-sonnet-5-5 " , max_tokens: 1024 , tools , messages ,
messages . push ({ role: " assistant " , content: risposta . content });
if (risposta . stop_reason !== " tool_use " ) { // il modello ha finito
const testo = risposta . content . find ( ( b ) => b . type === " text " );
if (testo && testo . type === " text " ) console . log (testo . text );
const risultati : Anthropic. ToolResultBlockParam [] = [];
for ( const blocco of risposta . content ) {
if (blocco . type !== " tool_use " ) continue ;
console . log ( ` [passo ${ passo } ] ` , blocco . name , blocco . input ); // log
let esito : string , errore = false ;
if ( RICHIEDONO_OK . has (blocco . name ) && ( await rl . question ( " Procedo? [s/N] " )) !== " s " ) {
esito = " L'utente ha negato l'azione. " ; errore = true ;
esito = await funzioni[blocco . name ](blocco . input );
risultati . push ({ type: " tool_result " , tool_use_id: blocco . id , content: esito, is_error: errore });
messages . push ({ role: " user " , content: risultati });
if ( ! finito) console . log ( " Fermato: raggiunto il limite di passi. " );
Nel ciclo ci sono già tre difese. MAX_PASSI impedisce che giri per sempre. Il
print è un log minimo di cosa ha fatto l’agente. E il rimborso passa da una
conferma umana: se rifiuti, il modello riceve un errore e può spiegarti cosa
sarebbe successo o proporre un’alternativa.
Prima di costruire un agente, sali la scala dal gradino più basso e fermati
appena funziona.
Una chiamata sola. Riassumere un testo, classificare un’email, estrarre campi da una fattura. Se basta un prompt ben scritto, finisce qui.
Una catena di passi fissi (workflow). Prima estrai i dati, poi li controlli, poi scrivi la risposta: la sequenza la decidi tu e il codice la esegue sempre uguale. È prevedibile, più economica e si testa meglio.
Un agente. Serve quando i passi da fare non si conoscono in anticipo: dipendono da cosa trovi. Capire perché un test fallisce, ricostruire la storia di un ordine, cercare in più fonti finché la risposta regge.
Il prezzo della flessibilità è la prevedibilità. Un workflow fa sempre lo stesso
percorso, un agente può farne uno diverso a ogni esecuzione, e per questo è più
difficile da testare e da spiegare quando sbaglia. Se riesci a disegnare i passi
su un foglio prima di cominciare, probabilmente ti serve un workflow.
Gli agenti falliscono in modi ricorrenti, e conviene conoscerli prima di
metterne uno in produzione.
Cicli. L’agente ripete lo stesso strumento con gli stessi argomenti perché il risultato non lo convince, e non ne esce. Senza un tetto ai passi gira finché non finisci i soldi o i token.
Errori che si compongono. Ogni passo ha una piccola probabilità di sbagliare, e uno sbaglio al passo tre inquina i passi dal quattro in poi, perché il modello costruisce sul risultato precedente. Più il compito è lungo, più cresce il rischio che l’esito finale sia sbagliato in modo plausibile.
Costo. A ogni giro rimandi tutta la conversazione, che si allunga con i risultati degli strumenti. Dieci giri non costano dieci volte una chiamata, costano di più, per il motivo visto in Il contesto in token .
Azioni irreversibili. Mandare una mail, cancellare un file, rimborsare un cliente: se l’agente sbaglia qui, non c’è un tasto per tornare indietro.
Ognuna di queste misure è piccola e si applica dal primo giorno.
Tetto ai passi (e, se serve, al budget di token). Quando scatta, l’agente si ferma e ti dice dov’è arrivato, invece di insistere.
Approvazione umana per le azioni con conseguenze. Le letture girano da sole, le scritture irreversibili aspettano un sì. È la regola da applicare per prima.
Strumenti con i permessi minimi. Se l’agente deve solo leggere ordini, il suo accesso al database è in sola lettura. Quello che non può fare non lo farà nemmeno quando sbaglia o viene ingannato.
Log completo. Registra ogni chiamata, argomenti e risultato. Quando un agente fa qualcosa di strano, il log è l’unico modo per capire in quale passo è andato fuori strada.
L’agente legge testo non fidato
Ogni risultato di uno strumento (una pagina web, un’email, un ticket) entra nel
prompt, e il modello potrebbe trattarlo come un’istruzione. Con un solo giro il
danno è limitato; con un agente che ha strumenti con effetti reali, un testo
malevolo può spingerlo a usarli. Rileggi Prompt injection e
sicurezza : i permessi minimi e
l’approvazione umana sono le tue difese anche qui, e in un agente contano di più.
Parti da un compito stretto
Un agente con tre strumenti e un obiettivo preciso è più affidabile di uno con
trenta strumenti e un obiettivo vago. Aggiungi capacità una alla volta, e solo
dopo aver visto dai log che l’agente sa usare bene quelle che ha già.
Verifica con la tua IAQuattro domande per fissare il metodo 5-7 min di verifica
Incolla il testo nella tua IA. Ti farà quattro domande progressive sulla lezione, una alla volta, e ti darà feedback.
Premi «Copia il testo» e incollalo nella tua IA preferita (Claude , ChatGPT , Gemini o un'altra). In alternativa scarica il file e daglielo come allegato.
Un agente è utile quanto gli strumenti che ha, e ogni strumento finora l’hai
scritto e collegato a mano. Esiste uno standard aperto per collegare modelli e
strumenti senza rifare l’integrazione ogni volta: è la prossima
lezione , su MCP.
AI-Guide
A free, bilingual (English and Italian) manual that teaches non-technical readers how to use conversational AI well, from the very first question through everyday productivity, work scenarios, and advanced topics. Audience: parents, teachers, professionals, students. Not engineers.
The canonical site is https://ai-guide.larosa.work. English is the default locale (`/en/`); every page is mirrored in Italian at the same path under `/it/`. URL slugs are identical across languages so any English URL below can be translated by replacing `/en/` with `/it/`.
Start here
Start here : Pick the path that fits your level. Get to where you need to go in the fastest way.Fundamentals
But what is AI? : Let's demystify the words "artificial intelligence". What it really is, what it isn't, why everyone is talking about it now.What is a prompt? : The word "prompt" explained without fluff. It's what you write to the AI to get an answer, and how you write it matters more than you'd think.Your first conversation : Open an AI and put what you've read into practice. No theory: a guided exercise for your first conversation.How does the AI "understand"? : A look behind the scenes. The AI doesn't really understand: it guesses the next word, one at a time. But it guesses so well that sometimes it feels like magic.When to trust it (and when not) : The AI is wrong with the same confidence as when it's right. Learning to recognize the cases and to verify is the difference between using it well and getting fooled.What you share when you use AI : What actually happens to your messages after you send them to ChatGPT or Claude? Who sees them, what stays, what you can control. And what you should never put in.Everyday use
Ask well : Four levers that make the difference between a vague answer and a useful one when you ask the AI.Photos, images, and files : Uploading a utility bill, a screenshot, a PDF. Modern AIs can see, and you can use that to read the world around you.Iterate the conversation : The first answer is rarely the right one. The move isn't rewriting from scratch, it's keeping the chat going.Learn something new : The AI as a personal tutor. Techniques to actually understand, not just get a reply.Summarize a long document : PDFs, articles, reports, books. How to ask for a summary that's actually useful, and how to know if you can trust it.Understanding something complicated : Bills, contracts, medical reports, regulations. The AI is an excellent translator of bureaucratese, if you use it well.Things NOT to do : AI helps with almost everything. But there are cases where delegating the decision is a bad idea, even when the answer looks right.Write better : The AI as editor on your draft, not as ghostwriter. Three patterns to use it without losing your voice.At work
AI as a thinking partner : Stress-test an idea before you propose it, anticipate objections, brainstorm with method. Without an explicit constraint AI confirms everything: the value comes from forcing it into discomfort.Company data and privacy : Whatever you paste into a public AI can leave your company. Three risk levels (red, yellow, green), what changes with Enterprise or Team plans, the NDA gut check, and what to do if your company has no policy yet.Working with data and tables : Cleaning messy data, Excel or Sheets formulas you can't remember, small analyses on extracts. AI is the right copilot for one-offs, but company data is still company data.Drafting professional documents : Proposals, briefs, reports. AI as a structured first draft, not as a ghostwriter who writes the whole thing.Hard emails : Saying no, responding to someone who messed up, giving delicate feedback. Where the wrong word costs.Preparing a meeting : Structured agenda, preparation brief, actionable extract, follow-up. AI works before and after; the meeting stays the human moment.Research for work : Mapping a new territory, synthesizing multiple sources, doing live research with citations. AI speeds you up a lot and hallucinates a lot, and method is what separates a solid deliverable from an embarrassing one.Reuse context with projects : Claude Projects, ChatGPT Projects, Gemini Gems (becoming skills): same mechanism, different names. You load once the context that recurs (who you are, what you do, how you write, reference files) and reuse it across every chat in that thread, instead of starting from scratch every time.Slides and presentations : Outline from a document, tight bullets, speaker notes. AI helps with content, not design; the default produces text-heavy slides, and that's the risk to neutralize.By profession
The bookings and cleaning calendar : A Google Sheets (or Excel) sheet with one row per booking, the nights calculation, a check for overlaps in the same room and the day's cleaning list. ChatGPT writes and explains the formulas, you paste them.Guest messages, in any language : From the pre-arrival message to a reply to a review that complains about noise, with ChatGPT translating and you checking facts, codes and promises.The house guide from a template : You turn your scattered notes (Wi-Fi, heating, rubbish sorting, parking, pharmacy) into a tidy welcome guide, with a fixed template and a simple way to keep it up to date.Set up ChatGPT for your B&B : You put your house facts, times and tone into ChatGPT once, and you decide what must never end up in the chat, starting with guests' documents.By profession : Chapters for specific jobs, built on the tasks you repeat every week, with the steps on the tool that job really uses.Claude Code on your notes folder : Thirty years of notes scattered in one folder per client become a handover document, with Claude Code reading the files in a copy, proposing a plan and writing only new files.Job reports and explaining it to the client : From notes scribbled after a job to a job report in a fixed format and an email in plain words for the client. The AI drafts, you check every line.Set up Claude, on your terms : You create a Claude Project with the rules of a technician who doesn't trust confident answers, decide what to upload and what never, and learn to clean a log before pasting it.When the AI doesn't know your machine : With a rare phone system the AI doesn't know how it works and tends to invent. How to ask for hypotheses instead of answers, and how to recognize a menu or a password that doesn't exist.The manual from the cabinet : You upload the scan of an old manual and ask questions of that document, with page number and exact quotation, then check on paper. And you build a quick sheet from it.Replying to citizens : From a citizen's request to a clear, courteous and correct reply, in plain language, with no personal data in the prompt.Fixing a letter and checking the facts : How to have Copilot revise a letter you already wrote (clarity, tone, errors) and how to check everything the AI may have invented, especially laws and articles.Minutes and circulars : From notes or a meeting transcript to minutes in the office format, and from a decision to an internal circular, checking that nothing was added that was never said.What you can do with Copilot, and what you can't : How to tell which Copilot your office has, what protects your data and what doesn't, what the law says about AI in public administration, and how to keep recurring instructions.Replying to customers and suppliers : A reply to a customer with a broken jar in the parcel and a quote request to a supplier, in four parts and in your own tone, without promises you cannot keep.Product descriptions and posts from your notes : From four lines of notes to a product card with a fixed template and an Instagram post, without Gemini inventing properties, certifications or health effects.Set up Gemini for your shop : You save your shop's instructions (products, tone, what never to promise) in Gemini once, as a skill or as a text to paste, and set the rule on customer data.The stock sheet : A Google Sheets file with quantity, reorder threshold and a formula that flags "Reorder", then a filter to see what to order and a supplier email written by Gemini from the filtered rows.The checked itinerary : Build an itinerary with Claude and have it checked against holidays, museum closures, connections and season. With the list of what Claude does not know, and where to verify it.The payment register in Excel : Claude designs the Excel sheet for deposits, balances and due dates, with the formulas and late-payment highlighting explained step by step. Then it helps when a formula breaks and with the monthly summary.The personalised quote : From your notes on a client to a quote in your agency's template, ready for Word. How to ask for variants and how to make Claude say what is missing instead of inventing it.Set up Claude for your agency : You create a Claude Project with the right instructions for a travel agency, upload three files and set the rule on client data. You do it once, then use it for quotes, itineraries and payments.Your work assistant : How to create a Project with the instructions for your job, step by step in Claude, in general terms in ChatGPT, and with an instructions document in Copilot. What to write, which files to upload, how to update it.For students
Ethics of studying : Eight lessons in, the question that closes the module: where does AI's help end and copying begin? The answer is a method of judgement.Notes from lectures and long texts : Audio transcription, slides, chapters, your own notes. How to compose course material into a study-ready form.Revise before an exam : Simulated oral exams, written tests with corrections, mind maps and flashcards. AI as a simulated professor that generates the pressure of the test.Sources and citations : The bibliography is where AI does the most damage in academic work. Telling a made-up citation from a real one is a skill you can learn.Study a new topic : Formal study against a fixed syllabus. AI as a tutor that stays within your textbook's frame, not one that drifts off.Translating and comparing texts : Translation is where AI looks perfect and can instead be sneaky. Use it as a study aid for the language, not as a translator you paste from.When AI tricks you : You're studying a topic for the first time, and the AI answers with confidence. How to notice it's wrong precisely when you can't know.Writing a thesis : A thesis isn't something you delegate. AI as a second reader that helps you build a months-long project without writing it for you.For teachers
Design a lesson : AI as a prep colleague, not a classroom replacement. Outline, critique of the outline, materials anchored to it. Three steps that give you time back.Differentiated materials by level : Same topic, three difficulty levels. The one-base-text, three-derivatives pattern keeps the fast and the slow students on board without the content drifting apart.Emails to families : Delicate emails to parents, from low grades to meeting requests. AI compresses the time, not the sensitivity. Three registers, a three-step pattern, reinforced privacy for minors.Ethics of teaching : Three axes of responsibility that stay yours when you use AI to teach: honesty about how you use it, the privacy of minors' data, and the grade you sign. The AI prepares, you answer for it.Explain in five different ways : The same idea presented in five different representations. Used in prep, but it earns its keep in class when the standard explanation doesn't land.Generate assessment questions : Building assessment questions with AI, from open-ended to multiple choice to problem-solving. The value is in the choice and the calibration of the distractors, not the volume.Grading with criteria : AI as a grading assistant, not a judge. Your rubric, a first pass on a sample, the teacher's check, the decision and the signature always yours.Inclusive materials (SEN) : Adapting materials for students with special educational needs isn't about making an easier version, it's about making it accessible. Where AI speeds things up and where the work stays with whoever knows the student.When students use AI : AI detectors are not proof. Three moves that work better: read the signals as hypotheses, redesign assignments so they hold up, talk to the student without accusing on a hunch.Going deeper
Agents : A model calling tools in a loop until the goal is met: how an agent works, when it's actually worth it, what can go wrong, and which limits to put on it.Choose the model : There's no best model, only the right one for your constraint. The main families and the criteria that matter, beyond this month's leaderboard.Context and tokens : What a token is and what the context window is: how much text fits in one call, what fills it, and what to do when it isn't enough.Costs and prompt caching : Where the cost of a model call comes from and how to reduce it: a smaller model, shorter context, batch processing and prompt caching.Evals: knowing whether it works : How to test an LLM-based feature: a small set of real cases, automatic checks and a judge, and a before/after comparison on every change.From chats to APIs : What changes when you call the model from your own code instead of the chat, a real first call in Python and TypeScript, and when the API is actually worth it.MCP and integrations : The Model Context Protocol: an open standard for connecting models and applications to tools and data, why it beats hand-built integrations, and how far to trust a server.A mini end-to-end project : Build, step by step, a small assistant that answers from your documents, with sources, defenses, evaluation and caching, putting together what you saw in the module.Privacy and data in APIs : What changes for your data when you move from chat to the API: commercial terms, minimizing personal data, GDPR basics, logs and secret keys.Prompt injection and safety : Instructions hidden in the data the model reads: direct and indirect injection, the risks once tools are involved, the defenses that work, and why there's no complete fix today.RAG: your own documents : Retrieving the right pieces from your documents and passing them into the prompt: what RAG is, how retrieval works, and when you actually need it instead of cramming everything into the context.System prompts and roles : The system prompt is the standing instruction you pass separately from the messages: the three roles, why to separate instructions from data, and why it isn't a security wall.Tool use and structured output : How to let the model act on the world and how to get data back in a fixed format your code can use, instead of free prose.What an API is, in five minutes : Request and response, endpoint, API key, JSON, status codes, rate limits and token billing: the minimum to know about APIs before you use a model from your own code.Reference
Glossary : The technical words you meet in the lessons, explained in two sentences. With a button to ask your AI to go deeper.About : AI-Guide is written by Fabrizio La Rosa. Here's what I do, where I come from, and why I decided to write this manual.Translations
The same manual is available in Italian at https://ai-guide.larosa.work/it/. Every English page has an Italian counterpart at the same path; replace `/en/` with `/it/` in any URL above to get the Italian version.
Optional
Sitemap : every public URL on the site.Privacy : what is and is not collected about readers.