Answer from your own documents with a small RAG

Learn LLMs · Beginner · 18 min · After Search by meaning with embeddings

How does a model answer from documents it was never trained on?

Run it against a real free API

The outputs in this lesson are simulated by a local mock server. To get real answers, create a free key at Mistral AI Free Plan and set these variables. Never put the key in your code.

export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_EMBED_MODEL=mistral-embed-2312
export LLM_API_KEY=your-key

Mistral AI Free Plan: what is free and how to get a key

  1. 1Guess

    Five help-page chunks are embedded, and so is the question "How do I get my money back for a damaged item?". Which chunk ranks first?
  2. 2Read

    Four moves

    RAG, retrieval-augmented generation, gives a model facts it was not trained on. Chunk: split your documents into short pieces. Embed: turn each chunk and the question into vectors. Retrieve: score every chunk against the question with cosine similarity and keep the top k. Augment: put those chunks into the prompt and ask the model to answer from them. The model never sees the whole library, only the few chunks that matter for this question.

  3. 3Code

    Chunk, embed and rank

    1 / 2
    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"math"
    	"net/http"
    	"os"
    	"sort"
    	"strings"
    )
    
    const docs = "To reset your password, open the login page and choose forgot password. We email you a reset link.\n\nParcel delivery takes three days. Use the tracking number from the courier to follow your order.\n\nDamaged items can be returned for a refund or a replacement. We send your money back within five days.\n\nA refund goes back to the card you paid with. Your invoice and payment receipt are on the billing page.\n\nThe API returns an error code when a request fails. Check the program logs to debug it."
    
    func post(path string, body map[string]any, out any) {
    	payload, _ := json.Marshal(body)
    	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+path, bytes.NewReader(payload))
    	req.Header.Set("Content-Type", "application/json")
    	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
    	res, err := http.DefaultClient.Do(req)
    	if err != nil {
    		fmt.Fprintln(os.Stderr, err)
    		os.Exit(1)
    	}
    	defer res.Body.Close()
    	json.NewDecoder(res.Body).Decode(out)
    }
    
    func embed(texts []string) [][]float64 {
    	var out struct {
    		Data []struct {
    			Embedding []float64 `json:"embedding"`
    		} `json:"data"`
    	}
    	post("/embeddings", map[string]any{"model": os.Getenv("LLM_EMBED_MODEL"), "input": texts}, &out)
    	vectors := make([][]float64, len(out.Data))
    	for i, d := range out.Data {
    		vectors[i] = d.Embedding
    	}
    	return vectors
    }
    
    func cosine(a, b []float64) float64 {
    	var dot, na, nb float64
    	for i := range a {
    		dot += a[i] * b[i]
    		na += a[i] * a[i]
    		nb += b[i] * b[i]
    	}
    	return dot / (math.Sqrt(na) * math.Sqrt(nb))
    }
    
    // retrieve returns the k chunks closest to the question, best first.
    func retrieve(question string, chunks []string, k int) ([]string, []float64) {
    	vectors := embed(append([]string{question}, chunks...))
    	scores := make([]float64, len(chunks))
    	order := make([]int, len(chunks))
    	for i := range chunks {
    		scores[i] = cosine(vectors[0], vectors[i+1])
    		order[i] = i
    	}
    	sort.SliceStable(order, func(a, b int) bool { return scores[order[a]] > scores[order[b]] })
    	var top []string
    	var topScores []float64
    	for _, i := range order[:k] {
    		top = append(top, chunks[i])
    		topScores = append(topScores, scores[i])
    	}
    	return top, topScores
    }
    
    func main() {
    	chunks := strings.Split(docs, "\n\n")
    	top, scores := retrieve("How do I get my money back for a damaged item?", chunks, 2)
    	for i, c := range top {
    		fmt.Printf("%.2f %s\n", scores[i], c)
    	}
    }
    

    Read the program. What will it print?

  4. 4Read

    The prompt

    The prompt has three parts: an instruction, the context and the question. The instruction says answer only from the context. Then comes a line Context: and one - chunk line per retrieved chunk. Last is the question. Tell the model to say "I don't know" when the answer is not in the context. Without that line it fills the gap from its training, and the answer looks grounded when it is not.

  5. 5Code

    The whole pipeline

    1 / 2
    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"math"
    	"net/http"
    	"os"
    	"sort"
    	"strings"
    )
    
    const docs = "To reset your password, open the login page and choose forgot password. We email you a reset link.\n\nParcel delivery takes three days. Use the tracking number from the courier to follow your order.\n\nDamaged items can be returned for a refund or a replacement. We send your money back within five days.\n\nA refund goes back to the card you paid with. Your invoice and payment receipt are on the billing page.\n\nThe API returns an error code when a request fails. Check the program logs to debug it."
    
    func post(path string, body map[string]any, out any) {
    	payload, _ := json.Marshal(body)
    	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+path, bytes.NewReader(payload))
    	req.Header.Set("Content-Type", "application/json")
    	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
    	res, err := http.DefaultClient.Do(req)
    	if err != nil {
    		fmt.Fprintln(os.Stderr, err)
    		os.Exit(1)
    	}
    	defer res.Body.Close()
    	json.NewDecoder(res.Body).Decode(out)
    }
    
    func embed(texts []string) [][]float64 {
    	var out struct {
    		Data []struct {
    			Embedding []float64 `json:"embedding"`
    		} `json:"data"`
    	}
    	post("/embeddings", map[string]any{"model": os.Getenv("LLM_EMBED_MODEL"), "input": texts}, &out)
    	vectors := make([][]float64, len(out.Data))
    	for i, d := range out.Data {
    		vectors[i] = d.Embedding
    	}
    	return vectors
    }
    
    func cosine(a, b []float64) float64 {
    	var dot, na, nb float64
    	for i := range a {
    		dot += a[i] * b[i]
    		na += a[i] * a[i]
    		nb += b[i] * b[i]
    	}
    	return dot / (math.Sqrt(na) * math.Sqrt(nb))
    }
    
    // retrieve returns the k chunks closest to the question, best first.
    func retrieve(question string, chunks []string, k int) ([]string, []float64) {
    	vectors := embed(append([]string{question}, chunks...))
    	scores := make([]float64, len(chunks))
    	order := make([]int, len(chunks))
    	for i := range chunks {
    		scores[i] = cosine(vectors[0], vectors[i+1])
    		order[i] = i
    	}
    	sort.SliceStable(order, func(a, b int) bool { return scores[order[a]] > scores[order[b]] })
    	var top []string
    	var topScores []float64
    	for _, i := range order[:k] {
    		top = append(top, chunks[i])
    		topScores = append(topScores, scores[i])
    	}
    	return top, topScores
    }
    
    func main() {
    	question := "How do I get my money back for a damaged item?"
    	top, _ := retrieve(question, strings.Split(docs, "\n\n"), 2)
    	fmt.Println("Retrieved:")
    	for _, c := range top {
    		fmt.Println("-", c)
    	}
    
    	prompt := "Answer only from the context. If the answer is not there, say \"I don't know\".\n\nContext:\n"
    	for _, c := range top {
    		prompt += "- " + c + "\n"
    	}
    	prompt += "\nQuestion: " + question
    
    	var out struct {
    		Choices []struct {
    			Message struct {
    				Content string `json:"content"`
    			} `json:"message"`
    		} `json:"choices"`
    	}
    	post("/chat/completions", map[string]any{
    		"model":    os.Getenv("LLM_MODEL"),
    		"messages": []map[string]string{{"role": "user", "content": prompt}},
    	}, &out)
    	fmt.Println("Answer:", out.Choices[0].Message.Content)
    }
    

    Read the program. What will it print?

  6. 6Fix

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"math"
    	"net/http"
    	"os"
    	"sort"
    	"strings"
    )
    
    const docs = "To reset your password, open the login page and choose forgot password. We email you a reset link.\n\nParcel delivery takes three days. Use the tracking number from the courier to follow your order.\n\nDamaged items can be returned for a refund or a replacement. We send your money back within five days.\n\nA refund goes back to the card you paid with. Your invoice and payment receipt are on the billing page.\n\nThe API returns an error code when a request fails. Check the program logs to debug it."
    
    func post(path string, body map[string]any, out any) {
    	payload, _ := json.Marshal(body)
    	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+path, bytes.NewReader(payload))
    	req.Header.Set("Content-Type", "application/json")
    	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
    	res, err := http.DefaultClient.Do(req)
    	if err != nil {
    		fmt.Fprintln(os.Stderr, err)
    		os.Exit(1)
    	}
    	defer res.Body.Close()
    	json.NewDecoder(res.Body).Decode(out)
    }
    
    func embed(texts []string) [][]float64 {
    	var out struct {
    		Data []struct {
    			Embedding []float64 `json:"embedding"`
    		} `json:"data"`
    	}
    	post("/embeddings", map[string]any{"model": os.Getenv("LLM_EMBED_MODEL"), "input": texts}, &out)
    	vectors := make([][]float64, len(out.Data))
    	for i, d := range out.Data {
    		vectors[i] = d.Embedding
    	}
    	return vectors
    }
    
    func cosine(a, b []float64) float64 {
    	var dot, na, nb float64
    	for i := range a {
    		dot += a[i] * b[i]
    		na += a[i] * a[i]
    		nb += b[i] * b[i]
    	}
    	return dot / (math.Sqrt(na) * math.Sqrt(nb))
    }
    
    // retrieve returns the k chunks closest to the question, best first.
    func retrieve(question string, chunks []string, k int) ([]string, []float64) {
    	vectors := embed(append([]string{question}, chunks...))
    	scores := make([]float64, len(chunks))
    	order := make([]int, len(chunks))
    	for i := range chunks {
    		scores[i] = cosine(vectors[0], vectors[i+1])
    		order[i] = i
    	}
    	sort.SliceStable(order, func(a, b int) bool { return scores[order[a]] < scores[order[b]] })
    	var top []string
    	var topScores []float64
    	for _, i := range order[:k] {
    		top = append(top, chunks[i])
    		topScores = append(topScores, scores[i])
    	}
    	return top, topScores
    }
    
    func main() {
    	question := "How do I get my money back for a damaged item?"
    	top, _ := retrieve(question, strings.Split(docs, "\n\n"), 2)
    
    	prompt := "Answer only from the context. If the answer is not there, say \"I don't know\".\n\nContext:\n"
    	for _, c := range top {
    		prompt += "- " + c + "\n"
    	}
    	prompt += "\nQuestion: " + question
    
    	var out struct {
    		Choices []struct {
    			Message struct {
    				Content string `json:"content"`
    			} `json:"message"`
    		} `json:"choices"`
    	}
    	post("/chat/completions", map[string]any{
    		"model":    os.Getenv("LLM_MODEL"),
    		"messages": []map[string]string{{"role": "user", "content": prompt}},
    	}, &out)
    	fmt.Println("Answer:", out.Choices[0].Message.Content)
    }
    
    The program runs, but the answer talks about passwords, not refunds. What is wrong?
  7. 7Say it back

  8. 8Mission · 15 min

    Replace the five chunks with five paragraphs of your own and set LLM_EMBED_MODEL to a real embeddings model from the offer at the top. Ask a question whose answer is in one paragraph. Real vectors have hundreds of dimensions, so the scores will differ from the simulated ones.

    export LLM_BASE_URL=<base URL from the offer page>
    export LLM_EMBED_MODEL=<embedding model id from the offer page>
    export LLM_MODEL=<chat model id from the offer page>
    export LLM_API_KEY=<your key>
    go run main.go

Common questions

Why not paste all my documents into the prompt?
A prompt has a limit, the context window, and you pay for every token you send. A library of documents is usually far larger than the window, and long prompts are slower and costlier. Retrieval sends only the few chunks that matter for the question, so the answer is cheaper, faster and easier to trace back to its source.
How big should a chunk be?
Big enough to hold one idea, small enough to stay on topic: a paragraph or a few sentences is a common start. Chunks that are too long mix topics and blur the match. Chunks that are too short lose the context around a fact. Try a size, test it on real questions, and change it when the right chunk does not come first.
Is RAG the same as fine-tuning?
No. Fine-tuning changes the model with more training. RAG leaves the model alone and gives it facts in the prompt at question time. RAG is easier to update, because you change a document, not the model, and you can show which chunks an answer came from. Fine-tuning suits style and format more than fresh facts.

Sources

Simulated responses from a local mock server, not from a real model. Run with local mock server (scripts/course-llm-mock.ts), go1.27.4 darwin/arm64, curl on 2026-12-03

Published Dec 3, 2026 · Updated Dec 3, 2026

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer