Print the Answer and Sources
Exit

Print the Answer and Sources

Display the generated answer, with optional source passages

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Why show sources?

The previous chapter generated an answer from retrieved chunks. But how does the user know the answer is trustworthy? By showing the source passages alongside the answer.

Displaying sources serves three purposes:

  1. Trust — the user can read the original text and verify the answer themselves.
  2. Debugging — if the answer is wrong, you can check whether the retrieval step returned the right chunks. A bad answer from good chunks means the model misread them. A bad answer from irrelevant chunks means the search function needs tuning.
  3. Transparency — the user sees exactly what the model was given. No hidden context, no mystery.

This is the same idea behind footnotes in academic papers — every claim points back to its source.

The show_sources parameter

Sources are helpful during development and for power users, but not always wanted in production. The show_sources parameter (default True) lets callers choose:

CallBehaviour
print_result(answer, chunks)Prints answer and sources
print_result(answer, chunks, show_sources=False)Prints answer only

Python pattern: enumerate with a start index

The loop uses enumerate(source_chunks, 1). The second argument tells Python to start counting from 1 instead of the default 0. This produces human-friendly labels: "Source 1", "Source 2", rather than "Source 0", "Source 1".

def print_result(answer, source_chunks, show_sources=True):
    print("Answer:")
    print(answer)
    if show_sources:
        print("\nSources:")
        for i, chunk in enumerate(source_chunks, 1):
            print(f"Source {i}:\n{chunk}\n")

Instructions

Complete the print_result function. The starter code provides the signature.

  1. Print "Answer:".
  2. Print answer.
  3. Add an if show_sources: block.
  4. Inside the block, print "\nSources:".
  5. Inside the block, create a for loop with variables i and chunk over enumerate(source_chunks, 1). Inside the loop, print f"Source {i}:\n{chunk}\n".