Introduction
In our last lesson, we focused on the "API contract" for our agent, designing precise tool schemas to ensure the LLM could reliably select and invoke functions. We built the foundation for a single, stateless exchange: the agent receives a request, calls a tool, and returns a result. However, for an agent to be truly useful, especially in service fulfillment, it must engage in coherent, multi-turn dialogues. It needs to remember what was said previously, ask clarifying questions, and build context over time.
This lesson addresses that fundamental requirement by tackling the problem of conversational state. You will learn how to manage multi-turn conversation state using message histories with role-based formatting. We will explore how, despite LLMs being inherently stateless, we can engineer a robust "memory" for our agent by carefully structuring and managing the history of its interactions. This is the first step in moving from a simple tool-caller to a stateful, conversational agent.
The Illusion of Memory: Context Windows and Statelessness
At their core, Large Language Models are stateless functions. When you make an API call, the model has no intrinsic memory of your previous requests. It processes the input you provide, generates an output, and then "forgets" the interaction ever happened. This is analogous to a pure function in programming or a stateless microservice in a distributed architecture; its output depends solely on its current input.
So, how do applications like ChatGPT create the convincing illusion of a continuous conversation? They achieve this by managing the state externally and re-supplying the relevant history with every single turn. This history is passed into what's known as the context window.
Why LLMs Forget—and How RAG + Context Engineering Fix It (Free Labs).
This video from KodeKloud provides a clear analogy for understanding the context window and its limitations.
Watch the initial segment from the beginning to understand the concept of the context window as the LLM's short-term memory. The analogy to human short-term memory and memorizing Pi digits is quite effective.
The context window is the finite amount of information (measured in tokens) that a model can consider at once. For an agent to hold a conversation, our application logic must:
- Store the history of the conversation.
- On each new user turn, combine the history with the new message.
- Send this entire payload to the LLM as its input context.
The agent's "memory" is therefore not inside the model, but in the history we construct and provide on every call.
Structuring Conversation: The Three Fundamental Roles
Simply concatenating text from the user and the agent isn't enough. The model needs to unambiguously understand who said what. To achieve this, conversational history is structured as a sequence of messages, each tagged with a specific role.
The article "Instruction Format: Chat Templates & Role Definitions" provides an excellent deep-dive into the theory and practice of this structure.
This first section introduces the three canonical roles and explains why this separation is crucial for training and inference.
Read the section titled Role Definitions. Pay close attention to the purpose of the System, User, and Assistant roles. The theatrical script analogy is a helpful mental model.
To summarize the key functions of each role:
system: This message sets the stage for the entire conversation. It's used to define the agent's persona, its objectives, constraints, and any high-level instructions that should persist across all turns. It's the director's notes for the agent. We will explore this role in depth in our next lesson.user: This represents the input from the human user. It's the prompt or question that the agent needs to respond to.assistant: This represents the model's own previous responses. When constructing the history, we label the agent's past outputs with this role. This is critical for the model to understand what it has already said and avoid repeating itself. When training, the loss is typically only calculated onassistanttokens.
This structured, role-based format is the universal standard for managing conversational state with modern LLMs.
Implementing In-Memory Conversation History
Let's translate this concept into a practical implementation. At its simplest, a conversation history can be managed as a list of dictionaries in your application's memory, where each dictionary contains a role and content key.
The following video demonstrates this basic principle with a simple Python script.
How to build your own long-term Agentic Memory System for LLMs | Mem0 from scratch in DSPy
This segment shows the most fundamental implementation of conversation history: appending messages to a list within a loop.
Watch from this timestamp. The key piece of logic is the messages list that grows with each turn by appending both the user input and the assistant's response. Notice how the memory is lost as soon as the script is restarted. This illustrates a purely in-memory, short-term conversational state.
While this simple loop is illustrative, a more robust implementation would encapsulate this logic within a service. The article "Building a chat application with a local LLM from scratch" provides a clean example using FastAPI, which aligns well with the principles of building a scalable backend service.
Building a chat application with a local LLM from scratch
This article contains a backend code snippet that shows how to handle a message history within a web endpoint.
In the section "Building the backend application", review the Python code block for backend/main.py. Focus on these key elements: The Message and ChatRequest Pydantic models, which formally define the structure of a single message and a list of messages. The chat function, which receives a ChatRequest object. The line messages = [{"role": "system", ...}] + [message.model_dump() for message in request.messages], which shows the full conversation history being constructed before being passed to the LLM client.
This FastAPI example demonstrates the core pattern: the client (or agent orchestrator) is responsible for maintaining the list of messages and sending the complete history with each request. The agent service itself remains stateless, simply processing the history it receives.
From Structured Data to Model-Ready Strings: Chat Templates
We now have a standardized way to represent the conversation history: a list of {"role": ..., "content": ...} dictionaries. However, different models are trained to expect this information in different raw string formats.
- Mistral models expect
[INST] User message [/INST] Assistant response. - Qwen models use a format like
<|im_start|>user\nUser message<|im_end|>. - Phi-3 models use
<|user|>\nUser message<|end|>.
Manually formatting these strings for each model would be brittle and unmaintainable. The standard solution is to use a chat template, which is part of a model's tokenizer configuration. The Hugging Face transformers library provides a convenient method, apply_chat_template, to handle this automatically.
These sections provide a practical guide to using apply_chat_template and understanding the underlying mechanics for training.
First, read Working with Chat Templates. The code examples clearly show how to pass the list of message dictionaries to apply_chat_template and how the output differs across models like Phi-3, Qwen2, and Mistral. This highlights the value of the abstraction. Pay close attention to the add_generation_prompt=True parameter; it is essential for telling the model it's its turn to speak. Next, read Tokenizing for Training. While you are not training a model right now, understanding how loss masking works provides a deeper insight into why the role separation is so important. The model is only trained to predict assistant tokens, reinforcing its role as a responder.
Using apply_chat_template allows you to write model-agnostic code. You manage the state as a clean list of dictionaries, and the tokenizer handles the final, messy conversion into the specific format the model requires.
The Inevitable Limit: Exceeding the Context Window
The simple approach of appending every message to a list works well for short conversations. However, as the dialogue continues, the token count of the history will eventually exceed the model's context window. When this happens, you have two choices:
- Fail the request.
- Truncate the history, causing the model to "forget" the beginning of the conversation.
A more sophisticated agent must manage its conversational memory more intelligently. This often involves compressing or summarizing older parts of the conversation to keep the most salient information while staying within the token limit.

