Pass History to the Prompt
Exit

Pass History to the Prompt

Update build_prompt to accept conversation history and embed it between the context and the question

💻

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

Where history belongs in the prompt

The format_history function converts the message list to a text block. That block needs to appear in the prompt after the retrieved context and before the question, so the model can use both the document context and the conversation history when formulating an answer.

Adding a history parameter to build_prompt keeps history injection in one place. The default value of None means existing callers that don't pass history continue to work without modification.

Instructions

  1. Add a new parameter named history to the list of parameters of the build_prompt function, after context_chunks and before file_list. The default value is None.
  2. On the line after context = ..., add history_text = format_history(history or []).
  3. The history block must sit between the context and the question. Edit the return string:
    • Change f"Context:\n{context}\n\n" to f"Context:\n{context}" — remove the trailing double newline, because history_text already starts with its own newline.
    • Add f"{history_text}\n\n" on the next line, before f"Question:\n{question}".