Format History

Write a function that converts the conversation history list into a readable string for the prompt

💻

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

How history is stored

You will store each turn of the conversation as a dictionary with two keys:

  • role: either "user" or "assistant", identifying who spoke.
  • content: the text of that message.

The full conversation is a list of these dictionaries, growing by two entries after each exchange — one for the user's question and one for the assistant's answer.

Why you need a formatting function

The model receives a plain text prompt, not a structured list. Before you can include the history in a prompt, you need to convert those dictionaries into a readable string.

In this chapter, you'll write a function called format_history that takes the conversation list and returns a formatted string you can prepend to any prompt.

Instructions

  1. Define a function called format_history that takes messages.
  2. If not messages, return an empty string "". This guard prevents a history section from appearing on the very first question, when there are no prior turns yet.
  3. Create a list called lines with one item: the string "\nConversation so far:".
  4. Loop over messages. For each msg:
    • If msg["role"] equals "user", set role to "You". Otherwise, set role to "Assistant".
    • Append f"{role}: {msg['content']}" to lines.
  5. Return "\n".join(lines).