Sub topic 8
Building conversational assistants
A conversational assistant is an application that carries on a multi-turn dialogue with a user and answers each message in light of what came before. This chapter covers the working model, context management, and the errors that show up most often. It assumes you know basic Python, JSON, and HTTP APIs. It also assumes you have read the chapters on how models generate text, on their limitations, and on prompting.
The working model: the model has no memory
A model call is stateless. Each request contains everything the model will see, and nothing carries over from the previous request. A conversation feels continuous only because your program resends the earlier turns every time.
Most chat APIs use a list of messages, each with a role:
system: standing instructions that define the assistant's purpose, tone, and rules.user: what the person typed.assistant: what the model replied earlier.
Your application owns this list. It appends the new user message, sends the whole list, receives a reply, and appends the reply.
A minimal assistant
The class below keeps the history and takes a complete function that wraps whichever model API you use. It receives a list of message dictionaries and returns the reply text.
class Assistant:
def __init__(self, complete, system_prompt: str):
self.complete = complete
self.system = {"role": "system", "content": system_prompt}
self.history = []
def say(self, user_text: str) -> str:
self.history.append({"role": "user", "content": user_text})
messages = [self.system] + self.history
reply = self.complete(messages)
self.history.append({"role": "assistant", "content": reply})
return reply
def fake_complete(messages):
# Stand-in model: reports how many messages it was sent.
return f"I was sent {len(messages)} messages."
bot = Assistant(fake_complete, "You are a concise support assistant.")
print(bot.say("Hi"))
print(bot.say("Where is my order?"))The second call prints I was sent 4 messages. The system prompt, two user turns, and one earlier reply were all resent. The input grows with every turn, and so does the cost of each call.
Context is a budget
A model can read only a limited number of tokens per request, called its context window. The system prompt, the history, any retrieved documents, and the reply you want must all fit in it. Long conversations eventually overflow it. Even before that, cost and latency rise with input length, and models can lose track of details buried in the middle of a long prompt.
You then have to decide what to keep. The common strategies are in the table.
| Strategy | How it works | Strength | Weakness |
|---|---|---|---|
| Full history | Send every turn | Nothing is lost | Hits the limit; cost grows each turn |
| Sliding window | Keep the last N turns | Simple, predictable size | Forgets early facts such as the user's name |
| Summarization | Replace old turns with a model-written summary | Keeps the gist in few tokens | Summaries drop details and can introduce errors |
| Pinned facts | Store key facts (name, order ID) separately and add them to every prompt | Reliable for important data | You must decide what counts as a key fact |
| Retrieval | Store past turns or documents and fetch only relevant ones | Scales to very long histories | Needs an embedding and search setup |
Real assistants usually combine them. A typical design pins a few facts, summarizes older turns, and keeps the last several turns verbatim.
A sliding window with pinned facts
Count the budget in tokens when you can. The sketch below approximates a token as four characters, which is a rough rule for English. Use your provider's tokenizer in production.
def estimate_tokens(text: str) -> int:
return max(1, len(text) // 4)
def build_messages(system, pinned, history, budget=1000):
header = system + "\n\nKnown facts:\n" + "\n".join(f"- {f}" for f in pinned)
used = estimate_tokens(header)
kept = []
for msg in reversed(history): # newest first
cost = estimate_tokens(msg["content"])
if used + cost > budget:
break
kept.append(msg)
used += cost
kept.reverse()
return [{"role": "system", "content": header}] + kept
history = [
{"role": "user", "content": "My order number is 4417."},
{"role": "assistant", "content": "Thanks. How can I help?"},
{"role": "user", "content": "It has not arrived."},
]
msgs = build_messages(
"You are a support assistant.",
["order number: 4417"],
history,
budget=40,
)
for m in msgs:
print(m["role"], "|", m["content"])With a small budget, the oldest turn is dropped. The order number survives because it was pinned.
Writing the system prompt
The system prompt is the assistant's job description. A good one states:
- The role and the audience ("You help customers of a bookshop").
- What is in scope and what to do outside it ("If asked about anything else, say you can only help with orders").
- Tone and length ("Reply in two or three sentences").
- How to handle uncertainty ("If you do not know, say so and offer to contact a person").
Keep it short and specific. Every token in it is paid for on every turn.
Grounding the assistant
On its own, an assistant answers from what the model absorbed in training, so it can state policies or prices that are wrong. When answers must match your data, add grounding:
- Retrieval: fetch relevant documents and place them in the prompt. The retrieval chapters cover this in detail.
- Tools: let the model call functions, such as an order lookup, so facts come from your systems.
Tell the model to prefer supplied material over its own knowledge, and to say when the material does not contain the answer.
Common errors
- Treating the model as stateful. Developers sometimes send only the latest message and then wonder why the assistant forgets. Resend the history.
- Unbounded history. The app works in testing and fails on long sessions with a context-length error. Enforce a budget before every call.
- Dropping the system prompt when trimming. If your trimming code removes the oldest messages, make sure the system message is never among them.
- Summaries that rewrite facts. A summary may turn "refund requested" into "refund approved". Pin critical facts as structured data instead of trusting a summary.
- Sharing history between users. Keep one history per conversation, keyed by a session ID. A global list leaks one user's data to another.
- Instructions that fade. In long chats the model may drift from the system prompt. Repeat key rules near the end of the prompt, or restate them when the history is long.
- No exit path. Assistants will sometimes fail. Provide a way to reach a person, and log conversations, within your privacy rules, so you can find failures.
- Trusting user text as instructions. A user can write "ignore your rules". Keep important constraints in code, not only in the prompt. The safety chapter covers this.
Streaming and latency
Users judge a chat by how fast the first words appear. Most APIs can stream tokens as they are generated. Stream the reply to the interface, and append the full text to history only when the stream ends. If the user cancels mid-stream, decide whether to store the partial reply. Storing it keeps the history truthful about what the user saw.
Testing a conversation
A single-turn test checks one answer. Conversations need multi-turn tests. Script a sequence of user messages, such as giving an order number first and asking about it three turns later, and check the final reply for the expected fact. Include a test with a very long history to confirm trimming works, and one off-topic request to confirm the scope rule holds.
Exercise
A user tells your assistant their name in turn 1. At turn 30 the assistant no longer knows it. Your code keeps only the last 10 turns. Name two ways to fix this, and say what each costs.
Show answer
Pin the name as a stored fact and add it to every prompt. This costs a few tokens per call and requires code that detects and saves the fact. Alternatively, summarize turns older than the window and include the summary. This costs an extra model call and risks the summary losing or changing details. A larger window also works, but it raises cost and latency and only delays the problem.
Exercise
Your assistant calls complete(history) on a global list shared by all web requests. Describe two problems this causes and the fix.
Show answer
Different users' messages are mixed into one conversation, so one user can see or influence another's context, which is a privacy leak and gives wrong answers. The list also grows without limit across all users, so it will exceed the context window. The fix is a separate history per session ID, stored per conversation, with a token budget enforced before each call.