This summarization process can itself be an LLM call. The agent effectively asks a model to summarize the current conversation so that the summary can be used as context for future turns.

We will delve into the implementation of these summarization and other long-term memory techniques in Module 4, "Agent State and Task Persistence." For now, it's important to recognize that a simple, growing list is the first step, but not the final solution for long-running, stateful agents.
Conclusion
In this lesson, we have established the fundamental mechanism for creating stateful, conversational agents. By understanding and implementing role-based message histories, you have moved beyond single-shot commands and can now build agents that maintain context across multiple turns.
Here are the key takeaways:
- LLMs are stateless: Conversational "memory" is an illusion created by externally managing the conversation history and resubmitting it with each turn.
- Roles provide structure: The
system,user, andassistantroles are essential for the model to understand the conversational flow and its own part in it. - History is a list of messages: The standard practice is to maintain the conversation as a list of dictionaries, each with a
roleandcontent. - Chat templates handle formatting: Use a model's tokenizer and its
apply_chat_templatemethod to convert the structured history into the specific string format the model expects, ensuring portability. - Context windows are finite: The simple append-only strategy will eventually fail. Advanced agents require summarization or other compression techniques to manage long-term state, a topic we will explore in a future module.
In our next lesson, we will build directly on this foundation by diving deep into system prompt design patterns. You will learn how to use the system message to effectively define your agent's identity, give it specific instructions and constraints, and shape its behavior for complex tasks.