Sub topic 5
Assistant Messages: The Model's Replies
This chapter assumes you can read basic Python, work with lists and dictionaries, and have called an HTTP API or an SDK before. You should also know that every chat message has a role and content, and that the system and user roles carry instructions and requests. Here you will look at the third role, assistant.
What an assistant message is
An assistant message is a message whose role is "assistant". It holds text that the model wrote, or text that you present as if the model wrote it.
{"role": "assistant", "content": "A list is an ordered, changeable collection of items."}The shape is the same as any other message. What differs is where it comes from. System and user messages come from your code and your users. Assistant messages usually come from the API response. You then decide whether to keep them in the history you send next time.
Where the reply appears in the response
When you call a chat API, the reply does not come back as a bare string. It comes inside a response object, and you pull the text out.
With an OpenAI-style SDK, the reply is a message object under choices:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=[
{"role": "system", "content": "You are a helpful assistant. Keep answers under three sentences."},
{"role": "user", "content": "What is a list in Python?"},
],
)
message = response.choices[0].message
print(message.role) # "assistant"
print(message.content) # the reply textchoices is a list because you can ask for several alternative replies in one call. By default there is one, so you read index 0.
With the Anthropic Messages API, the reply is a list of content blocks:
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="MODEL_NAME", # replace with a model available to you
max_tokens=300,
system="You are a helpful assistant. Keep answers under three sentences.",
messages=[
{"role": "user", "content": "What is a list in Python?"},
],
)
print(response.role) # "assistant"
print(response.content[0].text) # the first block of the replyresponse.content is a list because a reply can contain more than one block. A block can be plain text, a request to call a tool, or other types depending on the features you use. Code that always reads content[0].text works for simple text replies, but it fails when the first block is not text.
Assistant messages are how the model "remembers"
The model keeps no memory between calls. The only way it can know what it said earlier is if you send that text back as assistant messages. This is why the loop from the spine works:
from openai import OpenAI
client = OpenAI()
history = [
{"role": "system", "content": "You are a helpful assistant. Keep answers under three sentences."}
]
def chat(user_text):
history.append({"role": "user", "content": user_text})
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=history,
)
reply = response.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(chat("What is a list in Python?"))
print(chat("How do I add an item to it?"))The second question says "it". The model can resolve that word only because the first answer, stored as an assistant message, travels with the second request. If you removed the line that appends the reply, the second call would see two user messages in a row and no answer between them. The model would have to guess what "it" meant.
You control what the history says
The API does not check that the assistant messages you send were really generated by the model. They are input like any other, so you can:
- Edit a reply before storing it, for example to remove a mistake or a long preamble.
- Drop replies from the history to save space.
- Write assistant messages yourself.
Writing them yourself is the basis of few-shot prompting. In this example, the two assistant messages are examples of the output format, and the model continues the pattern for the last user message:
messages = [
{"role": "system", "content": "Classify the sentiment of the text as positive, negative, or neutral. Reply with one word."},
{"role": "user", "content": "The delivery was fast and the box was intact."},
{"role": "assistant", "content": "positive"},
{"role": "user", "content": "The app crashes every time I open it."},
{"role": "assistant", "content": "negative"},
{"role": "user", "content": "The package arrived on Tuesday."},
]The model did not write "positive" or "negative" here. You did, and that is fine. The model treats them as precedent for its own style.
Reading the stop reason before you store a reply
A reply can end for different reasons. Check why before you append it to the history, especially in a long conversation.
| Provider style | Field | Common values |
|---|---|---|
| OpenAI-style | `response.choices[0].finish_reason` | `stop` (finished naturally), `length` (hit the token limit), `content_filter`, `tool_calls` |
| Anthropic-style | `response.stop_reason` | `end_turn` (finished naturally), `max_tokens` (hit the limit), `stop_sequence`, `tool_use` |
Value names can change between API versions, so confirm them in your provider's documentation.
The most common problem is truncation. If the reply stopped because it reached the token limit, the text ends mid-sentence. If you store it, the next turn builds on a broken answer. A small guard makes the problem visible:
def extract_reply(response):
choice = response.choices[0]
if choice.finish_reason == "length":
raise ValueError("Reply was cut off by the token limit; raise the limit or shorten the prompt.")
return choice.message.contentWhether to raise, retry with a higher limit, or store the partial text depends on your application. The point is to decide deliberately instead of storing it by accident.
Empty and non-text replies
The content of an assistant message is not always a string. Handle these cases:
- No text. When the model asks to call a tool, the OpenAI-style
message.contentcan beNoneand the request appears in a separate field. If you appendNoneas content without handling it, the next request may be rejected. Tool messages are covered in a later chapter. - Refusals. The model may reply with text declining a request. This is still a normal assistant message, with a stop reason that looks like a normal finish. Do not parse the text to detect refusals unless you have to. Some providers expose a dedicated refusal field.
- Multiple blocks. With Anthropic-style APIs, join the text blocks instead of reading only the first:
def reply_text(response):
return "".join(block.text for block in response.content if block.type == "text")When you store an Anthropic-style reply in history, you can store the plain string as content. If the reply includes tool-use blocks, store the full block list instead, because the tool results that follow must refer to those blocks.
Ordering rules for assistant messages
Assistant messages follow the ordering rules from the earlier chapter, with details that matter in practice.
- A conversation normally alternates: user, assistant, user, assistant. The model's reply is generated after the last message you send.
- Some providers reject a history that starts with an assistant message, or require the first non-system message to be from the user. Others accept it.
- Some providers merge or reject two consecutive messages with the same role. Do not rely on either behavior. Keep roles alternating.
- Normally the last message you send is a user message. The model then writes the next assistant turn.
Prefilling: starting the reply for the model
If the last message you send has the role assistant, some providers treat it as the beginning of the reply and continue from it. This is called prefilling. It can force a format, such as starting a JSON object:
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="MODEL_NAME", # replace with a model that supports prefilling
max_tokens=200,
messages=[
{"role": "user", "content": "Return the name and age of the person in this sentence as JSON: Maria is 34."},
{"role": "assistant", "content": "{"},
],
)
# The response continues after the prefill, so add it back to get complete JSON.
print("{" + response.content[0].text)Two details matter. First, the response contains only the continuation, so you must put the prefilled text back yourself. Second, support varies by provider and model. Some models and APIs reject a conversation that ends with an assistant message. Check your provider's documentation before depending on it, and have a fallback such as asking for JSON in the system message.
Treat assistant text as output, not as truth
The text in an assistant message is generated, not looked up. It can be wrong, outdated, or confidently invented. Two habits follow from this:
- Validate the reply before acting on it, for example by parsing JSON and checking required keys instead of trusting the format.
- Remember that earlier assistant messages influence later ones. A wrong answer left in the history can be repeated or built on. If you detect an error, correct or remove it from the history before the next turn.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Not appending the reply to history | The model forgets its previous answer | Append `{"role": "assistant", "content": reply}` after every call |
| Appending a truncated reply | Later turns build on a cut-off answer | Check the stop reason first |
| Appending `None` for a tool-call reply | The next request fails validation | Handle tool calls separately |
| Reading only `content[0]` with Anthropic-style APIs | Text is missed or an error occurs | Join all text blocks |
| Sending two user messages when you meant a pair | The model has no answer to refer to | Keep user and assistant turns paired |
| Forgetting to add the prefill back | Output is missing its first characters | Concatenate prefill and continuation |
Summary
An assistant message holds the model's reply, or an example reply you wrote. You read it from the response, check why it stopped, and append it to the history you resend on the next call. That resent history is the only memory the model has.
Exercise
A chat loop sends the system message and the new user message on every call, but it never appends the model's replies to the history. A user asks "What is a tuple in Python?" and then "How is it different from a list?". Why does the second answer often miss the point, and what one change fixes it?
Show answer
The API is stateless, so the model sees only what each request contains. On the second call it receives the system message and the question "How is it different from a list?" with no earlier turns, so "it" has no referent. Fix it by appending the first user message and the model's reply (as a message with role "assistant") to the history after the first call, then sending that full history with the second question.
Exercise
A reply comes back with finishreason "length" (or stopreason "max_tokens"). Why is it risky to append it to the history unchanged, and what are two reasonable ways to handle it?
Show answer
The text is cut off mid-answer, and later turns will treat that broken text as what the assistant said. You can raise the token limit and retry the same request, or detect the truncation and ask the user whether to continue. You could also store the partial text only after marking or completing it. The key point is to check the stop reason before storing.