Start learning free

LESSON 62 OF 129 · AI ENGINEERING: RETRIEVAL (RAG)

Answer from the Passages in Python

Practice

The last lesson found the three passages closest to a question. A customer wants an answer, not three passages. So the passages go to the model, and the model writes the answer from them. First search, then answer: together this is retrieval-augmented generation, RAG for short.

The shape of the prompt: each passage sits inside its own pair of tags, and the opening tag carries the file it comes from. The question goes last. Here is such a prompt for another shop, a bike shop:

<passage source="hours.md">Opening hours: We are open Monday to Friday, 9 to 17.</passage>
<passage source="repairs.md">Repairs: A flat tyre is fixed the same day.</passage>
Question: Are you open on Sunday?

Passages in the prompt are not enough. Without a rule, the model mixes them with what it knows about shops in general, and the customer can't tell which part is which. The system prompt must say that the passages are the only thing the model may use, and that it may say it doesn't know. An answer tied to the text you sent is called grounded.

When your program is finished, it prints the grounded answer. Then the check asks one more question through your function and looks at the prompt you sent:

Yes, in most cases. You can return any item within 14 days of delivery if it is unused and in its original packaging. Gift cards and items bought on sale can't be returned or refunded.
Do you ship to Canada? -> Yes. Shipping to Canada costs a flat $15 and takes 7 to 10 business days. Express delivery isn't available for Canada.
Calls to the model: 2
Passages in the last prompt: 3 of 3
The question comes after the passages: True

Your task: the search from the last lesson, top_matches, is already in the editor. Write a system prompt SYSTEM and a function answer(question) that puts the three passages into the prompt inside <passage source="…"> tags, adds the question last, calls the model and returns the reply's text. Then print the answer to "Can I get my money back?".


Assignment
Follow the Coding Tutorial to build answer(question) and the system prompt that keeps the model to the passages.


Hint
Two of the strings around a passage have a double quote inside them, so write those two with single quotes around them. Every piece of SYSTEM ends with a space, so the sentences don't run together.


STEP 1 OF 12
    Ctrl + Enter to check

    Ai Answer From Passages in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free