跳到正文

第 15 课 · Retrieval and Tools

Retrieval with Llama: Answer from Your Documents

Build retrieval for Llama: split documents into chunks, embed them with an embedding model, find the closest passages and ask for answers with citations.

A Llama model does not know your private documents. Retrieval-augmented generation (RAG) helps without any training: your program finds relevant passages and puts them into the prompt. The model then answers from that text. This is often the first thing to try for company knowledge.

The pipeline

flowchart LR
  D["Documents"] --> C["Chunks"]
  C --> E["Embeddings"]
  E --> I["Index"]
  Q["Question"] --> QE["Question embedding"]
  QE --> I
  I --> P["Top passages"]
  P --> L["Llama writes the answer"]

Indexing happens ahead of time. Searching and answering happen for each question.

Chunking

Split documents into pieces that make sense on their own, such as sections or paragraphs. Chunks that are too big waste context; chunks that are too small lose meaning. Keep metadata (title, source, date, who may read it) with each chunk. See chunking documents.

Embeddings come from an embedding model

An embedding is a list of numbers that represents meaning, so that similar texts get nearby vectors. Use a model made for embeddings. A chat Llama is not automatically a good embedding model.

Ollama has an endpoint POST /api/embed. It takes a model and an input (one string or a list) and returns embeddings, one vector for each input. This command is real, for your own machine:

Terminal
curl http://localhost:11434/api/embed -d '{
  "model": "<an-embedding-model>",
  "input": ["How do I reset the device?", "Refunds take five days."]
}'

Replace the placeholder with an embedding model that you have downloaded, and check its license. Use the same embedding model for documents and questions. If you change it, rebuild the index. Also note that the truncate option, on by default, shortens inputs that are too long, so oversized chunks can lose text silently.

A working toy retriever

Without an embedding model, you can still learn the mechanics with word counts. Real embeddings capture meaning far better than this.

Python Stand-in: retrieval with word-count vectors

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last question has no answer in the documents, yet the search still returns two results. A search always has a "top", even when nothing is relevant. Use a score threshold (chosen by testing) and let the model say it does not know.

Ask with grounding

Put the passages in the prompt with IDs, and ask for citations:

TEXT
System: Answer only from the sources. Cite source IDs in brackets.
If the sources do not answer the question, say "I don't know from these documents."

<source id="reset">To reset the lamp, hold the power button...</source>
<source id="charge">Charge the lamp with...</source>

User: How do I reset my lamp?

Check citations in code: every cited ID must be among the ones you sent. A valid ID still does not prove that the passage supports the claim.

Security and privacy

  • Access control belongs in retrieval: never retrieve chunks that the current user may not read.
  • Retrieved text is untrusted. A document can say "ignore your instructions". Treat it as data and limit what the model can do.
  • Remove or protect personal data, and know where your index is stored.

Improving results

Test retrieval separately from answering. For each test question, check whether the right chunk appears in the top results. Possible upgrades are better chunking, keyword search combined with vector search, and a reranker that reorders candidates. Change one thing at a time and measure again. See retrieval-augmented generation for more.

Chunk size in practice

There is no perfect size. Start with natural units such as one section or a few paragraphs, and keep the heading with each chunk so the text makes sense alone. A small overlap between neighboring chunks can keep a sentence from being split away from its context. Then look at real retrieved chunks. If they are full of unrelated material, make them smaller. If they lack the needed detail, make them larger or include neighbors.

Storing vectors

For a few thousand chunks, a plain list in memory with a loop over cosine similarity is often enough. For larger collections, you can use a database with vector search or a dedicated vector index. Whatever you choose, store the text, the metadata and the name of the embedding model together, so you can rebuild or filter safely.

How many passages to send

More passages give the model more chances to find the answer, but they use context, slow the reply and add distractions. Start with a few, measure retrieval on your test questions and increase only if the right passage is often just outside the top results. Count the tokens of the final prompt and keep room for the reply.

Failure cases to test

  • A question whose answer is not in the documents.
  • Two documents that disagree, such as an old and a new policy. Keep dates in the metadata and decide which should win.
  • A question that uses different words from the document.
  • A document that contains instructions aimed at the model.
  • A user who asks about a document they are not allowed to see.

Each of these has a specific fix, such as a threshold, a version filter, better embeddings, limited permissions or filtering in retrieval.

Retrieval is not memory

Retrieval does not teach the model anything. The passages exist only in the current request. That is useful: when you correct a document, the next answer can use the new text as soon as the index is updated, and when you delete a document, you can remove it from search. It also means that every request must retrieve again, and that follow-up questions such as "and how long does it take?" may need to be rewritten into a full question before searching.

Start simple. Build the simplest version first and keep its scores as your baseline.

Common mistakes

Do not blame the model for every wrong answer. First check that the needed passage was actually retrieved and fit inside the context window.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What must you do if you change the embedding model?

    Vectors from different models are not comparable.
  2. 2. Why does a relevance threshold help?

    Weak matches should be rejected so the system can admit it does not know.
  3. 3. Where must you enforce who may see a document?

    Never rely on the model to hide text that you already gave it.

Summary

  • RAG gives Llama relevant text at question time.
  • Chunk well, embed with a suitable model and use it consistently.
  • Test retrieval separately, and require grounded answers with citations.
  • Enforce access control and treat retrieved text as untrusted.

Next: Tool Calling with Llama

你的学习进度保存在此浏览器中,无需账号。