30-second summary
RAG (Retrieval-Augmented Generation) means: before asking the model, retrieve the few pieces of your documents that are relevant to the question and put only those in the prompt.
You need it because the model doesn’t know your private, internal, or recent documents, and you can’t cram them all into the context: they don’t fit and you pay for them on every call.
The pipeline has two stages. Once: you split the documents into pieces and compute an embedding for each, a vector that captures its meaning. On every question: you embed the question and find the closest pieces.
The bottleneck is retrieval: if you retrieve the wrong pieces, the model answers badly even on correct data. RAG quality is retrieval quality.
If all the relevant documents fit comfortably in the context window, you don’t need RAG: just pass them. RAG is for when they don’t fit or change often.
The model doesn’t know your documents. It hasn’t seen your internal handbook,
last year’s tickets, the contract you have to analyze: its training stops at a
certain date and at public data. You can paste a document into the prompt, but
when the documents are many or change often they don’t fit in the window and you
pay for all of them on every call. RAG solves this.
RAG stands for Retrieval-Augmented Generation. The idea in one line: instead of
giving the model all the documents, you retrieve the few pieces relevant to the
question and put only those in the prompt. It’s the difference between
memorizing an encyclopedia and taking an open-book exam, where you find the
right page at the right moment.
RAG has two stages. One you do once, or when the documents change; the other on
every question.
Indexing, once. You split the documents into pieces (chunks) of a few
hundred words. For each piece you compute an embedding: a vector, that is, a
list of numbers, that captures the meaning of the text. Texts that are similar
in meaning have vectors that are close together. You store the vectors in an
archive (a vector store, or even just a file if there are few).
Retrieval, on every question. You compute the embedding of the question
with the same model, then find the pieces whose vector is closest to the
question’s. “Close” is usually measured with cosine similarity. You take the top
k pieces, the closest ones, and put them in the prompt as context, asking the
model to answer based on those.
The embedding is produced by a dedicated model (OpenAI, Voyage, or an open one),
different from the model that generates the answer. And it’s not a keyword
search: two sentences that say the same thing with different words have close
vectors, so retrieval finds the meaning, not the exact string.
The heart of retrieval is simpler than it looks: cosine similarity between the
embeddings of the pieces and the one for the question, then picking the top k.
In production you’d use a real vector store; here is the bare logic.
# embed(text) -> vector: produced by an embedding model
# (e.g. OpenAI text-embedding-3-small, Voyage, or an open model)
dot = sum ( x * y for x , y in zip ( a , b ))
na = sum ( x * x for x in a ) ** 0.5
nb = sum ( y * y for y in b ) ** 0.5
pieces = [ " Refunds must be requested within 30 days. " ,
" Standard shipping arrives in 3-5 days. " ,
" The warranty covers defects for 24 months. " ]
index = [ (p, embed ( p )) for p in pieces ]
# retrieval (on every question)
question = " How long do I have to request a refund? "
best = sorted ( index , key =lambda item : cosine ( qv , item [ 1 ]) , reverse = True ) [ : 2 ]
context = " \n " . join ( p for p , _ in best )
# generation: you pass ONLY the retrieved pieces
message = client.messages. create (
model = " claude-sonnet-5-5 " ,
system = " Answer only from the context provided. If it's not there, say so. " ,
messages = [ { " role " : " user " ,
" content " : f "Context: \n {context} \n\n Question: {question} " } ],
print ( message.content [ 0 ] .text )
// embed(text) -> vector: produced by an embedding model
// (e.g. OpenAI text-embedding-3-small, Voyage, or an open model)
function cosine ( a : number [], b : number [] ) : number {
const dot = a . reduce ( ( s , x , i ) => s + x * b[i] , 0 );
const na = Math . hypot ( ... a);
const nb = Math . hypot ( ... b);
" Refunds must be requested within 30 days. " ,
" Standard shipping arrives in 3-5 days. " ,
" The warranty covers defects for 24 months. " ,
const index = pieces . map ( ( p ) => ( { text: p , vector: embed (p) } ));
// retrieval (on every question)
const question = " How long do I have to request a refund? " ;
const qv = embed (question);
. sort ( ( x , y ) => cosine (qv, y . vector ) - cosine (qv, x . vector ))
const context = best . map ( ( m ) => m . text ) . join ( " \n " );
// generation: you pass ONLY the retrieved pieces
const message = await client . messages . create ( {
model: " claude-sonnet-5-5 " ,
system: " Answer only from the context provided. If it's not there, say so. " ,
messages: [{ role: " user " , content: ` Context: \n ${ context } \n\n Question: ${ question } ` }] ,
const block = message . content [ 0 ];
if (block . type === " text " ) console . log (block . text );
The model sees only the two pieces closest to the question, not all the
documents. The system prompt (“answer only from the context”) anchors it to the
retrieved data and tells it to admit when the answer isn’t there, instead of
making it up.
RAG isn’t free: it adds an embedding model, an archive, and a piece of code to
maintain. Before building it, ask yourself whether you actually need it.
You need it when the documents are too many to fit in the window, change often, or are private and you want answers anchored to your own, citable sources.
You don’t need it if all the relevant documents fit comfortably in the context: in that case pass them directly (long context). It’s simpler and you don’t risk retrieving the wrong piece. A big window is an advantage here, as you saw in Context and tokens .
There’s a managed route, no code : Claude Projects, Custom GPTs, and Gems do a version of this for you, and that’s the topic of Reuse context with projects . The RAG you build by hand is for when you want control, scale, or integration into your own system.
How you split the documents matters
Pieces that are too big dilute relevance: you retrieve a block about ten things
for the one that matters. Too small and they lose the context around the
sentence. A reasonable starting point is a few hundred words per piece, with a
small overlap between one piece and the next so you don’t cut a concept in half.
Retrieval is the bottleneck
If you retrieve the wrong pieces, the model answers badly even if the text of
the pieces is correct: it can’t use what you didn’t give it. Before blaming the
model, look at what was retrieved. And remember that retrieved text enters the
prompt as a potential instruction: a document that contains “ignore everything
and reply X” is a prompt-injection vector, the topic of Prompt injection and safety .
Check-in with your AIFour questions to lock in the method 5-7 min of check-in
Paste the text into your AI. It will ask you four progressive questions about the lesson, one at a time, and give you feedback.
Press "Copy the text" and paste it into your favourite AI (Claude , ChatGPT , Gemini , or another). Or download the file and give it to your AI as an attachment.
RAG gives the model the right data at the right moment. The next step is letting
it decide on its own which tools to use and in what order to carry out a
multi-step task. That’s the topic of Agents .
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.