---
title: "Answer from your own documents with a small RAG"
slug: "rag-basics"
description: "Chunk a text, embed it, find the closest chunks to a question and put them into the prompt, so the model answers from your own documents."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-llm/rag-basics"
---

# Answer from your own documents with a small RAG

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.

```sh
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](https://aifree.dev/offer/mistral-ai-free-plan)

## Predict

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?

- The one about parcel delivery and tracking
- The one about damaged items, refunds and replacements
- The one about the API error code

Answer: The one about damaged items, refunds and replacements — It is about getting money back for a damaged item, so its vector points the same way as the question.

Next you split the text into chunks and see the scores.

## 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.

## Chunk, embed and rank

```go
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)
	}
}
```

Output:

```
1.00 Damaged items can be returned for a refund or a replacement. We send your money back within five days.
0.37 A refund goes back to the card you paid with. Your invoice and payment receipt are on the billing page.
```

_Simulated response (local mock server), 2026-12-03._

One embeddings request carries the question and every chunk, so the vectors are comparable. The scores are the mock's; a real model gives different numbers with the same order.

## 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.

## The whole pipeline

```go
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)
}
```

Output:

```
Retrieved:
- Damaged items can be returned for a refund or a replacement. We send your money back within five days.
- A refund goes back to the card you paid with. Your invoice and payment receipt are on the billing page.
Answer: Based on the context: Damaged items can be returned for a refund or a replacement. We send your money back within five days.
```

_Simulated response (local mock server), 2026-12-03._

The mock answers from the first context line, with the words "Based on the context". A real model writes its own sentence from the chunks.

## Fix it

```go
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?

- It sorts the scores ascending, so it sends the worst chunks
- The question is too short
- The chat model is too small

Answer: It sorts the scores ascending, so it sends the worst chunks — The lowest similarity comes first, so the two least related chunks go into the prompt.

Fixed:

```go
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)
}
```

Output:

```
Answer: Based on the context: Damaged items can be returned for a refund or a replacement. We send your money back within five days.
```

_Simulated response (local mock server), 2026-12-03._

## Say it back

In your own words: what are the four moves of RAG, and why tell the model to say "I don't know"?

Our sentence: I split my documents into chunks, embed them and the question, keep the chunks closest to the question, and put them in the prompt. I tell the model to answer only from that context and to say "I don't know" otherwise, so it does not make up an answer when the chunks do not hold it.

## Mission (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.

```sh
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

- https://platform.openai.com/docs/guides/embeddings (read 2026-12-03)
- https://docs.mistral.ai/capabilities/embeddings/text_embeddings/ (read 2026-12-03)
- https://pkg.go.dev/encoding/json (read 2026-12-03)
- https://pkg.go.dev/net/http (read 2026-12-03)

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.
