Track Turns

Update chat_loop to maintain conversation history and pass it to build_prompt on every turn

💻

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

Building up the conversation memory

The messages list is the conversation memory. It starts empty at the beginning of each session. After each exchange, you append two entries: one recording what the user asked and one recording what the assistant answered.

Every new call to build_prompt receives the full messages list so the model sees all prior turns before generating the next answer. The list grows by two entries per turn, accumulating the complete history of the conversation.

Instructions

  1. Create an empty list called messages on the line after file_list = ..., before while True. This is the conversation memory — it starts empty at the beginning of each session and grows as the user and assistant exchange messages.
  2. The build_prompt function now accepts a history parameter. Update the existing build_prompt call to build_prompt(question, top_chunks, messages, file_list), passing messages as the third argument between top_chunks and file_list.
  3. After print(f"Assistant: {answer}"), record what the user asked by appending {"role": "user", "content": question} to messages. This saves the question so it appears in the next prompt.
  4. Record what the assistant answered by appending {"role": "assistant", "content": answer} to messages. Saving both sides of the exchange gives the model the full back-and-forth context on the next question.