03.2 Messages, Roles and Conversation State
Every LLM API call carries a conversation: some instructions, a list of turns, and inside each turn one or more pieces of content. The four providers agree on that idea and disagree on almost every detail: what the roles are called, where the system prompt goes, whether content is a string or a list of typed blocks, what the model's reply looks like, which shapes are rejected, and whether the provider will store the conversation for you. This lesson is the precise reference for those message formats, and for keeping conversations correctly, either in your own database or on the provider's servers. By the end you'll have a converter between the formats, a SQLite conversation store, and a clear rule for when to let the provider hold the state.
What you'll learn
- Every role on every API (OpenAI Responses and Chat Completions, Anthropic Messages, Gemini
generate_contentand Interactions, OpenRouter), where instructions go, and whatdevelopermeans compared withsystem - Content as a plain string vs typed blocks and parts, how each provider represents the model's reply, and why you must append the full reply (reasoning items, thinking blocks, thought signatures) rather than just its text
- The message-shape rules (first turn, alternation, merging, no prefill, empty content, document placement, tool results, size limits) and the exact errors they produce
- Client-managed conversations done properly: an in-memory history that keeps provider-native output, a persistent SQLite store, reloading and continuing a conversation, switching providers mid-conversation, and trimming to a budget
- Server-side conversation state as API mechanics: OpenAI's
store,previous_response_id, retrieve/list/delete and the Conversations API; Gemini'sprevious_interaction_id; Anthropic's message threads beta; what each one keeps, for how long, and how it fails - A small, tested converter between one canonical message format and every provider's request and response shapes
- Gemini's chat helper and the difference between curated and comprehensive history
- How the common request parameters (output caps, stop sequences, reasoning effort,
metadata, end-user identifiers) map across providers - What stored message data means for privacy: what
storekeeps, how to delete it, how to identify users without sending personal data, and what HIPAA, SOC 2 and data residency mean for an API call (Part 10)
What you don't need
- API keys. Every part has something you can run for free: real code against a local model, mocked servers that return the providers' documented errors, or pure-Python code with no network at all. Samples that need a hosted provider are labelled, and their output is marked as illustrative (lesson 03.1 explains the output labels used across the module).
- Knowing what to write in a system prompt. This lesson shows where instructions go; Module 04 teaches what to put in them.
- Tool calling, streaming, images and caching in depth. They appear here only as message shapes, with links to the lessons that own them.
Setup
The samples need Python 3.11+ and the three official SDKs. Lessons 03.1 to 03.9 share one project folder, llm-apis, from lesson 03.1; if you don't have it yet, create it first, with the Python version set:
uv init llm-apis --bare --python 3.13
cd llm-apis
git initThen add this lesson's packages:
uv add openai anthropic google-genai python-dotenv tiktoken httpx
# or: pip install openai anthropic google-genai python-dotenv tiktoken httpxThe samples were written and checked against openai 3.42.1, anthropic 2.4.0 and google-genai 2.34.0 as of November 2026. google-genai 3.0.0 came out on 6 November 2026 with two breaking changes (a different default HTTP library and Gemini API version), and an unversioned install gives you 3.x, so httpx is in the command above (the script imports it, and 3.x no longer installs it). Lesson 03.1, 4.5 explains what changes and what to do. Python 3.11 and 3.12 also work; 3.13 is what this module's outputs were produced on. Setting it matters because plain uv init copies the Python limit from whichever interpreter it finds first, and the next uv add can then fail: see lesson 03.1, 4.2 for why, and Part 4 for the full setup, including the .env file:
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...The free local option. Samples marked "Try it free" run against a small local model: Ollama serves the OpenAI and Anthropic formats on http://localhost:11434. Lesson 03.1, Part 12 shows how to install it. A 0.5B-parameter local model gives poor answers, but it exercises the real SDKs, the real request shapes and the real response objects, which is what this lesson is about. Samples written for the hosted OpenAI and Anthropic APIs (their output is labelled illustrative) can also be run unchanged against the stand-in by pointing the SDKs at it with the OPENAI_BASE_URL and ANTHROPIC_BASE_URL environment variables, which both SDKs read; this lesson says what happens when you do. Gemini has no local stand-in: Ollama does not speak Gemini's API (lesson 03.1, 12.4), so every google-genai sample here is marked hosted-only (it needs GEMINI_API_KEY) and was not run. In your own tests, a hand-written mock server or recorded responses can stand in for Gemini.
What you must be able to do after this lesson#
- Build a conversation request with the right roles
- Explain the difference between string content and typed parts
- Fix message-shape errors
- Manage conversation history on the client
- Map the common request parameters across providers
- Explain what happens to message data for privacy
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Put that in the system prompt." (Which one? There are five places it can go.) | Part 2: Roles across providers |
"Should this be a developer message or a system message?" |
2.2 OpenAI Responses |
"Gemini rejected our history: there's no assistant role." |
2.5 Gemini generate_content |
| "We only stored the text of the replies, and now tool calls fail." | 3.6 Append the full output, not just the text |
| "Our JSON prefill trick started returning 400s." | 4.2 Prefill is gone |
| "Where do we keep conversations, and in what shape?" | Part 5: Client-managed conversations done properly |
| "Can we start a chat on Claude and continue it on Gemini?" | 5.4 Continuing on a different provider |
"Just use previous_response_id; then we don't need a database." |
Part 7: Server-side conversation state |
| "Chaining works, but the bot stopped following its instructions." | 7.1 previous_response_id chaining |
| "A user asked us to delete their data. Is it on OpenAI's side too?" | Part 10: Privacy and data handling |
| "Security wants to know if we are HIPAA or SOC 2 covered when we call the API." | 10.5 Compliance frameworks |
"What's the Gemini name for max_tokens?" |
Part 9: The common request parameters |
| "Write an adapter so our app isn't tied to one provider." | Part 6: Converting between formats |
Part 1: The anatomy of a conversation request#
1.1 Three layers: instructions, turns and parts#
Every chat request on every provider has the same three layers, whatever each API calls them:
- Instructions: the standing orders for the model (the "system prompt"). Who it is, what it must and mustn't do, the format of its answers.
- Turns: the conversation so far, in order. Each turn has a speaker, called its role: the end user, or the model itself.
- Parts: the content inside each turn. Plain text, but also images, documents, tool calls and their results, and the model's own reasoning data.
Around these sit the options: the model ID, the output cap, reasoning effort, metadata and so on (Part 9).
flowchart TB
subgraph req ["One request"]
I["Instructions<br/>(system / developer / instructions / system_instruction)"]
subgraph turns ["Turns, in order"]
T1["user turn"] --> T2["assistant / model turn"] --> T3["user turn"]
end
subgraph parts ["Inside each turn: content parts"]
P1["text"]
P2["image / document"]
P3["tool call / tool result"]
P4["reasoning item / thinking block / thought signature"]
end
O["Options<br/>(model, max output, effort, metadata ...)"]
end
T3 -. "each turn holds" .-> parts
req --> M["Model reads ONE flattened sequence<br/>(the chat template, lesson 02.2)"]None of this structure survives into the model. The provider flattens the whole request into one token sequence with role markers, using the model's chat template (lesson 02.2, 4.3). Roles and parts are an API contract that tells the provider how to build that sequence, and which parts deserve which level of trust. Because the model remembers nothing between calls, the whole request is rebuilt and re-read on every turn (lesson 02.7, Part 3).
1.2 The same conversation on five SDK paths#
The fastest way to see the differences is to send the same three-turn conversation, with the same system instruction, through every SDK path and print what each one puts on the wire. Three of the five paths (OpenAI Responses, OpenAI Chat Completions and Anthropic Messages) can run free against Ollama, the local stand-in, so the first script does that. The two Gemini paths have no local stand-in, so they get a second, hosted-only script right after it. In both, an event hook (a function the HTTP client calls with every outgoing request) records the request body.
What to look for: the first script has three short blocks, one per SDK path, and each builds the same history and makes one call per turn. The payoff is the printout at the end, the request body each SDK sent for turn 3. If the script looks long, read the table in 1.3 first and come back to the code.
# s1_2_three_turns_wire.py
"""The same three-turn conversation on three SDK paths, against the free local stand-in.
Ollama (localhost:11434) speaks the OpenAI and Anthropic formats. An httpx2 event hook
records the body of every request, so we can print exactly what each SDK put on the wire
for the final turn. (The two Gemini paths are in the hosted-only script that follows.)
"""
import json
import anthropic
import httpx2 # openai 3.x and anthropic 2.x use httpx2 (Pydantic's fork of httpx)
from openai import OpenAI
SYSTEM = "You are a bike-shop assistant. Answer in one short sentence."
USER_TURNS = [
"Hi, I'm Priya. I ride a 2019 Trek FX 3.",
"What tyre pressure should I start with?",
"What's my name, and which bike do I ride?",
]
MAX_OUT = 40 # small: the local model serves one request at a time
captured: dict[str, bytes] = {} # the LAST request body per SDK path
def recorder(name: str):
def hook(request) -> None: # receives an httpx/httpx2 Request before it is sent
captured[name] = request.content
return hook
# --- 1. OpenAI Responses API: instructions + input list ---------------------------------
oai = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama",
http_client=httpx2.Client(event_hooks={"request": [recorder("openai_responses")]}))
history_r: list = []
for text in USER_TURNS:
history_r.append({"role": "user", "content": text})
r = oai.responses.create(model="gpt-6-luna", instructions=SYSTEM, input=history_r,
max_output_tokens=MAX_OUT, store=False)
history_r.append({"role": "assistant", "content": r.output_text}) # text-only: see Part 3
print("OpenAI Responses :", r.output_text)
# --- 2. OpenAI Chat Completions: system message inside the list -------------------------
oai_chat = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama",
http_client=httpx2.Client(event_hooks={"request": [recorder("openai_chat")]}))
history_c: list = [{"role": "system", "content": SYSTEM}]
for text in USER_TURNS:
history_c.append({"role": "user", "content": text})
c = oai_chat.chat.completions.create(model="gpt-6-luna", messages=history_c,
max_completion_tokens=MAX_OUT)
history_c.append({"role": "assistant", "content": c.choices[0].message.content})
print("OpenAI Chat :", c.choices[0].message.content)
# --- 3. Anthropic Messages: top-level system + user/assistant messages ------------------
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama",
http_client=httpx2.Client(event_hooks={"request": [recorder("anthropic")]}))
history_a: list = []
for text in USER_TURNS:
history_a.append({"role": "user", "content": text})
m = claude.messages.create(model="claude-haiku-5-5", max_tokens=MAX_OUT, system=SYSTEM,
messages=history_a)
history_a.append({"role": "assistant", "content": m.content}) # all blocks, as objects
print("Anthropic :", next(b.text for b in m.content if b.type == "text"))
# --- What each SDK sent for turn 3 --------------------------------------------------------
def short(value) -> str: # compact JSON, long strings cut to keep the printout readable
text = json.dumps(value, ensure_ascii=False)
return text if len(text) <= 96 else text[:93] + "..."
for name, body in captured.items():
print(f"\n===== {name}: request body for turn 3 =====")
for key, value in json.loads(body).items(): # one line per top-level key / list item
if isinstance(value, list):
print(f"{key}: [")
for item in value:
print(" ", short(item))
print("]")
else:
print(f"{key}: {short(value)}")OpenAI Responses : I'm Priya, and I ride a 2019 Trek FX 3.
OpenAI Chat : Hello! My name is Priya, and I love riding a bike with a 2019 Trek FX 3. What can I help you with today?
Anthropic : My name is Priya and I ride a 2019 Trek FX 3.
===== openai_responses: request body for turn 3 =====
model: "gpt-6-luna"
input: [
{"role": "user", "content": "Hi, I'm Priya. I ride a 2019 Trek FX 3."}
{"role": "assistant", "content": "Hello Priya! It's nice to meet you!"}
{"role": "user", "content": "What tyre pressure should I start with?"}
{"role": "assistant", "content": "For most bikes, it’s best to keep the front tire at the low...
{"role": "user", "content": "What's my name, and which bike do I ride?"}
]
instructions: "You are a bike-shop assistant. Answer in one short sentence."
max_output_tokens: 40
store: false
===== openai_chat: request body for turn 3 =====
model: "gpt-6-luna"
messages: [
{"role": "system", "content": "You are a bike-shop assistant. Answer in one short sentence."}
{"role": "user", "content": "Hi, I'm Priya. I ride a 2019 Trek FX 3."}
{"role": "assistant", "content": "Hello Priya! Welcome to our bike shop and thank you for sha...
{"role": "user", "content": "What tyre pressure should I start with?"}
{"role": "assistant", "content": "Generally, most road bikes benefit from a bit more than twi...
{"role": "user", "content": "What's my name, and which bike do I ride?"}
]
max_completion_tokens: 40
===== anthropic: request body for turn 3 =====
max_tokens: 40
messages: [
{"role": "user", "content": "Hi, I'm Priya. I ride a 2019 Trek FX 3."}
{"role": "assistant", "content": [{"text": "Hello! Nice to meet you at the bike shop!", "type...
{"role": "user", "content": "What tyre pressure should I start with?"}
{"role": "assistant", "content": [{"text": "Always check the recommended tire pressure before...
{"role": "user", "content": "What's my name, and which bike do I ride?"}
]
model: "claude-haiku-5-5"
system: "You are a bike-shop assistant. Answer in one short sentence."The replies come from a 0.5B local model, so they wobble (one path even invents a new name for Priya). A hosted model would answer every path correctly. What matters here is the three request bodies, which are exactly what the real providers receive.
Now the two Gemini paths. This script is the same exercise for the google-genai SDK: an Interactions call (top-level system_instruction and a list of steps) and a generate_content call (system_instruction in the config and contents with user and model roles). It needs a real key and a spend limit, so it is hosted-only:
# s1_2_three_turns_wire_gemini.py
"""The same three-turn conversation on the two Gemini SDK paths. Hosted-only: needs GEMINI_API_KEY."""
import json
import httpx # google-genai 2.34.0 uses httpx (3.x uses httpx2: lesson 03.1, 4.5)
from google import genai
from google.genai import types
SYSTEM = "You are a bike-shop assistant. Answer in one short sentence."
USER_TURNS = [
"Hi, I'm Priya. I ride a 2019 Trek FX 3.",
"What tyre pressure should I start with?",
"What's my name, and which bike do I ride?",
]
MAX_OUT = 40
captured: dict[str, bytes] = {} # the LAST request body per SDK path
def recorder(name: str):
def hook(request) -> None: # receives an httpx Request before it is sent
captured[name] = request.content
return hook
def gemini_client(name: str) -> genai.Client: # reads GEMINI_API_KEY from the environment
return genai.Client(http_options=types.HttpOptions(
httpx_client=httpx.Client(event_hooks={"request": [recorder(name)]})))
# 4. Interactions API: top-level system_instruction + a list of steps
gi = gemini_client("gemini_interactions")
steps: list = []
for text in USER_TURNS:
steps.append({"type": "user_input", "content": [{"type": "text", "text": text}]})
it = gi.interactions.create(model="gemini-3.8-flash", system_instruction=SYSTEM, input=steps,
generation_config={"max_output_tokens": MAX_OUT}, store=False)
steps.extend(s.model_dump(exclude_none=True) for s in it.steps) # every output step
print("Gemini Interactions :", it.output_text)
# 5. generate_content: system_instruction in the config + contents with user/model roles
gg = gemini_client("gemini_generate_content")
contents: list[types.Content] = []
for text in USER_TURNS:
contents.append(types.Content(role="user", parts=[types.Part.from_text(text=text)]))
g = gg.models.generate_content(
model="gemini-3.8-flash", contents=contents,
config=types.GenerateContentConfig(system_instruction=SYSTEM, max_output_tokens=MAX_OUT))
contents.append(g.candidates[0].content) # role="model", all parts
print("Gemini generate_content:", g.text)
for name, body in captured.items():
print(f"\n===== {name}: request body for turn 3 =====")
print(json.dumps(json.loads(body), indent=2, ensure_ascii=False))1.3 Reading the differences#
Put the five request shapes side by side (three captured above, two from Google's documentation and the Gemini SDK) and the whole lesson is visible in one table:
| OpenAI Responses | OpenAI Chat Completions | Anthropic Messages | Gemini generate_content |
Gemini Interactions | |
|---|---|---|---|---|---|
| Instructions | instructions (top level) |
a system or developer message, first in messages |
system (top level) |
system_instruction in the config; on the wire systemInstruction as a Content |
system_instruction (top level) |
| The list of turns | input |
messages |
messages |
contents |
input |
| User turn | {"role": "user", ...} |
{"role": "user", ...} |
{"role": "user", ...} |
{"role": "user", "parts": [...]} |
{"type": "user_input", "content": [...]} |
| Model turn | role: "assistant" (or output items) |
role: "assistant" |
role: "assistant" |
role: "model" |
{"type": "model_output", ...} (plus other step types) |
| Content | a string, or typed parts (input_text, ...) |
a string, or typed parts (text, ...) |
a string, or typed blocks; the SDK sent the reply back as blocks | always parts |
always a list of typed content |
| Output cap | max_output_tokens |
max_completion_tokens |
max_tokens (required) |
max_output_tokens (config) |
generation_config.max_output_tokens |
Four details in the request bodies are worth a second look:
- The Gemini SDK rewrites your request. You pass
system_instruction="..."as a string; on the wire it issystemInstructionas a full Content object ({"parts": [...], "role": "user"}), and every field name is camelCase (generationConfig,maxOutputTokens). The REST API uses camelCase; the Python SDK accepts snake_case and translates. When you read Google's REST docs or debug a raw request, expect the camelCase names. (The hosted-only Gemini script above prints the real bodies if you have a key.) - The Interactions API has no roles at all. A turn is a step whose
typesays who produced it:user_inputormodel_output(and, with tools and thinking,function_call,thoughtand others). - The Anthropic SDK sent our appended reply back as a list of blocks, because we appended
m.content(the SDK's block objects) rather than a string. That's deliberate (3.6). - Chat Completions is the only format where the system prompt is just another message in the list. That's also the format of OpenRouter, Ollama, LiteLLM and most of the ecosystem, which is why converters so often start from it (Part 6).
What this means for you as an engineer: treat "a conversation" as your own data structure, and treat each provider's request shape as a serialization format for it. Most production bugs in multi-turn code come from mixing the two: storing one provider's shape and replaying it to another, or storing only part of what the provider returned.
Part 2: Roles across providers#
2.1 The role table#
As of November 2026, verified against each provider's API reference:
| Role or slot | OpenAI Responses | OpenAI Chat Completions | Anthropic Messages | Gemini generate_content |
Gemini Interactions | OpenRouter (Chat Completions) |
|---|---|---|---|---|---|---|
| Standing instructions | instructions parameter, or a developer/system message in input |
developer message (or system) |
top-level system (string or text blocks) |
system_instruction in GenerateContentConfig |
top-level system_instruction (string) |
system (or developer) message |
| Instructions mid-conversation | a developer/system message anywhere in input |
a developer/system message |
a {"role": "system"} message after a user turn (current models) |
❌ (only the one system_instruction) |
❌ | depends on the routed model |
| End user | user |
user |
user |
user |
user_input step |
user |
| The model | assistant (plus output items such as reasoning) |
assistant |
assistant |
model |
model_output step (plus thought and tool steps) |
assistant |
| Tool results | function_call_output items |
tool |
tool_result blocks inside a user message |
function_response parts |
function_result steps |
tool |
Tool messages are listed for completeness; their shapes and placement rules belong to lesson 03.5.
What each role is for, in one paragraph: instructions (system, developer, instructions, system_instruction) carry the application's rules, written by you, and the model is trained to give them more weight than anything a user says; user turns carry what the end user typed, plus anything else you choose to show the model on the user's behalf (documents, images, tool results); assistant/model turns carry what the model said before, and the model treats them as its own words, which is why faking or editing them is both powerful and risky (lesson 02.7, 3.3); tool results carry data from your code. The more trusted the role, the more careful you must be about what goes into it: never paste untrusted text (a web page, an email, a user's upload) into a system or developer message. Prompt injection, the attack that exploits this, is Module 12's topic. What to write in each role is Module 04's.
2.2 OpenAI Responses: instructions and four roles#
The Responses API gives you two ways to instruct the model:
instructions, a top-level string. OpenAI's reference describes it as "a system (or developer) message inserted into the model's context", and the text-generation guide says these instructions "will take priority over a prompt in theinputparameter".- Messages inside
inputwith one of four roles: "One ofuser,assistant,system, ordeveloper."
On the precedence between them, the Responses reference says: "Instructions given with the developer or system role take precedence over instructions given with the user role. Messages with the assistant role are presumed to have been generated by the model in previous interactions."
developer vs system. In the API reference, the two roles are listed separately but grouped together: both take precedence over user. The distinction comes from OpenAI's Model Spec (the document that defines how OpenAI's models should rank instructions), whose "chain of command", as of the 29 October 2026 version, is: Root > System > Developer > User > Guideline > "No authority by default". In the spec, "System" means OpenAI's own instructions ("system messages from OpenAI … cannot be overridden by developers or users"), "Developer" means yours, and assistant messages, tool messages and quoted or untrusted text have no authority by default. So the naming rule is:
- Use
developer(orinstructions) for your application's rules. That matches what the model is trained to expect from an application. The Chat Completions reference is explicit for reasoning models ("o1" and the "o-series" are OpenAI's earlier reasoning-model families; the rule carries over to newer ones): "With o1 models and newer, developer messages replace the previous system messages." systemstill works: it's an accepted role, and it also outranksuser, which keeps old code and Chat Completions-style histories running. The docs don't promise it behaves identically todeveloper, so preferdeveloperin new code.
instructions vs a developer message is a practical choice, not a priority one:
instructions= |
a developer message in input |
|
|---|---|---|
| Where it sits | Always first, before input |
Wherever you put it in the list |
With previous_response_id |
Not carried over: resend it on every request (7.1) | Becomes part of the stored history, so it is carried over |
| Good for | The fixed system prompt you send every turn | Context that changes during a conversation ("the promotion has ended") |
Here is what both instruction styles look like on the wire. The script uses a mock transport: the real SDK builds and sends the request into a function we wrote, which records it and returns a minimal valid response, so nothing leaves your machine:
# s2_roles_wire.py
"""Show the wire: where instructions go in each API (mock transports, nothing is sent)."""
import json
import anthropic
import httpx2
from openai import OpenAI
bodies: list[dict] = []
def openai_handler(request: httpx2.Request) -> httpx2.Response:
bodies.append(json.loads(request.content))
return httpx2.Response(200, json={ # a minimal Responses API object (documented shape)
"id": "resp_mock", "object": "response", "created_at": 0, "model": "gpt-6-luna",
"status": "completed", "output": [], "parallel_tool_calls": True,
"tool_choice": "auto", "tools": []})
def anthropic_handler(request: httpx2.Request) -> httpx2.Response:
bodies.append(json.loads(request.content))
return httpx2.Response(200, json={ # a minimal Message object (documented shape)
"id": "msg_mock", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"content": [{"type": "text", "text": "ok"}], "stop_reason": "end_turn",
"stop_sequence": None, "usage": {"input_tokens": 1, "output_tokens": 1}})
oai = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(openai_handler)))
claude = anthropic.Anthropic(api_key="sk-test",
http_client=httpx2.Client(transport=httpx2.MockTransport(anthropic_handler)))
# OpenAI Responses: `instructions` plus a developer message inside `input`
oai.responses.create(
model="gpt-6-luna",
instructions="You are a bike-shop assistant.",
input=[
{"role": "developer", "content": "Today's promotion: 10% off helmets."},
{"role": "user", "content": "Do you sell helmets?"},
],
)
# Anthropic: `system` as a list of text blocks, then a mid-conversation system message
claude.messages.create(
model="claude-haiku-5-5",
max_tokens=500,
system=[
{"type": "text", "text": "You are a bike-shop assistant."},
{"type": "text", "text": "Shop policy: free fitting with every bike."},
],
messages=[
{"role": "user", "content": "Do you sell helmets?"},
{"role": "assistant", "content": "Yes, from 40 to 180 euros."},
{"role": "user", "content": "Any discounts?"},
{"role": "system", "content": "The helmet promotion has now ended."}, # after a user turn
],
)
for body in bodies:
print(json.dumps(body, indent=1)){
"model": "gpt-6-luna",
"input": [
{
"role": "developer",
"content": "Today's promotion: 10% off helmets."
},
{
"role": "user",
"content": "Do you sell helmets?"
}
],
"instructions": "You are a bike-shop assistant."
}
{
"max_tokens": 500,
"messages": [
{
"role": "user",
"content": "Do you sell helmets?"
},
{
"role": "assistant",
"content": "Yes, from 40 to 180 euros."
},
{
"role": "user",
"content": "Any discounts?"
},
{
"role": "system",
"content": "The helmet promotion has now ended."
}
],
"model": "claude-haiku-5-5",
"system": [
{
"type": "text",
"text": "You are a bike-shop assistant."
},
{
"type": "text",
"text": "Shop policy: free fitting with every bike."
}
]
}The Anthropic half of that script is the subject of 2.4.
2.3 OpenAI Chat Completions: developer, system, user, assistant, tool#
Chat Completions has no instructions parameter: instructions are messages in the messages list. The roles, per the API reference, are developer, system, user, assistant and tool, plus the legacy function role (its companions functions and function_call are marked deprecated in favour of tools and tool_calls). The developer role is "Developer-provided instructions that the model should follow, regardless of messages sent by the user. With o1 models and newer, developer messages replace the previous system messages."
messages = [
{"role": "developer", "content": "You are a bike-shop assistant."}, # or "system"
{"role": "user", "content": "Do you sell helmets?"},
{"role": "assistant", "content": "Yes, from 40 to 180 euros."},
{"role": "user", "content": "Any discounts?"},
]Three things to know:
- Chat Completions is stateless. Its
storeparameter "(default: false)" only stores completions "for use in our model distillation or evals products"; there is no chaining (Part 7). - The ecosystem speaks this format. OpenRouter, Ollama, LiteLLM, vLLM and Gemini's OpenAI-compatibility endpoint all accept it, most with
systemrather thandeveloper. If a non-OpenAI server rejectsdeveloper, sendsystem. - It isn't deprecated. OpenAI recommends Responses for new projects and supports Chat Completions indefinitely (lesson 03.1, 5.1).
2.4 Anthropic: system, user/assistant, and mid-conversation system messages#
The system parameter is top level, and the reference types it as "string or array of TextBlockParam". The string form is the everyday one. The list form (as in s2_roles_wire.py above) matters for prompt caching: each text block can carry its own cache_control breakpoint, so you can cache a long, stable policy block separately from a shorter part that changes (lesson 03.7). Text blocks must be non-empty (the schema sets minLength: 1).
messages holds user and assistant turns. In the reference's words: "Our models are trained to operate on alternating user and assistant conversational turns… Consecutive user or assistant turns in your request will be combined into a single turn." Merging is convenient (you can send a tool result and a follow-up question as two user messages), but it means two separate user messages are not two turns to the model.
Mid-conversation system messages are new behaviour. On Claude Fable 5.2, Fable 5.1, Opus 5.5, Sonnet 5.5, Haiku 5.5 and some other recent models (the full list is on Anthropic's "Mid-conversation system messages" page), messages can also contain {"role": "system", "content": ...}. Not every current model has it: as of November 2026 the page says "This feature is not available on Claude Sonnet 5. Use the top-level system field there instead." Read the model list on that page rather than hard-coding one. The rules, as of November 2026:
- It "must immediately follow a
userturn (including auserturn that carriestool_resultblocks) or anassistantturn ending in a server tool result, and must precede anassistantturn or end the array". - "A
systemmessage that carries content cannot be the first entry inmessages." The top-levelsystemparameter is still where the main system prompt goes. - It "cannot sit between a
tool_useblock and itstool_result". Anything else is a 400 error, with one documented exception: a system message with empty content that only setsoutput_config.effort"is accepted anywhere". - It has "the same authority as the top-level
systemfield", and it doesn't invalidate the cached prefix before it (the already-cached start of the prompt, lesson 02.7, Part 7), because it's appended rather than edited in. That's its main use: changing instructions late in a long conversation without rewriting (and re-caching, and re-binding thinking blocks for) everything before it (lesson 02.7, 4.6). - Anthropic's warning: it's "not a place for untrusted content".
- Content types.
contentis a string ortextblocks, which is all this lesson uses. The page also allowstool_additionandtool_removalblocks, which change the available tools in the middle of a conversation and need beta headers (inline-tools-2026-09-15for tool changes that define tools inline,mid-conversation-tool-changes-2026-07-01for changes that name a tool). How to change tools mid-conversation is covered in lesson 03.5, 14.5; agents are Module 08A's topic. - Turn-scoped messages. A system message can carry
clear_at("never"by default, or"next_user_message") so that it applies to one turn only. That needs the beta headermid-conversation-system-clear-at-2026-08-21; without it,clear_atis rejected as an unknown field. A turn-scoped message is text only (tool blocks andoutput_configare a 400), can't carrycache_control, and must be resent verbatim: dropping it or changingclear_atlater counts as editing an earlier message.
2.5 Gemini generate_content: system_instruction and user/model#
generate_content keeps instructions out of the turn list. In the Python SDK they go in the config, types.GenerateContentConfig(system_instruction="..."); the REST field is systemInstruction, a Content that is "currently, text only". The turns go in contents, a list of Content objects, each with a role and a list of parts. The role "must be either 'user' or 'model'".
from google.genai import types
contents = [
types.Content(role="user", parts=[types.Part.from_text(text="Do you sell helmets?")]),
types.Content(role="model", parts=[types.Part.from_text(text="Yes, from 40 to 180 euros.")]),
types.Content(role="user", parts=[types.Part.from_text(text="Any discounts?")]),
]
config = types.GenerateContentConfig(system_instruction="You are a bike-shop assistant.")2.6 Gemini Interactions: system_instruction and steps#
The Interactions API (Google's recommended interface for new projects since it became generally available in June 2026; generate_content remains fully supported, see lesson 03.1, 5.3) takes system_instruction as a plain top-level string, and input in one of four forms, per the API reference: a string, a Content, a list of Content, or a list of Steps.
The trap is the word "Content". In Interactions, a Content is a single typed block such as {"type": "text", "text": "..."} or {"type": "image", ...}, with no role. So:
input form |
What it means |
|---|---|
"Do you sell helmets?" |
One user message |
{"type": "text", "text": "..."} |
One user message with one block |
[{"type": "text", ...}, {"type": "image", ...}] |
One user message with several blocks |
[{"type": "user_input", "content": [...]}, {"type": "model_output", "content": [...]}, ...] |
A multi-turn history: this is how you send earlier turns without server-side state |
Google's text-generation guide shows exactly the last pattern for stateless conversations: keep the steps, "pass the accumulated steps in the input field, and append your new turn as a user_input step", appending the model's returned steps after each call (history.append(step.model_dump())). The response's steps include only the model-generated ones (model_output, thought, function_call and so on).
2.7 OpenRouter: Chat Completions roles, translated per model#
OpenRouter's Chat Completions endpoint accepts system, developer, user, assistant and tool messages (its full API reference lists all five; its shorter overview page lists only system, user, assistant and tool). It forwards the request to whichever provider serves the model, translating the format. For Anthropic models, its reasoning guide notes in passing that "ordinary system text is still sent as the top-level system prompt". As of November 2026, OpenRouter does not document how it handles system messages for models that have no system role, or several system messages scattered through a conversation, so:
- Send one
systemmessage, first. That's the shape every upstream provider can map. - Don't rely on mid-conversation system or developer messages through OpenRouter unless you've tested the specific model and provider route.
- OpenRouter's stateless Responses-compatible endpoint takes
instructionsandinputexactly like OpenAI's Responses API (7.8).
2.8 Roles: what this means for you as an engineer#
- Keep one canonical place for instructions in your own data model and render it per provider:
instructions, adevelopermessage,system, orsystem_instruction. - Never trust the role label to make content safe. A role tells the model how much authority to give the content. It doesn't sanitize anything.
- Store late instruction changes as events, not as edits to the system prompt, so caching and reasoning continuity survive (lesson 02.7, 4.6).
Part 3: Content: strings vs typed parts#
3.1 The shorthand and the full form#
Every provider lets you write a simple text turn as a string, and every provider stores and returns content as a list of typed pieces:
| Shorthand | Full form | Typed piece called | |
|---|---|---|---|
| OpenAI Responses | {"role": "user", "content": "Hi"}, or input="Hi" (the reference: "equivalent to a text input with the user role") |
"content": [{"type": "input_text", "text": "Hi"}, ...] |
content part |
| OpenAI Chat Completions | "content": "Hi" |
"content": [{"type": "text", "text": "Hi"}, ...] |
content part |
| Anthropic | "content": "Hi" |
"content": [{"type": "text", "text": "Hi"}, ...] |
content block |
Gemini generate_content |
contents="Hi" (the SDK wraps it in a user Content) |
Content(role="user", parts=[Part(text="Hi"), ...]) |
Part |
| Gemini Interactions | input="Hi" |
{"type": "user_input", "content": [{"type": "text", "text": "Hi"}]} |
content (inside a step) |
| OpenRouter | "content": "Hi" |
Chat Completions parts | content part |
The shorthand is fine for a single text message. Use the full form as soon as a turn has more than one piece (text plus an image, a tool result plus a question), or when you need per-piece options such as Anthropic's cache_control. Your stored history should always use the full form, because that's what the providers return.
3.2 OpenAI: input parts and output items#
Input content parts (Responses): input_text, input_image and input_file. Output content parts, inside an assistant message: output_text and refusal. Images and files are lesson 03.6's topic.
The model's reply is not a single message. response.output is a list of output items, each with a type: message (the visible answer, made of output_text and refusal parts), reasoning (the model's reasoning, as a summary and encrypted content), function_call, built-in tool calls such as web_search_call, compaction (7.4), and more than a dozen others in SDK 3.42.1. response.output_text is an SDK convenience property that concatenates the output_text parts of all message items; it isn't a field in the JSON.
On the input side there is one more item type worth knowing: {"type": "item_reference", "id": "..."}, a pointer to an item the server already holds, which saves you re-sending it. It is covered with the other server-side mechanics in 7.2.
3.3 Anthropic: content blocks#
Anthropic calls every piece a content block. In SDK 2.4.0 the input block types are text, image, document, search_result, tool_use, tool_result, thinking, redacted_thinking, the server-tool blocks (server_tool_use, web_search_tool_result, web_fetch_tool_result, code_execution_tool_result and others) and container_upload. The response's content uses the same set minus the input-only types (image, document, search_result, tool_result).
| Block | Who sends it | What it's for |
|---|---|---|
text |
both | Text. citations may be attached in responses (lesson 03.6) |
image, document |
you, in user turns |
Images and PDFs/text documents (lesson 03.6) |
tool_use |
the model | A request to call your tool (lesson 03.5) |
tool_result |
you, in a user turn |
Your tool's answer (lesson 03.5) |
thinking |
the model | Its reasoning (often summarized) plus a signature: "an encrypted copy of the full reasoning that you pass back unchanged" |
redacted_thinking |
the model | Reasoning that was safety-redacted, as encrypted data; pass it back unchanged too |
A Claude reply usually contains several blocks, for example [thinking, text] or [thinking, text, tool_use]. Pick the text by type (block.type == "text"), never by position: response.content[0] is a thinking block on current models, which think by default.
3.4 Gemini: Parts, and Interactions steps#
generate_content. A Content is a role plus a list of Parts. A Part is one of a set of mutually exclusive fields: text, inline_data (bytes plus MIME type), file_data (a file URI), function_call, function_response, executable_code, code_execution_result and others, plus two flags that matter here: thought=True marks a thought-summary part, and thought_signature holds "an opaque signature for the thought so it can be reused in subsequent requests". The model's reply is response.candidates[0].content, a Content with role="model". response.text is an SDK convenience property that joins the non-thought text parts.
Interactions. The reply is interaction.steps, a list of typed steps: model_output (holding content blocks), thought (with a signature and an optional summary), function_call, built-in tool call/result steps and others. interaction.output_text is the convenience accessor. When you interactions.get a stored interaction, Google says it "also includes user_input steps for full context, though the interactions.create response only returns model-generated steps".
3.5 Where the reply lives, per provider#
| The full reply (store and replay this) | The convenience text (display this) | Reasoning data inside it | |
|---|---|---|---|
| OpenAI Responses | response.output (list of items) |
response.output_text |
reasoning items with encrypted_content |
| OpenAI Chat Completions | response.choices[0].message |
.message.content |
none returned; reasoning stays on OpenAI's side |
| Anthropic | response.content (list of blocks) |
the text blocks |
thinking / redacted_thinking blocks with signatures |
Gemini generate_content |
response.candidates[0].content |
response.text |
thought_signature on parts; thought parts with include_thoughts |
| Gemini Interactions | interaction.steps |
interaction.output_text |
thought steps with signature |
| OpenRouter | response.choices[0].message (including reasoning_details) |
.message.content |
the reasoning_details array (arrives in model_extra with the openai SDK) |
3.6 Append the full output, not just the text#
Reasoning models produce hidden reasoning, and the providers return an opaque, signed or encrypted form of it so that the model can continue its train of thought on the next request. Lesson 02.8, 8.2 explains why; the practical rule is: append everything the provider returned, unchanged. Rebuilding an assistant turn from its text silently throws away that continuity, and in tool loops it causes validation errors.
Per provider, "everything" means:
- OpenAI (stateless): append every item of
response.output, reasoning items included. Withstore=False(or under Zero Data Retention, ZDR: a contract option under which the provider keeps nothing after responding, 7.5), reasoning items carryencrypted_content. As of November 2026, OpenAI's reasoning guide says they include it "by default" in stateless mode, and that "the API still accepts the legacyreasoning.encrypted_contentvalue inincludefor compatibility, but doesn't require it". Passinginclude=["reasoning.encrypted_content"]is therefore harmless and makes the intent explicit. Withstore=Trueandprevious_response_id, the server keeps them for you (Part 7). - Anthropic: append
response.contentas the assistant message, thinking and redacted-thinking blocks with their signatures included, in the original order, unmodified. Editing them is a 400: "thinkingorredacted_thinkingblocks in the latest assistant message cannot be modified." - Gemini
generate_content: appendresponse.candidates[0].contentas it is. Google: "pass the full, unmodified conversation history (including thought signatures) incontents. The SDKs handle this automatically", which holds as long as you keep the SDK'sContentobjects (or dump and reload them without losingthought_signature). A request missing a signature it needs can end with finish reasonMISSING_THOUGHT_SIGNATURE. - Gemini Interactions (stateless): append every returned step,
thoughtsteps included. Google: "You MUST always resend allthoughtblocks exactly as they were received." - OpenRouter: keep the assistant message's
reasoning_detailsarray and send it back unchanged; its docs say "you cannot rearrange or modify the sequence of these blocks".
This sample runs a two-turn conversation with reasoning on all three first-party providers, and on both Gemini APIs, appending the full output each time:
# s3_7_full_output_reasoning.py
"""Append the FULL assistant output, reasoning included, on every first-party provider."""
from typing import Any
import anthropic
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI
load_dotenv()
SYSTEM = "You are a bike-shop assistant. Answer in two sentences."
TURN_1 = "My commute is 12 km with a steep 2 km climb. Which gearing should I look for?"
TURN_2 = "And if I switch to an e-bike?"
# --- OpenAI Responses, stateless: store=False, encrypted reasoning comes back ------------
client = OpenAI()
history: list[Any] = [{"role": "user", "content": TURN_1}]
for next_turn in (TURN_2, None):
response = client.responses.create(
model="gpt-6-luna",
instructions=SYSTEM, # resent on every call
input=history,
reasoning={"effort": "low"},
store=False, # nothing kept on OpenAI's side
include=["reasoning.encrypted_content"], # now the default when store=False; harmless
max_output_tokens=2_000,
)
print("OpenAI items:", [(item.type, len(getattr(item, "encrypted_content", None) or ""))
for item in response.output])
history += response.output # reasoning item + message, unchanged
if next_turn:
history.append({"role": "user", "content": next_turn})
print("OpenAI answer:", response.output_text, "\n")
# --- Anthropic: append response.content, thinking blocks and signatures included ---------
claude = anthropic.Anthropic()
messages: list[Any] = [{"role": "user", "content": TURN_1}]
for next_turn in (TURN_2, None):
message = claude.messages.create(
model="claude-haiku-5-5",
max_tokens=4_000,
system=SYSTEM,
thinking={"type": "adaptive", "display": "summarized"},
output_config={"effort": "low"},
messages=messages,
)
print("Claude blocks:", [(b.type, len(getattr(b, "signature", "") or "")) for b in message.content])
messages.append({"role": "assistant", "content": message.content}) # every block
if next_turn:
messages.append({"role": "user", "content": next_turn})
print("Claude answer:", next(b.text for b in message.content if b.type == "text"), "\n")
# --- Gemini generate_content: append candidates[0].content (keeps thought signatures) ----
gemini = genai.Client()
config = types.GenerateContentConfig(
system_instruction=SYSTEM,
thinking_config=types.ThinkingConfig(thinking_level=types.ThinkingLevel.LOW, include_thoughts=True),
max_output_tokens=2_000,
)
contents: list[types.Content] = [types.Content(role="user", parts=[types.Part.from_text(text=TURN_1)])]
for next_turn in (TURN_2, None):
result = gemini.models.generate_content(model="gemini-3.8-flash", contents=contents, config=config)
content = result.candidates[0].content if result.candidates else None
if content is None:
raise RuntimeError(f"No content: {result.prompt_feedback}")
print("Gemini parts:", [("thought" if p.thought else "text", p.thought_signature is not None)
for p in content.parts or []])
contents.append(content) # role="model", every part, unchanged
if next_turn:
contents.append(types.Content(role="user", parts=[types.Part.from_text(text=next_turn)]))
print("Gemini answer:", result.text, "\n")
# --- Gemini Interactions, stateless: resend every step, thought steps included -----------
steps: list[Any] = [{"type": "user_input", "content": [{"type": "text", "text": TURN_1}]}]
for next_turn in (TURN_2, None):
interaction = gemini.interactions.create(
model="gemini-3.8-flash",
system_instruction=SYSTEM,
input=steps,
store=False,
generation_config={"thinking_level": "low", "thinking_summaries": "auto",
"max_output_tokens": 2_000},
)
print("Interactions steps:", [s.type for s in interaction.steps or []])
steps.extend(s.model_dump(exclude_none=True) for s in interaction.steps or [])
if next_turn:
steps.append({"type": "user_input", "content": [{"type": "text", "text": next_turn}]})
print("Interactions answer:", interaction.output_text)OpenAI items: [('reasoning', 1376), ('message', 0)]
OpenAI items: [('reasoning', 1504), ('message', 0)]
OpenAI answer: With an e-bike, wide-range gearing matters less, because the motor's assist flattens the climb. Prioritize a mid-drive motor with enough torque for 2 km of steep road.
Claude blocks: [('thinking', 412), ('text', 0)]
Claude blocks: [('thinking', 396), ('text', 0)]
Claude answer: With an e-bike, the motor does much of the climbing, so a simpler gear range is fine. Choose a mid-drive motor with good torque and a battery that covers 24 km with margin.
Gemini parts: [('thought', False), ('text', True)]
Gemini parts: [('thought', False), ('text', True)]
Gemini answer: An e-bike's motor reduces how low your gears need to go, so a standard 1x drivetrain or an internal hub is enough. Focus on motor torque and battery range instead.
Interactions steps: ['thought', 'model_output']
Interactions steps: ['thought', 'model_output']
Interactions answer: On an e-bike the motor handles most of the climb, so you can choose simpler gearing. Look for a torquey mid-drive motor and a battery with comfortable range.Read the output for the shape: each OpenAI reply is a reasoning item (its encrypted_content is the long opaque string you must keep) followed by a message; each Claude reply is a thinking block with a signature followed by text; Gemini's reply carries thought signatures on its parts; Interactions returns a thought step before the model_output step. All of it goes back into the history.
What a local run of this sample showed. The sample compiles and passes a static type check (pyright) against the SDK versions named in Setup. Run unchanged against the local stand-in (a "smoke run": does the code run end to end? Only the OpenAI and Anthropic paths can run there: Gemini has no local stand-in), it stops at the first call, because Ollama returns 400 "gpt-6-luna" does not support thinking: the small local model can't reason. With the reasoning options removed (delete the reasoning=, thinking=, output_config= and thinking_config= arguments and the two thinking_* keys in generation_config), the same append logic runs end to end on the OpenAI and Anthropic paths, so you can still practise those mechanics for free (the two Gemini paths are hosted-only and were not run). That's typical: reasoning data is the part of a conversation you can only see with a hosted reasoning model.
Part 4: Message-shape rules and the errors they cause#
4.1 The rules, side by side#
A conversation can be valid JSON and still be rejected. These are the shape rules as of November 2026. "Not documented" means we found no rule in the provider's reference or guides; it doesn't mean anything goes.
| Rule | OpenAI (Responses / Chat Completions) | Anthropic Messages | Gemini (generate_content / Interactions) |
OpenRouter |
|---|---|---|---|---|
| At least one turn | Chat Completions: an empty messages list is a 400 |
messages is required |
contents / input are required |
As Chat Completions |
| First turn | Instructions may come first; no documented rule after that | No explicit rule in the reference, but the models are trained on conversations that start with user; a content-carrying system message cannot be first |
No documented rule; start with user |
Start with system (optional), then user |
| Alternation | Not required | "Consecutive user or assistant turns … will be combined into a single turn" |
Not documented; merging consecutive same-role turns yourself is the safe choice | Depends on the upstream provider |
| Last turn (prefill) | No prefill feature documented | 400 on Claude 4.6 and later (4.2) | 400 on Gemini 3.6 Flash, 3.5 Flash-Lite and later | Supported as a feature, but the upstream model may reject it |
| Valid roles | user, assistant, system, developer (Chat: plus tool) |
user, assistant, and system within the placement rules of 2.4 |
user, model / steps by type |
system, developer, user, assistant, tool |
| Empty content | Not documented | Text blocks have minLength: 1; send no empty text |
Not documented (the SDK's chat helper treats empty parts as invalid, Part 8) |
Not documented |
| Documents | Files go in user input (lesson 03.6) | Under anthropic-version: 2026-10-21, a document block directly in an assistant message is a 400: "Send documents in user messages instead" |
In user turns | In user turns |
| Citations on input text | — | Under 2026-10-21, a text block with a non-empty citations array in a user message is a 400 |
— | — |
| Tool results | function_call_output must reference a call_id from the model |
tool_result blocks must immediately follow the assistant's tool_use, and come FIRST in the user message's content |
A function_response must answer the model's function_call |
As Chat Completions |
| Request size | Per-endpoint limits: see lesson 03.6, 1.7 | A request over the limit is a 413 request_too_large that you fix, not retry (lesson 03.8); the current limit (as of 2026-11-04) is in lesson 03.6, 1.7 |
Inline-data limits: see lesson 03.6, 1.7 | Depends on the upstream provider |
Tool-result placement is a preview: lesson 03.5 owns it. Request sizes change often, so they are stated once, in lesson 03.6, 1.7 (media) and lesson 03.8 (the 413 error). An assistant turn with no text, which would make the empty-content rule bite, is handled in 5.4. Token limits, as opposed to byte limits, are in lesson 02.7, 2.6.
4.2 Assistant prefill is gone#
Prefill meant ending the conversation with a partial assistant turn, such as {"role": "assistant", "content": "{"}, so the model would continue from there: a popular trick for forcing JSON or skipping a preamble (lesson 02.2, 12.3 explains why it worked). As of November 2026:
- Anthropic: "Claude 4.6 and later models … do not support prefilling assistant messages". A request whose last message is an assistant turn returns a 400
invalid_request_errorwith the message "This model does not support assistant message prefill. The conversation must end with a user message." - Gemini: starting with Gemini 3.6 Flash and Gemini 3.5 Flash-Lite, "API requests ending with a non-empty model role turn are disallowed and return an HTTP 400 Error", and the change applies to "all future Gemini model releases".
- OpenAI: no prefill feature is documented for either API.
- OpenRouter: documents "Assistant prefill" as a feature ("OpenRouter supports asking models to complete a partial response"), but it can only work where the upstream model allows it, which excludes current Claude and Gemini models.
What to use instead:
| You used prefill to... | Use instead |
|---|---|
| Force JSON or a fixed format | Structured output (lesson 03.4) |
| Skip a preamble or set a tone | Instructions in the system/developer message (Module 04) |
| Continue a cut-off answer | Append the partial answer as the assistant turn, then a user turn such as "Continue exactly where you stopped" (lesson 02.7, 2.6) |
4.3 Try it: real errors from wrong shapes#
This script provokes shape errors in two ways. Part A sends bad requests to the free local stand-in and prints the real errors it returns. Part B covers rules the stand-in doesn't enforce: it uses the real SDKs with a mock server (an httpx2.MockTransport for Anthropic, an httpx.MockTransport for Google) that returns the error bodies documented by Anthropic and Google. The fixtures are visible in the code.
# s4_3_shape_errors.py
"""Wrong message shapes and the errors they cause.
Part A runs against the free local stand-in (real errors from a real server).
Part B uses mock servers, because the stand-in does NOT enforce these rules: the fixtures
copy the error bodies documented by Anthropic and Google.
"""
import json
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import errors, types
# ---------------------------------------------------------------- A. real, local errors
local_claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")
local_openai = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
try: # an empty conversation
local_claude.messages.create(model="claude-haiku-5-5", max_tokens=20, messages=[])
except anthropic.BadRequestError as e:
print("A1 Anthropic format, no messages ->", e.status_code, e.body)
try: # the same mistake in Chat Completions
local_openai.chat.completions.create(model="gpt-6-luna", messages=[])
except openai.BadRequestError as e:
print("A2 Chat Completions, no messages ->", e.status_code, e.message)
try: # caught by the SDK before anything is sent: max_tokens is required by Anthropic
local_claude.messages.create(model="claude-haiku-5-5", # type: ignore[call-overload]
messages=[{"role": "user", "content": "Hi"}])
except TypeError as e:
print("A3 Anthropic SDK, no max_tokens ->", type(e).__name__, str(e)[:60], "...")
# ---------------------------------------------------------------- B. mocked provider errors
def mock_anthropic(error_message: str) -> anthropic.Anthropic:
"""A real Anthropic client whose HTTP layer returns one documented 400 error."""
def handler(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(400, headers={"request-id": "req_mock_01"}, json={
"type": "error", "request_id": "req_mock_01",
"error": {"type": "invalid_request_error", "message": error_message}})
return anthropic.Anthropic(api_key="sk-test", max_retries=0,
http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))
# B1. Prefill: the conversation ends with an assistant turn (Claude 4.6 and later)
claude = mock_anthropic("This model does not support assistant message prefill. "
"The conversation must end with a user message.")
try:
claude.messages.create(model="claude-haiku-5-5", max_tokens=100, messages=[
{"role": "user", "content": "Give me a JSON object describing a bike."},
{"role": "assistant", "content": "{"}, # the old prefill trick
])
except anthropic.BadRequestError as e:
print("B1 Anthropic prefill ->", e.status_code, e.body["error"]["message"]) # type: ignore[index]
# B2. Editing a thinking block in the latest assistant turn before sending it back
claude = mock_anthropic("`thinking` or `redacted_thinking` blocks in the latest assistant "
"message cannot be modified. These blocks must remain as they were "
"in the original response.")
try:
claude.messages.create(model="claude-haiku-5-5", max_tokens=100, messages=[
{"role": "user", "content": "Which tyre is wider, 35 mm or 40 mm?"},
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "(edited by our app)", "signature": "EqQBCk..."},
{"type": "text", "text": "40 mm."}]},
{"role": "user", "content": "By how much?"},
])
except anthropic.BadRequestError as e:
print("B2 Anthropic edited thinking ->", e.status_code, e.body["error"]["message"][:70], "...") # type: ignore[index]
# B3. Gemini 3.6+ rejects a request whose last turn is a non-empty model turn
seen: list[dict] = []
def google_handler(request: httpx.Request) -> httpx.Response:
seen.append(json.loads(request.content))
return httpx.Response(400, json={"error": {
"code": 400, "status": "INVALID_ARGUMENT",
"message": "API requests ending with a non-empty model role turn are disallowed."}})
gemini = genai.Client(api_key="test-key", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=httpx.MockTransport(google_handler))))
try:
gemini.models.generate_content(model="gemini-3.8-flash", contents=[
types.Content(role="user", parts=[types.Part.from_text(text="Name a bike brand.")]),
types.Content(role="model", parts=[types.Part.from_text(text="Sure: ")]),
])
except errors.ClientError as e:
print("B3 Gemini trailing model turn ->", e.code, e.status, e.message)
print(" roles the SDK sent:", [c["role"] for c in seen[0]["contents"]])A1 Anthropic format, no messages -> 400 {'type': 'error', 'error': {'type': 'invalid_request_error', 'message': 'messages is required'}, 'request_id': 'req_8cda909147784eec09b8cd50'}
A2 Chat Completions, no messages -> 400 Error code: 400 - [] is too short - 'messages'
A3 Anthropic SDK, no max_tokens -> TypeError Missing required arguments; Expected either ('max_tokens', ' ...
B1 Anthropic prefill -> 400 This model does not support assistant message prefill. The conversation must end with a user message.
B2 Anthropic edited thinking -> 400 `thinking` or `redacted_thinking` blocks in the latest assistant messa ...
B3 Gemini trailing model turn -> 400 INVALID_ARGUMENT API requests ending with a non-empty model role turn are disallowed.
roles the SDK sent: ['user', 'model']What to notice:
- The SDKs turn a 400 into a typed exception:
anthropic.BadRequestError,openai.BadRequestError,google.genai.errors.ClientError. The parsed error body is one.body(Anthropic, OpenAI) ore.code,e.statusande.message(Google). Lesson 03.8 covers the whole error taxonomy; the point here is that shape errors are 400s you must fix, never retry. - A3 never reached a server. The Anthropic SDK checks required arguments itself, and
max_tokensis required by the Messages API. - B3's last line is the evidence: the SDK sent the roles
['user', 'model'], a history ending in a model turn.
The local stand-in enforced only the "no messages" rule. In probes for this lesson, Ollama 0.32.5 accepted all of the following without complaint: a trailing assistant turn (prefill) on the Anthropic format, empty text and empty content lists, a conversation starting with an assistant turn, and "role": "model" in the OpenAI and Anthropic formats. Gemini has no local stand-in, so its rules (B3) are shown only with the mock server. That's exactly why a pre-flight check in your own code is worth having.
4.4 A pre-flight checker#
A few lines of pure Python catch most shape mistakes before they cost a round trip (and before a local test passes something production will reject). Save it as s4_4_preflight.py: later demos import check_turns from it, which is why the demo cases sit under an if __name__ == "__main__": guard.
# s4_4_preflight.py
"""Pre-flight checks: catch message-shape mistakes before they cost a round trip."""
from typing import Any
ASSISTANT_ROLE = {"openai": "assistant", "anthropic": "assistant", "gemini": "model",
"interactions": "assistant"}
STEP_ROLE = {"user_input": "user", "model_output": "assistant"} # Interactions steps have no roles
def check_turns(provider: str, turns: list[dict[str, Any]]) -> list[str]:
"""turns: Responses `input`, Anthropic `messages`, Gemini `contents`, or Interactions
steps (provider "interactions"), as dicts. Alternation is deliberately NOT checked."""
problems: list[str] = []
# Responses items without a role (reasoning, function_call...) and Interactions steps other
# than user_input/model_output are not conversational turns: this checker skips them.
turns = [t for t in turns if "role" in t or t.get("type") in STEP_ROLE]
if not turns:
return ["the conversation is empty"]
allowed = {"user", ASSISTANT_ROLE[provider]}
if provider == "openai":
allowed |= {"system", "developer"}
if provider == "anthropic":
allowed |= {"system"} # mid-conversation system, current models
roles = [t.get("role") or STEP_ROLE.get(t.get("type", ""), t.get("type")) for t in turns]
for i, (turn, role) in enumerate(zip(turns, roles)):
if role not in allowed:
problems.append(f"turn {i}: role {role!r} is not valid here (allowed: {sorted(allowed)})")
body = turn.get("content", turn.get("parts"))
if body in ("", [], None):
problems.append(f"turn {i}: empty content")
elif isinstance(body, list):
for j, part in enumerate(body):
if part.get("type") in (None, "text", "input_text") and part.get("text") == "":
problems.append(f"turn {i} part {j}: empty text")
if provider == "anthropic" and role == "assistant" and part.get("type") == "document":
problems.append(f"turn {i}: document block in an assistant turn")
if provider == "anthropic" and role == "system" and (i == 0 or roles[i - 1] != "user"):
problems.append(f"turn {i}: a system message must directly follow a user turn")
if roles[-1] == ASSISTANT_ROLE[provider]:
problems.append("the last turn is an assistant/model turn (prefill is rejected)")
first_chat = next((r for r in roles if r not in ("system", "developer")), None)
if first_chat != "user":
problems.append("the first non-system turn should be a user turn")
return problems
if __name__ == "__main__":
cases = {
("anthropic", "prefill"): [{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "{"}],
("anthropic", "system first + document in assistant"): [
{"role": "system", "content": "Be brief."},
{"role": "user", "content": "Summarize the manual."},
{"role": "assistant", "content": [{"type": "document", "source": {"type": "text",
"media_type": "text/plain", "data": "..."}}]},
{"role": "user", "content": "Thanks"}],
("gemini", "OpenAI-style roles"): [{"role": "user", "parts": [{"text": "Hi"}]},
{"role": "assistant", "parts": [{"text": "Hello"}]},
{"role": "user", "parts": [{"text": ""}]}],
("openai", "valid"): [{"role": "developer", "content": "Be brief."},
{"role": "user", "content": "Hi"}],
}
for (provider, label), turns in cases.items():
print(f"{provider:9s} {label}:")
for problem in check_turns(provider, turns) or ["OK"]:
print(" -", problem)anthropic prefill:
- the last turn is an assistant/model turn (prefill is rejected)
anthropic system first + document in assistant:
- turn 0: a system message must directly follow a user turn
- turn 2: document block in an assistant turn
gemini OpenAI-style roles:
- turn 1: role 'assistant' is not valid here (allowed: ['model', 'user'])
- turn 2 part 0: empty text
openai valid:
- OKThe checker simplifies some rules (Anthropic's system-message placement has more cases, see 2.4 and Exercise 3), and it deliberately does not check alternation: Anthropic merges consecutive turns, and for the other providers no rule is documented. It also skips items without a role (reasoning items, function calls) and treats Interactions steps (user_input, model_output) as user and assistant turns, so 6.3 can run it on the converter's output for every format. Extend it to the exact rules you rely on. In production, run a check like this where conversations enter your system (when you load from the database and when you build a request), log violations with the conversation ID, and fail fast in tests. It doesn't replace the provider's validation; it gives you a clear error message, in your own logs, before the request leaves.
What this means for you as an engineer: shape errors are deterministic. They come from your history-building code, not from the model, so test them like any other serialization code: type-check the request dicts, unit-test the converter, and assert on the last turn's role.
Part 5: Client-managed conversations done properly#
Lesson 02.7, 3.4 showed the minimal version: keep a Python list, append each turn, send the whole list. That's correct, and it's enough for a script. A product needs more: conversations that survive a server restart, that can be audited and deleted, that record cost, and that don't break when you change provider or trim history. This part builds that, in two files you can reuse: chatfmt.py (the canonical format and converters, shown in full in Part 6) and convo_store.py (the store).
5.1 What a history must hold#
Store every assistant turn in two views:
- Portable parts: the text (and images) of the turn, in a provider-neutral form. Any provider can be sent these.
- The provider-native payload: exactly what the provider returned, serialized to JSON (OpenAI output items, Anthropic content blocks, Gemini parts with their thought signatures, Interactions steps, OpenRouter's message with
reasoning_details). Only the same provider can be sent this, and it must be sent unchanged.
When you build the next request, use the native payload if the target is the provider that produced it, and the portable parts otherwise. That one rule gives you reasoning continuity on the same provider, and portability across providers. In chatfmt.py, a message looks like this:
@dataclass
class Part:
type: Literal["text", "image"]
text: str | None = None
media_type: str | None = None # e.g. "image/png" (images only)
data_b64: str | None = None # base64-encoded bytes (images only)
# property is_empty: True for an image with no data, or text that is empty or only whitespace
@dataclass
class Message:
role: Role # "user" | "assistant"
parts: list[Part]
native: dict[str, Any] | None = None # {"provider": ..., "model": ..., "payload": [...]}
# property has_portable_content: True if any part is non-empty
# property has_compaction: True if the native payload holds a compaction item (7.4)has_portable_content is what makes the rule safe to apply: a reply with no text (a tool-only reply, a refusal, a reply cut off while thinking) has parts == [], and the builders never replay or send it as an empty turn (5.4).
Alongside each turn, keep the metadata you'll need later: which provider and model produced it, the finish reason, token usage, the provider's request ID and response ID, and a timestamp. Usage needs care, because the providers count differently:
5.2 A persistent conversation store#
Here is a complete store on SQLite, using only the standard library. The schema has three tables: conversations (one row per chat), messages (one row per turn, with the provider metadata) and parts (the portable content of each turn).
# convo_store.py
"""convo_store.py: a persistent conversation store on SQLite (standard library only).
Keeps two views of every assistant turn:
* portable parts (text, images) that any provider can read, and
* the provider-native payload exactly as returned (reasoning items, thinking blocks,
thought signatures), so the same provider can be sent its own output back unchanged.
Scope: roles are user/assistant and parts are text/image. Tool calls, tool results and a
`system` role are deliberately not stored here; lesson 03.11 extends the schema for them.
"""
from __future__ import annotations
import json
import sqlite3
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from chatfmt import Conversation, Message, Part
SCHEMA = """
CREATE TABLE IF NOT EXISTS conversations (
id TEXT PRIMARY KEY,
user_ref TEXT NOT NULL, -- a keyed hash of your user ID, never an email
title TEXT,
system_prompt TEXT, -- sent on every request; versioned with the row
metadata TEXT NOT NULL DEFAULT '{}',
provider_state TEXT NOT NULL DEFAULT '{}', -- server-side IDs: {"openai_conversation": "conv_..."}
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT -- soft delete first, purge later (see 10.4)
);
CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
conversation_id TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
seq INTEGER NOT NULL, -- order within the conversation: 0, 1, 2, ...
role TEXT NOT NULL CHECK (role IN ('user', 'assistant')), -- 03.11 widens this
provider TEXT, -- who produced it (assistant turns)
model TEXT, -- the model ID the provider reported
native TEXT, -- provider-native payload, JSON, replayed as-is
compacted_by TEXT, -- id of the compaction message that replaced this turn
finish_reason_raw TEXT, -- the provider's own word: completed, end_turn, STOP...
input_tokens INTEGER, -- TOTAL input: uncached + cached + written (03.7's `input` is only the uncached part)
cached_tokens INTEGER, -- cache READS only; the cache-write count is inside usage_raw
output_tokens INTEGER, -- includes reasoning tokens
reasoning_tokens INTEGER,
usage_raw TEXT, -- the provider's usage object, unmodified
request_id TEXT, -- for support tickets (lesson 03.1)
provider_response_id TEXT, -- resp_..., msg_..., interaction id
created_at TEXT NOT NULL,
UNIQUE (conversation_id, seq) -- two writers can't both append turn N
);
CREATE TABLE IF NOT EXISTS parts (
message_id TEXT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
idx INTEGER NOT NULL,
type TEXT NOT NULL CHECK (type IN ('text', 'image')), -- 03.11 adds tool parts
text TEXT,
media_type TEXT,
data_b64 TEXT, -- small images only; store big files in object storage
PRIMARY KEY (message_id, idx)
);
CREATE INDEX IF NOT EXISTS idx_conversations_user ON conversations(user_ref, updated_at);
"""
def _now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
class ConversationStore:
def __init__(self, path: str = "conversations.db") -> None:
Path(path).parent.mkdir(parents=True, exist_ok=True) # e.g. out/ for the demos
self.db = sqlite3.connect(path)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA foreign_keys = ON") # SQLite needs this for CASCADE
self.db.executescript(SCHEMA)
def create(self, user_ref: str, system_prompt: str | None, title: str | None = None,
metadata: dict[str, str] | None = None) -> str:
conversation_id = f"cv_{uuid.uuid4().hex[:12]}"
now = _now()
with self.db: # a transaction: all or nothing
self.db.execute(
"INSERT INTO conversations (id, user_ref, title, system_prompt, metadata,"
" created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
(conversation_id, user_ref, title, system_prompt,
json.dumps(metadata or {}), now, now))
return conversation_id
def append(self, conversation_id: str, message: Message, *, provider: str | None = None,
finish_reason_raw: str | None = None, usage: dict[str, Any] | None = None,
request_id: str | None = None, provider_response_id: str | None = None) -> int:
"""Append one message; returns its sequence number."""
usage = usage or {}
with self.db:
self._require_active(conversation_id)
(seq,) = self.db.execute(
"SELECT COALESCE(MAX(seq) + 1, 0) FROM messages WHERE conversation_id = ?",
(conversation_id,)).fetchone()
message_id = f"msg_{uuid.uuid4().hex[:12]}"
native = message.native
self.db.execute(
"INSERT INTO messages (id, conversation_id, seq, role, provider, model, native,"
" finish_reason_raw, input_tokens, cached_tokens, output_tokens, reasoning_tokens,"
" usage_raw, request_id, provider_response_id, created_at)"
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(message_id, conversation_id, seq, message.role,
provider or (native or {}).get("provider"), (native or {}).get("model"),
json.dumps(native) if native else None, finish_reason_raw,
usage.get("input_tokens"), usage.get("cached_tokens"),
usage.get("output_tokens"), usage.get("reasoning_tokens"),
json.dumps(usage.get("raw")) if usage.get("raw") else None,
request_id, provider_response_id, _now()))
self.db.executemany(
"INSERT INTO parts (message_id, idx, type, text, media_type, data_b64)"
" VALUES (?, ?, ?, ?, ?, ?)",
[(message_id, i, p.type, p.text, p.media_type, p.data_b64)
for i, p in enumerate(message.parts)])
self.db.execute("UPDATE conversations SET updated_at = ? WHERE id = ?",
(_now(), conversation_id))
return seq
def _require_active(self, conversation_id: str) -> None:
row = self.db.execute("SELECT deleted_at FROM conversations WHERE id = ?",
(conversation_id,)).fetchone()
if row is None or row["deleted_at"] is not None:
raise KeyError(conversation_id) # unknown, or soft-deleted
def load(self, conversation_id: str, raw: bool = False) -> Conversation:
"""The history to send: turns replaced by a compaction message are skipped. With
raw=True you get the full transcript instead (every turn, but not the opaque compaction
items): for an audit, or to continue on another provider."""
row = self.db.execute(
"SELECT system_prompt FROM conversations WHERE id = ? AND deleted_at IS NULL",
(conversation_id,)).fetchone()
if row is None:
raise KeyError(conversation_id)
conv = Conversation(system=row["system_prompt"])
for m in self.db.execute(
"SELECT id, role, native FROM messages WHERE conversation_id = ?"
+ ("" if raw else " AND compacted_by IS NULL") + " ORDER BY seq",
(conversation_id,)):
parts = [Part(p["type"], text=p["text"], media_type=p["media_type"],
data_b64=p["data_b64"])
for p in self.db.execute(
"SELECT * FROM parts WHERE message_id = ? ORDER BY idx", (m["id"],))]
native = json.loads(m["native"]) if m["native"] else None
message = Message(m["role"], parts, native=native)
if raw and message.has_compaction and not message.has_portable_content:
continue # an opaque summary: not part of the transcript
conv.messages.append(message)
return conv
def usage_totals(self, conversation_id: str) -> dict[str, int]:
row = self.db.execute(
"SELECT COUNT(*) AS turns, SUM(input_tokens) AS input, SUM(output_tokens) AS output"
" FROM messages WHERE conversation_id = ? AND role = 'assistant'",
(conversation_id,)).fetchone()
return {"assistant_turns": row["turns"], "input_tokens": row["input"] or 0,
"output_tokens": row["output"] or 0}
def mark_compacted(self, conversation_id: str, compaction_seq: int) -> int:
"""Record that the message at `compaction_seq` (a compaction item you appended) replaces
every earlier turn. The rows stay in the database; load() just skips them. Returns how
many turns were marked."""
with self.db:
self._require_active(conversation_id)
found = self.db.execute("SELECT id FROM messages WHERE conversation_id = ? AND seq = ?",
(conversation_id, compaction_seq)).fetchone()
if found is None:
raise ValueError(f"no message with seq {compaction_seq} in conversation {conversation_id}")
by = found[0]
return self.db.execute(
"UPDATE messages SET compacted_by = ? WHERE conversation_id = ? AND seq < ?"
" AND compacted_by IS NULL", (by, conversation_id, compaction_seq)).rowcount
def set_provider_state(self, conversation_id: str, key: str, value: str | None) -> None:
"""Remember a server-side ID, e.g. the last OpenAI response ID. None removes the key."""
with self.db:
self._require_active(conversation_id)
state = self.get_provider_state(conversation_id)
if value is None:
state.pop(key, None)
else:
state[key] = value
self.db.execute("UPDATE conversations SET provider_state = ?, updated_at = ? WHERE id = ?",
(json.dumps(state), _now(), conversation_id))
def get_provider_state(self, conversation_id: str) -> dict[str, str]:
row = self.db.execute("SELECT provider_state FROM conversations WHERE id = ?",
(conversation_id,)).fetchone()
if row is None:
raise KeyError(conversation_id)
return json.loads(row["provider_state"])
def soft_delete(self, conversation_id: str) -> None:
"""Hide the conversation (load() and append() stop seeing it) but keep the rows, so
a failed provider-side deletion can be retried. Call delete() once that's done."""
with self.db:
self.db.execute("UPDATE conversations SET deleted_at = ? WHERE id = ?",
(_now(), conversation_id))
def delete(self, conversation_id: str) -> None:
"""Hard delete: the messages and parts go with it (ON DELETE CASCADE)."""
with self.db:
self.db.execute("DELETE FROM conversations WHERE id = ?", (conversation_id,))The design decisions, and why:
| Decision | Why |
|---|---|
UNIQUE (conversation_id, seq) and a transaction around each append |
Two requests for the same conversation (two browser tabs, a retry) can't both write turn N. One of them fails loudly instead of interleaving turns |
native stored as JSON, untouched |
Reasoning items, signatures and thought signatures must go back exactly as received. Never "clean up" this column |
system_prompt on the conversation |
Instructions are resent on every request; storing them per conversation keeps old conversations reproducible after you change the prompt |
input_tokens normalized to total input, plus usage_raw |
Comparable numbers across providers, without losing the provider's own breakdown. The three usage columns relate as input_tokens = uncached + cached_tokens + written, with written (cache writes) found in usage_raw; cached_tokens counts cache reads only. Lesson 03.7 names the same buckets input (uncached), cached and written, so subtract before you price a stored row |
request_id and provider_response_id |
The request ID is what support asks for (lesson 03.1, 8.6); the response ID lets you find and delete a provider-side copy (Part 10) |
user_ref is a keyed hash, not an email |
The conversation table is often exported to analytics; it shouldn't identify people. Use the keyed hash of 10.3 with its own purpose string (for example "storage-v1") |
provider_state JSON on the conversation, with set_provider_state() / get_provider_state() |
Server-side IDs (an OpenAI conversation ID, the last previous_response_id) if you mix modes. Section 7.10 uses it to chain when possible and replay when an ID fails |
deleted_at soft delete (soft_delete()) plus a hard delete() |
Users expect "delete" to work immediately in the UI: soft_delete() hides the conversation from load() and append() while keeping the rows, so a failed provider-side deletion can be retried (10.4); delete() purges. Your retention policy decides when |
finish_reason_raw, not a normalized finish reason |
The vocabularies differ (completed, end_turn, STOP, stop...), so the column keeps each provider's own word, and finish_reason_from_* in chatfmt.py read it (OpenAI's incomplete_details.reason when the response is incomplete). Mapping them to one set is lesson 03.11's job; see lesson 02.5, 4.5 for what each means |
compacted_by and load(raw=True) |
A compaction item replaces earlier turns without deleting them: load() skips the replaced turns, raw=True returns the full transcript (7.4) |
Small images inline in data_b64 |
Fine for a demo. In production, store files in object storage and keep a reference; lesson 03.6 covers provider file IDs |
The flow around it, on every turn:
flowchart LR
U["New user message"] --> S1["store.append(user turn)"]
S1 --> DB[("SQLite<br/>conversations / messages / parts")]
DB --> L["store.load(id)<br/>canonical Conversation"]
L --> T["trim to budget<br/>(optional)"]
T --> C["to_anthropic / to_gemini /<br/>to_openai_responses ..."]
C --> P["Provider API"]
P --> R["message_from_*(response)<br/>portable parts + native payload"]
R --> S2["store.append(assistant turn,<br/>usage, request ID)"]
S2 --> DB5.3 Try it: create, append, reload and continue#
This demo needs no network. It uses a Claude reply built from the documented response shape (with a placeholder signature), stores it, closes the database, reopens it as a "different process" would, and builds the next request two ways:
# s5_3_store_demo.py
"""Create, append, reload and continue a stored conversation (no network)."""
import json
import os
import anthropic.types as at
from chatfmt import (finish_reason_from_anthropic, message_from_anthropic, text, to_anthropic,
to_openai_responses, usage_from_anthropic)
from convo_store import ConversationStore
DB = "out/demo_conversations.db"
if os.path.exists(DB):
os.remove(DB) # start fresh on every run
# A Claude reply as the SDK returns it: a thinking block (with its signature) plus text.
# Shape copied from the Messages API reference; the signature is a made-up placeholder.
reply = at.Message.model_validate({
"id": "msg_01DemoReply", "type": "message", "role": "assistant",
"model": "claude-haiku-5-5", "stop_reason": "end_turn", "stop_sequence": None,
"content": [
{"type": "thinking", "thinking": "Hybrid tyres: suggest a mid-range pressure.",
"signature": "EqQBCkYIBxgCKkDdemoSignatureNotReal"},
{"type": "text", "text": "Start at about 60 psi and adjust for comfort."},
],
"usage": {"input_tokens": 41, "output_tokens": 37, "cache_read_input_tokens": 0,
"cache_creation_input_tokens": 0},
})
# --- Session 1: create the conversation and append two turns ----------------------------
store = ConversationStore(DB)
cid = store.create(user_ref="u_9f2c41d0", system_prompt="You are a bike-shop assistant.",
title="Tyre pressure", metadata={"channel": "web"})
store.append(cid, text("user", "What pressure for my hybrid's tyres?"))
seq = store.append(cid, message_from_anthropic(reply), finish_reason_raw=finish_reason_from_anthropic(reply),
usage=usage_from_anthropic(reply.usage), request_id="req_demo_123",
provider_response_id=reply.id)
print("created", cid, "| last seq:", seq)
store.db.close()
# --- Session 2 (think: a different server process, an hour later) -----------------------
store = ConversationStore(DB)
conv = store.load(cid)
conv.messages.append(text("user", "And for a wet commute?"))
print("reloaded", len(conv.messages), "messages | usage so far:", store.usage_totals(cid))
# Continue on the SAME provider: the thinking block goes back unchanged
same = to_anthropic(conv)
print("\nAnthropic request, assistant turn:")
print(json.dumps(same["messages"][1], indent=1))
# Continue on a DIFFERENT provider: only the portable text survives
other = to_openai_responses(conv)
print("\nOpenAI Responses request, assistant turn:")
print(json.dumps(other["input"][1], indent=1))
# Server-side IDs live in the conversation's provider_state; soft delete hides it (7.10, 10.4)
store.set_provider_state(cid, "openai_previous_response_id", "resp_demo_1")
print("\nprovider_state:", store.get_provider_state(cid))
store.soft_delete(cid)
try:
store.load(cid)
except KeyError:
print("after soft_delete, load() raises KeyError; the rows are still in the database")created cv_e59dd9ac2de5 | last seq: 1
reloaded 3 messages | usage so far: {'assistant_turns': 1, 'input_tokens': 41, 'output_tokens': 37}
Anthropic request, assistant turn:
{
"role": "assistant",
"content": [
{
"signature": "EqQBCkYIBxgCKkDdemoSignatureNotReal",
"thinking": "Hybrid tyres: suggest a mid-range pressure.",
"type": "thinking"
},
{
"text": "Start at about 60 psi and adjust for comfort.",
"type": "text"
}
]
}
OpenAI Responses request, assistant turn:
{
"role": "assistant",
"content": "Start at about 60 psi and adjust for comfort."
}
provider_state: {'openai_previous_response_id': 'resp_demo_1'}
after soft_delete, load() raises KeyError; the rows are still in the databaseThe conversation ID is random, so yours will differ. The important lines are the two request blocks: the reloaded history, sent back to Anthropic, still carries the thinking block and its signature exactly as stored; sent to OpenAI, the same turn is plain text, because a Claude signature means nothing there. The last two lines show the new bookkeeping methods: a server-side ID saved in provider_state, and a soft-deleted conversation that load() no longer returns.
5.4 Continuing on a different provider#
Because the store holds a canonical history, a conversation can move between providers turn by turn. This sample moves one stored conversation across providers: turn 1 on the Anthropic format, turn 2 on Gemini's, turn 3 on OpenAI's Responses format. Because turn 2 is Gemini, which has no local stand-in, the sample needs hosted keys for all three and is illustrative:
# s5_4_switch_providers.py
"""One stored conversation, continued on three different providers' formats.
Hosted-only: needs ANTHROPIC_API_KEY, GEMINI_API_KEY and OPENAI_API_KEY in the environment.
"""
import os
import anthropic
from google import genai
from google.genai import types
from openai import OpenAI
from chatfmt import (finish_reason_from_anthropic, finish_reason_from_gemini,
finish_reason_from_openai, message_from_anthropic, message_from_gemini,
message_from_openai, text, to_anthropic, to_gemini, to_openai_responses,
usage_from_anthropic, usage_from_gemini, usage_from_openai)
from convo_store import ConversationStore
DB = "out/switch_demo.db"
if os.path.exists(DB):
os.remove(DB)
store = ConversationStore(DB)
cid = store.create(user_ref="u_9f2c41d0",
system_prompt="You are a bike-shop assistant. Answer in one short sentence.")
claude = anthropic.Anthropic()
gemini = genai.Client()
oai = OpenAI()
# Turn 1 on Anthropic
store.append(cid, text("user", "My name is Priya and I ride a Trek FX 3."))
req = to_anthropic(store.load(cid))
reply = claude.messages.create(model="claude-haiku-5-5", max_tokens=40, **req)
store.append(cid, message_from_anthropic(reply), finish_reason_raw=finish_reason_from_anthropic(reply),
usage=usage_from_anthropic(reply.usage), provider_response_id=reply.id)
# Turn 2 on Gemini: the converter maps assistant -> model and system -> system_instruction
store.append(cid, text("user", "Which tyre width suits it?"))
req = to_gemini(store.load(cid))
g = gemini.models.generate_content(
model="gemini-3.8-flash", contents=req["contents"],
config=types.GenerateContentConfig(max_output_tokens=40, **req["config"]))
store.append(cid, message_from_gemini(g), finish_reason_raw=finish_reason_from_gemini(g), # e.g. "STOP"
usage=usage_from_gemini(g.usage_metadata), provider_response_id=g.response_id)
# Turn 3 on OpenAI Responses
store.append(cid, text("user", "What's my name and bike?"))
req = to_openai_responses(store.load(cid))
r = oai.responses.create(model="gpt-6-luna", max_output_tokens=40, store=False, **req)
store.append(cid, message_from_openai(r), finish_reason_raw=finish_reason_from_openai(r),
usage=usage_from_openai(r.usage), provider_response_id=r.id)
for row in store.db.execute(
"SELECT seq, role, provider, model, finish_reason_raw, input_tokens, output_tokens"
" FROM messages WHERE conversation_id = ? ORDER BY seq", (cid,)):
print(tuple(row))
print("final answer:", r.output_text)What's lost when you cross providers:
- Reasoning continuity. Thinking blocks, reasoning items and thought signatures are dropped (3.6).
- Provider-only content. Citations, server-tool results (web search, code execution), file IDs from one provider's Files API, and Anthropic's mid-conversation system messages have no portable equivalent in this lesson's canonical format. Decide per type: convert to text, drop, or refuse the switch.
- Tool call IDs. Each provider has its own ID format and pairing rules for tool calls and results; lesson 03.5 shows them, and lesson 03.11 normalizes them.
- Behaviour. A different model reads the same history differently. Switching mid-conversation is a product decision, and worth an evaluation (Module 10A).
So the claim "a conversation can move between providers" holds for text histories (with images). It does not yet hold for turns that have no text, which is the next topic.
What to do with a turn that has no text
Not every reply has visible text. Three cases are common:
- A tool-only reply: the model answered with a tool call and nothing else (the shapes are lesson 03.5, 6.8's).
- A reply cut off while thinking:
max_tokens(orlength) ran out before any text, so only a reasoning item or thinking block exists. - A refusal: Anthropic returns it as a normal 200 with
"content": []andstop_reason: "refusal"; OpenAI returns arefusalpart; Gemini can return a candidate with no content, or a blocked prompt with no candidates at all (8.2).
If you store only the text, such a turn becomes an empty message, and an empty message is a request bug: Anthropic's text blocks must be non-empty (4.1) and the checker in 4.4 flags every empty form. So chatfmt.py applies four rules:
message_from_*never creates an empty text part. A reply with no text hasparts == [], andmessage.has_portable_contentisFalse. A refusal's text is kept, because the user saw it.- A turn with no portable content is never replayed from its native payload, even to the provider that made it: a lone reasoning item, or a tool call with no result after it, isn't a valid history. (The one exception is a compaction item, 7.4.)
- Instead, the
to_*builders followon_empty:"placeholder"(the default) sends one short text turn,(no text reply), which keeps the user/assistant alternation;"omit"leaves the turn out, so two user turns end up side by side (Anthropic merges them, and the other providers document no rule);"error"raisesEmptyTurnError. - An empty user turn always raises
EmptyTurnError: there is nothing sensible to send in its place.
A placeholder puts words in the model's mouth, and models imitate their own history, so prefer "omit" or "error" where that matters. And these rules are a stopgap for histories that contain tool turns, not a way to support tool loops: a real tool conversation needs the call and its result kept together, which the canonical format here doesn't model and lesson 03.11 adds.
Two more cases need a decision from your app, not from the converter. A reply truncated mid-answer has partial text, so it isn't empty and replays like any assistant turn; continue it with a user message (4.2) or drop it. And a refused exchange is best dropped (the user message that caused it and the refusal) or rephrased rather than replayed, as Gemini's curated history does (8.2). On Anthropic message threads the docs are explicit: when a response has stop_reason: "refusal", do not continue the thread; start a new one without, or with a rephrased version of, the turn that led to the refusal (7.7). 6.3 runs all of these cases and prints what the checker finds.
5.5 Trimming to a token budget#
Long conversations need trimming or summarizing; lesson 02.7, Part 4 covers the strategies and budgeting. Two engineering details are specific to the store above. First, trim the canonical history before converting, so the same rule works for every provider. Second, once anything is dropped, strip Anthropic's native payloads from the turns you keep: on current Claude models each thinking block is bound to everything before it, so replaying an old thinking block after deleting earlier turns can be rejected with a 400 ("Invalid signature in thinking block. The block is bound to a different conversation"), as lesson 02.8, 8.2 explains, including the thinking.block_binding.prefix_mismatch_behavior: "drop_block" stopgap. Removing all thinking blocks is allowed and is the clean fix.
# s5_5_trim_to_budget.py
"""Trim a stored conversation to a token budget before converting it for a provider."""
import tiktoken
from chatfmt import Conversation, Message, Part, text
enc = tiktoken.get_encoding("o200k_base") # an ESTIMATE; count exactly near the limit (03.7)
def estimate(message: Message) -> int:
return 4 + sum(len(enc.encode(p.text or "")) for p in message.parts) \
+ sum(1_000 for p in message.parts if p.type == "image") # crude image allowance
def trim_to_budget(conv: Conversation, budget: int) -> tuple[Conversation, int]:
"""Keep the newest whole user->assistant exchanges that fit. Returns (trimmed, dropped)."""
used = len(enc.encode(conv.system or ""))
kept: list[Message] = []
for message in reversed(conv.messages):
cost = estimate(message)
if used + cost > budget:
break
kept.insert(0, message)
used += cost
while kept and kept[0].role != "user": # never start with an orphaned reply
kept.pop(0)
dropped = len(conv.messages) - len(kept)
if dropped:
# On current Claude models each thinking block is bound to everything before it,
# so after dropping earlier turns, replaying old thinking blocks is a 400. Strip them
# (but keep a compaction block: it is an opaque summary that must go back unchanged).
kept = [Message(m.role, m.parts, None)
if (m.native or {}).get("provider") == "anthropic" and not m.has_compaction else m
for m in kept]
return Conversation(conv.system, kept), dropped
conv = Conversation(system="You are a bike-shop assistant.")
for i in range(1, 7):
conv.messages.append(text("user", f"Question {i}: " + "tell me more about tyre pressure " * 8))
reply = text("assistant", f"Answer {i}: " + "pressure depends on width and load " * 8)
reply.native = {"provider": "anthropic", "model": "claude-haiku-5-5",
"payload": [{"type": "thinking", "thinking": "...", "signature": "Eq..."},
{"type": "text", "text": reply.parts[0].text}]}
conv.messages.append(reply)
conv.messages.append(text("user", "So what pressure for 40 mm tyres?"))
trimmed, dropped = trim_to_budget(conv, budget=300)
print(f"kept {len(trimmed.messages)} of {len(conv.messages)} messages, dropped {dropped}")
for m in trimmed.messages:
print(f" {m.role:9s} native={'yes' if m.native else 'no '} {(m.parts[0].text or '')[:40]!r}")kept 5 of 13 messages, dropped 8
user native=no 'Question 5: tell me more about tyre pres'
assistant native=no 'Answer 5: pressure depends on width and '
user native=no 'Question 6: tell me more about tyre pres'
assistant native=no 'Answer 6: pressure depends on width and '
user native=no 'So what pressure for 40 mm tyres?'Trim what you send, never what you store: the database keeps the full transcript, and trimming happens on the loaded copy. (The sample keeps a compaction block when it strips thinking blocks, because that one is an opaque summary that must go back unchanged; 7.4.)
5.6 Production concerns#
- Write the user turn before calling the model, and the assistant turn after a successful response. If the call fails, the user turn is already saved, and a retry must not append it again: retry the call, not the append. If you'd rather not keep unanswered user turns, append both in one transaction after the response.
- Serialize writes per conversation. The unique constraint catches races; your API layer should also reject a second message while a reply is still being generated (or queue it).
- Regenerate and edit create branches. "Regenerate this answer" or "edit my earlier message" turns a list into a tree. Add a
parent_idtomessagesand load the path to the current leaf. On Claude, a branch that changes an earlier turn must not replay the old branch's thinking blocks. - Version your system prompt. Store a prompt version (or the text, as above) per conversation, so you can reproduce old conversations and evaluate prompt changes (Module 04, Module 10A).
- Log what you sent. When a model "forgets", the first question is what the request actually contained (lesson 03.10). Storage, archiving and analytics at scale are Module 11A's topics.
Part 6: Converting between formats#
Reference
6.1 Choosing a canonical form#
To support more than one provider, pick one internal format and convert at the edges. Two common choices:
- Chat Completions as the canonical form. Tempting, because the ecosystem speaks it. But it puts instructions inside the message list, has nowhere to keep another provider's reasoning data, and its content parts don't match Anthropic's or Gemini's one to one, so you end up with special cases everywhere.
- Your own small types (the approach here): a
Conversationwith onesystemstring and a list ofMessages with auser/assistantrole, portableParts, and an optionalnativepayload. Every provider format is then a pure function of it.
The converter in this part is deliberately focused on messages: system instruction, user and assistant turns, text and image parts, and native-payload passthrough. Lesson 03.11 builds the full provider adapters on top of it (tools, streaming, structured output, errors, usage and retries).
6.2 The converter#
# chatfmt.py
"""chatfmt.py: a canonical conversation format and converters for four providers.
Canonical form: one system instruction + a list of user/assistant messages, each made of
text and image parts. Assistant messages may also carry the provider-native output they
came from (reasoning items, thinking blocks, thought signatures), which is replayed
verbatim when the next request goes to the SAME provider and dropped otherwise.
A turn with no portable content (a tool-only reply, a refusal, a reply cut off while
thinking) is never replayed from its native payload and never sent as empty content:
the builders substitute a placeholder, omit the turn, or raise (see `on_empty`).
An empty USER turn always raises EmptyTurnError.
Lesson 03.11 builds full adapters (tools, streaming, errors, usage) on top of this.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
Role = Literal["user", "assistant"]
Provider = Literal["openai", "openai_chat", "anthropic", "gemini", "gemini_interactions", "openrouter"]
OnEmpty = Literal["placeholder", "omit", "error"]
# What to send for an assistant turn that has no text (see `on_empty` in the builders).
EMPTY_ASSISTANT_PLACEHOLDER = "(no text reply)"
class EmptyTurnError(ValueError):
"""A turn has nothing to send (or an assistant turn was empty and on_empty='error')."""
class NoOutputError(Exception):
"""The provider answered with HTTP 200 but there is no reply to read: a blocked
prompt (Gemini `candidates` is None) or an error body (OpenRouter `choices` is None)."""
def __init__(self, reason: str, detail: str | None = None) -> None:
super().__init__(f"no output: {reason}" + (f" ({detail})" if detail else ""))
self.reason, self.detail = reason, detail
@dataclass
class Part:
type: Literal["text", "image"]
text: str | None = None
media_type: str | None = None # e.g. "image/png" (images only)
data_b64: str | None = None # base64-encoded bytes (images only)
@property
def is_empty(self) -> bool:
"""An image with no data, or text that is empty or only whitespace."""
if self.type == "image":
return not self.data_b64
return not (self.text or "").strip()
@dataclass
class Message:
role: Role
parts: list[Part]
native: dict[str, Any] | None = None # {"provider": ..., "model": ..., "payload": [...]}
@property
def has_portable_content(self) -> bool:
"""True if any text or image part is non-empty. False for a tool-only reply, a
refusal, or a reply cut off while thinking."""
return any(not p.is_empty for p in self.parts)
@property
def has_compaction(self) -> bool:
"""True if the native payload holds a `compaction` item or block (OpenAI
`context_management` / `responses.compact`, Anthropic server-side compaction).
It is opaque and must be replayed unchanged to the provider that made it."""
items = (self.native or {}).get("payload") or []
return any(isinstance(i, dict) and i.get("type") == "compaction" for i in items)
@dataclass
class Conversation:
system: str | None = None
messages: list[Message] = field(default_factory=list)
def text(role: Role, value: str) -> Message:
return Message(role, [Part("text", text=value)])
def _native_for(message: Message, provider: str) -> list | None:
"""The provider-native payload, but only if it came from this same provider AND the
turn has something to say. A turn with no portable content (a tool-only reply, a
refusal, thinking cut off by max_tokens) is never replayed natively: a lone reasoning
item or a tool call without its result is not a valid history. The one exception is a
compaction item, which exists only as native payload."""
if (message.native and message.native.get("provider") == provider
and message.native["payload"]
and (message.has_portable_content or message.has_compaction)):
return message.native["payload"]
return None # different provider (or none): fall back to the portable parts
def _turn_parts(message: Message, on_empty: OnEmpty) -> list[Part] | None:
"""The non-empty portable parts to send for a turn, or None to omit the turn.
on_empty decides what an assistant turn with no text becomes:
"placeholder": one short text part (keeps the user/assistant alternation intact),
"omit": the turn is left out (two user turns may end up side by side),
"error": raise EmptyTurnError.
An empty user turn always raises: there is nothing sensible to send in its place.
"""
parts = [p for p in message.parts if not p.is_empty]
if parts:
return parts
if message.has_compaction: # an opaque summary of earlier turns: never swap in a placeholder
raise EmptyTurnError("this turn is a compaction item from another provider: build the "
"request from the full transcript instead (store.load(..., raw=True))")
if message.role == "user" or on_empty == "error":
raise EmptyTurnError(f"empty {message.role} turn: nothing to send")
if on_empty == "omit":
return None
return [Part("text", text=EMPTY_ASSISTANT_PLACEHOLDER)]
# ----------------------------------------------------------------- canonical -> request
def to_openai_responses(conv: Conversation, on_empty: OnEmpty = "placeholder") -> dict[str, Any]:
items: list[dict[str, Any]] = []
for m in conv.messages:
native = _native_for(m, "openai")
if m.role == "assistant" and native is not None:
items.extend(native) # message + reasoning items, unchanged
continue
parts = _turn_parts(m, on_empty)
if parts is None:
continue
if m.role == "assistant":
items.append({"role": "assistant", "content": "".join(p.text or "" for p in parts)})
else:
content = []
for p in parts:
if p.type == "text":
content.append({"type": "input_text", "text": p.text})
else:
content.append({"type": "input_image",
"image_url": f"data:{p.media_type};base64,{p.data_b64}"})
items.append({"role": "user", "content": content})
request: dict[str, Any] = {"input": items}
if conv.system:
request["instructions"] = conv.system # resend on EVERY request
return request
def to_chat_completions(conv: Conversation, provider: str = "openai_chat",
on_empty: OnEmpty = "placeholder") -> dict[str, Any]:
"""OpenAI Chat Completions, and OpenRouter (provider="openrouter")."""
messages: list[dict[str, Any]] = []
if conv.system:
messages.append({"role": "system", "content": conv.system})
for m in conv.messages:
native = _native_for(m, provider)
if m.role == "assistant" and native is not None:
messages.append(native[0]) # e.g. keeps OpenRouter's reasoning_details
continue
parts = _turn_parts(m, on_empty)
if parts is None:
continue
if m.role == "assistant":
messages.append({"role": "assistant", "content": "".join(p.text or "" for p in parts)})
else:
content = []
for p in parts:
if p.type == "text":
content.append({"type": "text", "text": p.text})
else:
content.append({"type": "image_url", "image_url": {
"url": f"data:{p.media_type};base64,{p.data_b64}"}})
messages.append({"role": "user", "content": content})
return {"messages": messages}
def to_anthropic(conv: Conversation, on_empty: OnEmpty = "placeholder") -> dict[str, Any]:
messages: list[dict[str, Any]] = []
for m in conv.messages:
native = _native_for(m, "anthropic")
if native is not None:
blocks = native # thinking blocks + signatures, unchanged
else:
parts = _turn_parts(m, on_empty)
if parts is None:
continue
blocks = []
for p in parts:
if p.type == "text":
blocks.append({"type": "text", "text": p.text})
else:
blocks.append({"type": "image", "source": {
"type": "base64", "media_type": p.media_type, "data": p.data_b64}})
messages.append({"role": m.role, "content": blocks})
request: dict[str, Any] = {"messages": messages}
if conv.system:
request["system"] = conv.system
return request
def to_gemini(conv: Conversation, on_empty: OnEmpty = "placeholder") -> dict[str, Any]:
"""generate_content: contents with roles user/model; system goes in the config."""
contents: list[dict[str, Any]] = []
for m in conv.messages:
role = "model" if m.role == "assistant" else "user" # NOT "assistant"
native = _native_for(m, "gemini")
if native is not None:
parts_out = native # parts with thought_signature, unchanged
else:
parts = _turn_parts(m, on_empty)
if parts is None:
continue
parts_out = []
for p in parts:
if p.type == "text":
parts_out.append({"text": p.text})
else:
parts_out.append({"inline_data": {"mime_type": p.media_type, "data": p.data_b64}})
contents.append({"role": role, "parts": parts_out})
request: dict[str, Any] = {"contents": contents}
if conv.system:
request["config"] = {"system_instruction": conv.system}
return request
def to_gemini_interactions(conv: Conversation, on_empty: OnEmpty = "placeholder") -> dict[str, Any]:
"""Interactions API: a list of steps; no roles, the step type says who spoke."""
steps: list[dict[str, Any]] = []
for m in conv.messages:
native = _native_for(m, "gemini_interactions")
if m.role == "assistant" and native is not None:
steps.extend(native) # thought steps (with signatures) + model_output
continue
parts = _turn_parts(m, on_empty)
if parts is None:
continue
content = []
for p in parts:
if p.type == "text":
content.append({"type": "text", "text": p.text})
else:
content.append({"type": "image", "mime_type": p.media_type, "data": p.data_b64})
steps.append({"type": "model_output" if m.role == "assistant" else "user_input",
"content": content})
request: dict[str, Any] = {"input": steps}
if conv.system:
request["system_instruction"] = conv.system # resend on EVERY request
return request
# ----------------------------------------------------------------- request -> canonical
# Used for importing stored request logs, and for the round-trip test.
def _image_from_data_url(url: str) -> Part:
header, data = url.split(",", 1) # "data:image/png;base64", "<b64>"
return Part("image", media_type=header[5:].split(";")[0], data_b64=data)
def _content_text(content: Any) -> str:
"""The text of a string-or-parts content value (used for system messages)."""
if isinstance(content, str):
return content
return "".join(c.get("text", "") for c in content if c.get("type") in ("text", "input_text"))
def _add_system(conv: Conversation, value: str) -> None:
"""Several system/developer messages are joined with a blank line, never overwritten."""
conv.system = f"{conv.system}\n\n{value}" if conv.system else value
def from_openai_responses(request: dict[str, Any]) -> Conversation:
conv = Conversation(system=request.get("instructions"))
raw = request["input"]
# input="Hi" means one user message
items: list[dict[str, Any]] = [{"role": "user", "content": raw}] if isinstance(raw, str) else raw
for item in items:
if item.get("type", "message") != "message":
continue # reasoning items etc. are not portable
if item["role"] in ("system", "developer"):
_add_system(conv, _content_text(item["content"]))
continue
content = item["content"]
if isinstance(content, str):
parts = [Part("text", text=content)]
else:
parts = [Part("text", text=c["text"]) if c["type"] in ("input_text", "output_text")
else Part("text", text=c["refusal"]) if c["type"] == "refusal"
else _image_from_data_url(c["image_url"]) for c in content]
conv.messages.append(Message(item["role"], parts))
return conv
def from_chat_completions(request: dict[str, Any]) -> Conversation:
conv = Conversation()
for msg in request["messages"]:
if msg["role"] in ("system", "developer"):
_add_system(conv, _content_text(msg["content"]))
continue
content = msg["content"]
if isinstance(content, str):
parts = [Part("text", text=content)]
else:
parts = [Part("text", text=c["text"]) if c["type"] == "text"
else _image_from_data_url(c["image_url"]["url"]) for c in content]
conv.messages.append(Message(msg["role"], parts))
return conv
def from_anthropic(request: dict[str, Any]) -> Conversation:
system = request.get("system")
if isinstance(system, list): # a list of text blocks
system = "\n\n".join(b["text"] for b in system)
conv = Conversation(system=system)
for msg in request["messages"]:
if msg["role"] == "system":
raise ValueError("mid-conversation system messages are not modelled by the "
"canonical format (see 2.4): handle them before converting")
blocks = [{"type": "text", "text": msg["content"]}] if isinstance(msg["content"], str) \
else msg["content"]
parts = []
for b in blocks:
if b["type"] == "text":
parts.append(Part("text", text=b["text"]))
elif b["type"] == "image":
parts.append(Part("image", media_type=b["source"]["media_type"],
data_b64=b["source"]["data"]))
# thinking / redacted_thinking blocks are provider-specific: not portable
conv.messages.append(Message(msg["role"], parts))
return conv
def from_gemini(request: dict[str, Any]) -> Conversation:
conv = Conversation(system=request.get("config", {}).get("system_instruction"))
for c in request["contents"]:
parts = []
for p in c["parts"]:
if p.get("thought"):
continue # thought summaries are not portable
if "text" in p:
parts.append(Part("text", text=p["text"]))
elif "inline_data" in p:
parts.append(Part("image", media_type=p["inline_data"]["mime_type"],
data_b64=p["inline_data"]["data"]))
conv.messages.append(Message("assistant" if c["role"] == "model" else "user", parts))
return conv
def from_gemini_interactions(request: dict[str, Any]) -> Conversation:
conv = Conversation(system=request.get("system_instruction"))
for step in request["input"]:
if step["type"] not in ("user_input", "model_output"):
continue # thought steps etc. are not portable
parts = [Part("text", text=c["text"]) if c["type"] == "text"
else Part("image", media_type=c["mime_type"], data_b64=c["data"])
for c in step.get("content", [])]
conv.messages.append(Message("user" if step["type"] == "user_input" else "assistant", parts))
return conv
# ----------------------------------------------------------------- response -> canonical
# Each takes the SDK's typed response object and keeps BOTH the portable text and the
# full native output, so the next same-provider request can replay it unchanged.
# Empty or whitespace-only text is never turned into a Part: a tool-only reply, a refusal
# or a reply cut off while thinking gives `parts == []` (and has_portable_content is False).
def _text_parts(texts: list[str | None]) -> list[Part]:
return [Part("text", text=t) for t in texts if t and t.strip()]
def message_from_openai(response: Any) -> Message:
payload = [item.model_dump(exclude_none=True) for item in response.output]
texts: list[str | None] = []
for item in response.output:
if item.type == "message":
for c in item.content:
texts.append(c.text if c.type == "output_text" else c.refusal) # refusal is text too
return Message("assistant", _text_parts(texts),
native={"provider": "openai", "model": getattr(response, "model", None), # a CompactedResponse has none
"payload": payload})
def message_from_chat_completion(completion: Any, provider: str = "openai_chat") -> Message:
if not completion.choices: # OpenRouter can send HTTP 200 with an error body
error = (completion.model_extra or {}).get("error")
raise NoOutputError("no_choices", str(error) if error else None)
msg = completion.choices[0].message
payload = [msg.model_dump(exclude_none=True)] # includes model_extra fields
return Message("assistant", _text_parts([msg.content, getattr(msg, "refusal", None)]),
native={"provider": provider, "model": completion.model, "payload": payload})
def message_from_anthropic(message: Any) -> Message:
payload = [block.model_dump(exclude_none=True) for block in message.content]
texts = [b.text for b in message.content if b.type == "text"]
return Message("assistant", _text_parts(texts),
native={"provider": "anthropic", "model": message.model, "payload": payload})
def message_from_gemini(response: Any) -> Message:
if not response.candidates: # a blocked prompt has no candidates at all
feedback = response.prompt_feedback
reason = feedback.block_reason.name if feedback and feedback.block_reason else "no_candidates"
raise NoOutputError(reason, feedback.block_reason_message if feedback else None)
content = response.candidates[0].content # can be None (e.g. finish reason SAFETY)
parts = (content.parts if content else None) or []
# mode="json" turns bytes (thought_signature) into base64 text, so it can be stored as JSON
payload = [p.model_dump(mode="json", exclude_none=True) for p in parts]
texts = [p.text for p in parts if p.text and not p.thought]
return Message("assistant", _text_parts(texts),
native={"provider": "gemini", "model": response.model_version, "payload": payload})
def message_from_interaction(interaction: Any) -> Message:
payload = [s.model_dump(mode="json", exclude_none=True) for s in interaction.steps or []]
texts = [c.text for s in interaction.steps or [] if s.type == "model_output"
for c in (s.content or []) if c.type == "text"]
return Message("assistant", _text_parts(texts),
native={"provider": "gemini_interactions", "model": interaction.model,
"payload": payload})
# ----------------------------------------------------------------- finish reasons, as stored
# These return the provider's OWN vocabulary (the vocabularies differ: "completed",
# "end_turn", "STOP", "stop"...). Mapping them to one set is lesson 03.11's job.
def finish_reason_from_openai(response: Any) -> str | None:
if response.status == "incomplete" and response.incomplete_details:
return response.incomplete_details.reason or "incomplete" # e.g. "max_output_tokens"
return response.status
def finish_reason_from_chat_completion(completion: Any) -> str | None:
return completion.choices[0].finish_reason if completion.choices else None
def finish_reason_from_anthropic(message: Any) -> str | None:
return message.stop_reason
def finish_reason_from_gemini(response: Any) -> str | None:
candidate = response.candidates[0] if response.candidates else None
return candidate.finish_reason.name if candidate and candidate.finish_reason else None
def finish_reason_from_interaction(interaction: Any) -> str | None:
return interaction.status
# ----------------------------------------------------------------- usage, normalized
# `usage` can be missing (None) on streamed or failed responses: every helper then returns
# None for each number, meaning "unknown", never 0.
def _unknown_usage() -> dict[str, Any]:
return {"input_tokens": None, "cached_tokens": None, "output_tokens": None,
"reasoning_tokens": None, "raw": None}
def usage_from_anthropic(u: Any) -> dict[str, Any]:
if u is None:
return _unknown_usage()
cached = (u.cache_read_input_tokens or 0) + (u.cache_creation_input_tokens or 0)
return {"input_tokens": u.input_tokens + cached, # input_tokens EXCLUDES cached tokens
"cached_tokens": u.cache_read_input_tokens or 0,
"output_tokens": u.output_tokens,
"reasoning_tokens": u.output_tokens_details.thinking_tokens
if u.output_tokens_details else None,
"raw": u.model_dump(exclude_none=True)}
def usage_from_openai(u: Any) -> dict[str, Any]:
if u is None:
return _unknown_usage()
return {"input_tokens": u.input_tokens, # includes cached tokens
"cached_tokens": u.input_tokens_details.cached_tokens,
"output_tokens": u.output_tokens, # includes reasoning tokens
"reasoning_tokens": u.output_tokens_details.reasoning_tokens,
"raw": u.model_dump(exclude_none=True)}
def usage_from_gemini(u: Any) -> dict[str, Any]:
if u is None:
return _unknown_usage()
return {"input_tokens": u.prompt_token_count, # includes cached tokens
"cached_tokens": u.cached_content_token_count or 0,
"output_tokens": (u.candidates_token_count or 0) + (u.thoughts_token_count or 0),
"reasoning_tokens": u.thoughts_token_count,
"raw": u.model_dump(mode="json", exclude_none=True)}Things that are easy to get wrong, and how the code handles them:
- Gemini's role is
model, and Interactions has no roles (step types instead). Both are mapped in one place. - Instructions are separate everywhere except Chat Completions, where they become the first message. The request builders return dicts that include the right instruction field, so callers can't forget it, including on later turns.
- Assistant turns on OpenAI Responses go back as a plain string (or as the original output items). Don't send assistant content as
input_textparts: those are for input. - Images become
input_imagewith a data URL (data:image/png;base64,...: the file's bytes inlined in a string) (Responses), animage_urlpart (Chat Completions and OpenRouter), animageblock with a base64 source (Anthropic),inline_data(Gemini) or animagecontent block (Interactions). Image limits and file IDs are lesson 03.6's topic. - Replies with no text are never sent as empty content (
has_portable_content,on_empty,EmptyTurnError; 5.4). - A 200 with nothing to read raises
NoOutputError: a Gemini blocked prompt hascandidates=None, and OpenRouter can answer HTTP 200 with only an error body (choicesisNone).message_from_geminiandmessage_from_chat_completionraise it instead of crashing with anAttributeErrororTypeError, and a Gemini candidate with nocontentgives an empty message. usagecan beNone(streams, failures). Theusage_from_*helpers then returnNonefor every number, meaning "unknown", never zero.- Importers don't lose instructions.
from_chat_completionsandfrom_openai_responsesjoin severalsystem/developermessages with a blank line (list-form content included) instead of keeping only the last one. - Gemini's binary fields (
thought_signature,inline_data.data) are bytes in the SDK.model_dump(mode="json")turns them into base64 text for storage, and the SDK decodes base64 strings back into bytes when you pass the dicts again, so a stored history replays correctly.
6.3 Try it: one conversation, every request shape#
# s6_converter_demo.py
"""Convert one canonical conversation to every provider's request shape, then back."""
import json
from chatfmt import (EMPTY_ASSISTANT_PLACEHOLDER, Conversation, Message, Part, from_anthropic,
from_chat_completions, from_gemini, from_gemini_interactions,
from_openai_responses, text, to_anthropic, to_chat_completions, to_gemini,
to_gemini_interactions, to_openai_responses)
from s4_4_preflight import check_turns # the checker from 4.4, saved next to this file
PNG_1PX = ("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJ"
"RU5ErkJggg==") # a 1x1 PNG, base64-encoded
conv = Conversation(
system="You are a bike-shop assistant. Answer in one short sentence.",
messages=[
Message("user", [Part("text", text="Is this tyre worn out?"),
Part("image", media_type="image/png", data_b64=PNG_1PX)]),
text("assistant", "The tread looks fine, but check the sidewall for cracks."),
text("user", "How often should I check it?"),
],
)
# name -> (builder, importer, the provider name and request key the 4.4 checker needs)
converters = {
"OpenAI Responses": (to_openai_responses, from_openai_responses, ("openai", "input")),
"Anthropic Messages": (to_anthropic, from_anthropic, ("anthropic", "messages")),
"Gemini generate_content": (to_gemini, from_gemini, ("gemini", "contents")),
"Gemini Interactions": (to_gemini_interactions, from_gemini_interactions,
("interactions", "input")),
"OpenRouter (Chat Completions)": (lambda c, **kw: to_chat_completions(c, "openrouter", **kw),
from_chat_completions, ("openai", "messages")),
}
for name, (to_provider, _, (checker_name, key)) in converters.items():
request = to_provider(conv)
assert not check_turns(checker_name, request[key]), name # run the 4.4 pre-flight check
shown = json.dumps(request, ensure_ascii=False).replace(PNG_1PX, "<base64 PNG>")
print(f"--- {name}\n{shown}\n")
# Round-trip test: canonical -> provider request -> canonical must be lossless
for name, (to_provider, from_provider, _) in converters.items():
assert from_provider(to_provider(conv)) == conv, name
print("round trip OK for", len(converters), "request formats; pre-flight checker found no problems")
# An assistant turn with NO text (a tool-only reply, a refusal) is not lossless, by design:
# the builders never send empty content, so it becomes a placeholder (or is omitted).
empty = Conversation(conv.system, [conv.messages[0], Message("assistant", []), conv.messages[2]])
with_placeholder = Conversation(conv.system, [conv.messages[0],
text("assistant", EMPTY_ASSISTANT_PLACEHOLDER),
conv.messages[2]])
omitted = Conversation(conv.system, [conv.messages[0], conv.messages[2]])
for name, (to_provider, from_provider, (checker_name, key)) in converters.items():
assert not check_turns(checker_name, to_provider(empty)[key]), name
assert from_provider(to_provider(empty)) == with_placeholder, name
assert from_provider(to_provider(empty, on_empty="omit")) == omitted, name
print("empty assistant turn: placeholder and omit both pass the checker, in all", len(converters), "formats")--- OpenAI Responses
{"input": [{"role": "user", "content": [{"type": "input_text", "text": "Is this tyre worn out?"}, {"type": "input_image", "image_url": "data:image/png;base64,<base64 PNG>"}]}, {"role": "assistant", "content": "The tread looks fine, but check the sidewall for cracks."}, {"role": "user", "content": [{"type": "input_text", "text": "How often should I check it?"}]}], "instructions": "You are a bike-shop assistant. Answer in one short sentence."}
--- Anthropic Messages
{"messages": [{"role": "user", "content": [{"type": "text", "text": "Is this tyre worn out?"}, {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "<base64 PNG>"}}]}, {"role": "assistant", "content": [{"type": "text", "text": "The tread looks fine, but check the sidewall for cracks."}]}, {"role": "user", "content": [{"type": "text", "text": "How often should I check it?"}]}], "system": "You are a bike-shop assistant. Answer in one short sentence."}
--- Gemini generate_content
{"contents": [{"role": "user", "parts": [{"text": "Is this tyre worn out?"}, {"inline_data": {"mime_type": "image/png", "data": "<base64 PNG>"}}]}, {"role": "model", "parts": [{"text": "The tread looks fine, but check the sidewall for cracks."}]}, {"role": "user", "parts": [{"text": "How often should I check it?"}]}], "config": {"system_instruction": "You are a bike-shop assistant. Answer in one short sentence."}}
--- Gemini Interactions
{"input": [{"type": "user_input", "content": [{"type": "text", "text": "Is this tyre worn out?"}, {"type": "image", "mime_type": "image/png", "data": "<base64 PNG>"}]}, {"type": "model_output", "content": [{"type": "text", "text": "The tread looks fine, but check the sidewall for cracks."}]}, {"type": "user_input", "content": [{"type": "text", "text": "How often should I check it?"}]}], "system_instruction": "You are a bike-shop assistant. Answer in one short sentence."}
--- OpenRouter (Chat Completions)
{"messages": [{"role": "system", "content": "You are a bike-shop assistant. Answer in one short sentence."}, {"role": "user", "content": [{"type": "text", "text": "Is this tyre worn out?"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,<base64 PNG>"}}]}, {"role": "assistant", "content": "The tread looks fine, but check the sidewall for cracks."}, {"role": "user", "content": [{"type": "text", "text": "How often should I check it?"}]}]}
round trip OK for 5 request formats; pre-flight checker found no problems
empty assistant turn: placeholder and omit both pass the checker, in all 5 formatsThe round-trip test is the important part: canonical → provider request → canonical must be lossless for every portable field. Keep a test like it in your suite, and add a case every time you support a new part type. The demo also feeds every request through the 4.4 checker (save that file as s4_4_preflight.py next to this one), and adds the one case that is not lossless by design: an assistant turn with no text becomes a placeholder (or is omitted), and the test asserts exactly that. The request builders are used by the provider-switching sample in 5.4 (Anthropic, Gemini and Responses formats; hosted-only, because of the Gemini turn), and 1.2 showed, with hand-built payloads, that the three OpenAI and Anthropic shapes are accepted by the local stand-in.
Replies with no text
The second demo builds nine replies that have no visible text, or only a refusal, from fixtures shaped like each API reference's documented response, stores them with message_from_*, and checks the requests that every builder produces for each of them. It then shows the three on_empty policies, and the two "200 with nothing to read" cases:
# s6_empty_turns_demo.py
"""Replies with no text, converted for every provider and checked before sending (no network).
A tool-only reply, a refusal, or thinking cut off by max_tokens has no visible text. This demo
builds each one from a fixture shaped like the provider's documented response, stores it with
message_from_*, converts the conversation for all five request formats, and runs the 4.4
pre-flight checker on every request. Save 4.4 as s4_4_preflight.py next to this file.
"""
import anthropic.types as atypes
import httpx2
from google.genai import types as gtypes
from google.genai._gaos.types.interactions import Interaction # SDK 2.34.0 location
from openai import OpenAI
from openai.types.chat import ChatCompletion
from openai.types.responses import Response
from chatfmt import (EMPTY_ASSISTANT_PLACEHOLDER, Conversation, EmptyTurnError, NoOutputError,
Message, message_from_anthropic, message_from_chat_completion,
message_from_gemini, message_from_interaction, message_from_openai, text,
to_anthropic, to_chat_completions, to_gemini, to_gemini_interactions,
to_openai_responses, usage_from_gemini)
from s4_4_preflight import check_turns
CALL_ARGS = {"sku": "FX3-700"}
CLAUDE = {"id": "msg_demo", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"stop_sequence": None, "usage": {"input_tokens": 20, "output_tokens": 5}}
OPENAI = {"id": "resp_demo", "object": "response", "created_at": 0, "model": "gpt-6-luna",
"status": "completed", "parallel_tool_calls": True, "tool_choice": "auto", "tools": []}
CHAT = {"id": "gen-demo", "object": "chat.completion", "created": 0, "model": "gpt-6-luna"}
replies: dict[str, Message] = {
"Claude: tool_use only": message_from_anthropic(atypes.Message.model_validate({
**CLAUDE, "stop_reason": "tool_use", "content": [
{"type": "tool_use", "id": "toolu_demo", "name": "check_stock", "input": CALL_ARGS}]})),
"Claude: refusal (content=[])": message_from_anthropic(atypes.Message.model_validate({
**CLAUDE, "stop_reason": "refusal", "content": []})),
"Claude: cut off while thinking": message_from_anthropic(atypes.Message.model_validate({
**CLAUDE, "stop_reason": "max_tokens", "content": [
{"type": "thinking", "thinking": "Let me work out...", "signature": "EqQB...demo"}]})),
"OpenAI: function_call only": message_from_openai(Response.model_validate({
**OPENAI, "output": [
{"type": "function_call", "id": "fc_demo", "call_id": "call_demo", "status": "completed",
"name": "check_stock", "arguments": '{"sku": "FX3-700"}'}]})),
"OpenAI: refusal part": message_from_openai(Response.model_validate({
**OPENAI, "output": [
{"type": "message", "id": "msg_demo", "role": "assistant", "status": "completed",
"content": [{"type": "refusal", "refusal": "I can't help with that."}]}]})),
"Chat: tool_calls, content=None": message_from_chat_completion(ChatCompletion.model_validate({
**CHAT, "choices": [{"index": 0, "finish_reason": "tool_calls", "message": {
"role": "assistant", "content": None, "tool_calls": [
{"id": "call_demo", "type": "function",
"function": {"name": "check_stock", "arguments": '{"sku": "FX3-700"}'}}]}}]})),
"Gemini: function_call only": message_from_gemini(gtypes.GenerateContentResponse.model_validate({
"model_version": "gemini-3.8-flash", "candidates": [{"finish_reason": "STOP", "content": {
"role": "model", "parts": [{"function_call": {"name": "check_stock", "args": CALL_ARGS}}]}}]})),
"Gemini: SAFETY, no content": message_from_gemini(gtypes.GenerateContentResponse.model_validate({
"model_version": "gemini-3.8-flash", "candidates": [{"finish_reason": "SAFETY"}]})),
"Interactions: function_call only": message_from_interaction(Interaction.model_validate({
"id": "int_demo", "status": "requires_action", "model": "gemini-3.8-flash",
"created": "2026-11-04T09:00:00Z", "updated": "2026-11-04T09:00:01Z",
"steps": [{"type": "function_call", "id": "fc_demo", "name": "check_stock",
"arguments": CALL_ARGS}]})),
}
# Each builder with the provider name check_turns expects, and where the turns sit in the request.
targets = {
"OpenAI Responses": ("openai", to_openai_responses, "input"),
"Chat Completions": ("openai", to_chat_completions, "messages"),
"Anthropic": ("anthropic", to_anthropic, "messages"),
"Gemini": ("gemini", to_gemini, "contents"),
"Interactions": ("interactions", to_gemini_interactions, "input"),
}
print("reply".ljust(34), "portable? problems the 4.4 checker finds in the 5 requests")
for label, reply in replies.items():
conv = Conversation("Be brief.", [text("user", "Is the FX3 in stock?"), reply,
text("user", "And in blue?")])
problems = {name: check_turns(provider, build(conv)[key])
for name, (provider, build, key) in targets.items()}
found = [f"{name}: {p[0]}" for name, p in problems.items() if p]
print(f"{label:34s} {str(reply.has_portable_content):9s} {'; '.join(found) or 'none'}")
# --- the three policies, on one reply -------------------------------------------------------
tool_only = replies["Claude: tool_use only"]
conv = Conversation(None, [text("user", "Is the FX3 in stock?"), tool_only, text("user", "And in blue?")])
print("\non_empty policies for the Claude tool_use-only reply, sent to Anthropic itself:")
for policy in ("placeholder", "omit"):
request = to_anthropic(conv, on_empty=policy)
print(f" {policy:11s}", [(m["role"], m["content"][0]["text"]) for m in request["messages"]])
try:
to_anthropic(conv, on_empty="error")
except EmptyTurnError as e:
print(" error ", type(e).__name__, "->", e)
try:
to_anthropic(Conversation(None, [text("user", " ")]))
except EmptyTurnError as e:
print(" empty USER turn always:", type(e).__name__, "->", e)
# --- a 200 response with nothing to read ----------------------------------------------------
blocked = gtypes.GenerateContentResponse.model_validate(
{"prompt_feedback": {"block_reason": "SAFETY"}}) # documented blocked-prompt shape
def router_handler(request: httpx2.Request) -> httpx2.Response: # OpenRouter: HTTP 200, error body only
return httpx2.Response(200, json={"error": {"code": 502, "message": "Provider returned error"}})
router_error = OpenAI(api_key="sk-test", http_client=httpx2.Client(
transport=httpx2.MockTransport(router_handler))).chat.completions.create(
model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Hi"}]) # no exception raised
for label, call in [("Gemini blocked prompt", lambda: message_from_gemini(blocked)),
("OpenRouter 200 + error body", lambda: message_from_chat_completion(router_error))]:
try:
call()
except NoOutputError as e:
print(f"{label}: NoOutputError reason={e.reason!r} detail={e.detail!r}")
print("usage_from_gemini(None) ->", usage_from_gemini(None))
print("placeholder text:", repr(EMPTY_ASSISTANT_PLACEHOLDER))reply portable? problems the 4.4 checker finds in the 5 requests
Claude: tool_use only False none
Claude: refusal (content=[]) False none
Claude: cut off while thinking False none
OpenAI: function_call only False none
OpenAI: refusal part True none
Chat: tool_calls, content=None False none
Gemini: function_call only False none
Gemini: SAFETY, no content False none
Interactions: function_call only False none
on_empty policies for the Claude tool_use-only reply, sent to Anthropic itself:
placeholder [('user', 'Is the FX3 in stock?'), ('assistant', '(no text reply)'), ('user', 'And in blue?')]
omit [('user', 'Is the FX3 in stock?'), ('user', 'And in blue?')]
error EmptyTurnError -> empty assistant turn: nothing to send
empty USER turn always: EmptyTurnError -> empty user turn: nothing to send
Gemini blocked prompt: NoOutputError reason='SAFETY' detail=None
OpenRouter 200 + error body: NoOutputError reason='no_choices' detail="{'code': 502, 'message': 'Provider returned error'}"
usage_from_gemini(None) -> {'input_tokens': None, 'cached_tokens': None, 'output_tokens': None, 'reasoning_tokens': None, 'raw': None}
placeholder text: '(no text reply)'A naive converter, one that joins each reply's text parts and sends the result, fails in exactly these cases: a Claude tool_use-only reply gives parts=[] and the Responses request carries {'role': 'assistant', 'content': ''}; an OpenAI function_call-only reply gives one empty text part, which a naive Anthropic builder sends as {'type': 'text', 'text': ''} (a 400, per 4.1); the checker flags each of them. With the rules above, no request has a problem. The one case the builders refuse to guess about is a compaction item from another provider, which raises (7.4).
6.4 From each response back to canonical#
The message_from_* functions take the SDK's typed response object and return a canonical assistant message holding both views. This demo builds one response per provider from fixtures that follow each API reference's documented shape, validates them into the SDKs' own response classes, and converts them:
# s6_2_responses_to_canonical.py
"""Turn each provider's typed response into a canonical message (fixtures, no network).
The fixtures follow each API reference's documented response shape; IDs, signatures (base64 of "demo-signature")
and encrypted content are made-up placeholders.
"""
from google.genai import types as gtypes
from google.genai._gaos.types.interactions import Interaction # SDK 2.34.0 location
import anthropic.types as atypes
from openai.types.chat import ChatCompletion
from openai.types.responses import Response
from chatfmt import (Conversation, message_from_anthropic, message_from_chat_completion,
message_from_gemini, message_from_interaction, message_from_openai, text,
to_anthropic, to_openai_responses)
ANSWER = "Start around 60 psi."
openai_resp = Response.model_validate({
"id": "resp_demo", "object": "response", "created_at": 0, "model": "gpt-6-luna",
"status": "completed", "parallel_tool_calls": True, "tool_choice": "auto", "tools": [],
"output": [
{"type": "reasoning", "id": "rs_demo", "summary": [], "encrypted_content": "gAAAA...demo"},
{"type": "message", "id": "msg_demo", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": ANSWER, "annotations": []}]}]})
claude_msg = atypes.Message.model_validate({
"id": "msg_demo", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"stop_reason": "end_turn", "stop_sequence": None,
"usage": {"input_tokens": 20, "output_tokens": 30},
"content": [{"type": "thinking", "thinking": "Hybrid tyres...", "signature": "EqQB...demo"},
{"type": "text", "text": ANSWER}]})
gemini_resp = gtypes.GenerateContentResponse.model_validate({
"candidates": [{"content": {"role": "model", "parts": [
{"text": ANSWER, "thought_signature": "ZGVtby1zaWduYXR1cmU="}]}, "finish_reason": "STOP"}],
"model_version": "gemini-3.8-flash"})
interaction = Interaction.model_validate({
"id": "int_demo", "status": "completed", "model": "gemini-3.8-flash",
"created": "2026-11-04T09:00:00Z", "updated": "2026-11-04T09:00:01Z",
"steps": [{"type": "thought", "signature": "ZGVtby1zaWduYXR1cmU="},
{"type": "model_output", "content": [{"type": "text", "text": ANSWER}]}]})
router_resp = ChatCompletion.model_validate({
"id": "gen-demo", "object": "chat.completion", "created": 0,
"model": "anthropic/claude-haiku-5.5",
"choices": [{"index": 0, "finish_reason": "stop", "message": {
"role": "assistant", "content": ANSWER,
"reasoning_details": [{"type": "reasoning.encrypted", "data": "demo"}]}}]}) # OpenRouter-only field
for label, message in [
("OpenAI Responses", message_from_openai(openai_resp)),
("Anthropic", message_from_anthropic(claude_msg)),
("Gemini generate_content", message_from_gemini(gemini_resp)),
("Gemini Interactions", message_from_interaction(interaction)),
("OpenRouter", message_from_chat_completion(router_resp, provider="openrouter")),
]:
assert message.native
kinds = [item.get("type") or "+".join(sorted(item)) for item in message.native["payload"]]
print(f"{label:24s} text={message.parts[0].text!r} native={message.native['provider']}: {kinds}")
# The same canonical history sent back to its own provider vs. to another one
conv = Conversation("Be brief.", [text("user", "Pressure for hybrid tyres?"),
message_from_anthropic(claude_msg), text("user", "And when wet?")])
print("\nto Anthropic (same): ", [b["type"] for b in to_anthropic(conv)["messages"][1]["content"]])
print("to OpenAI (different):", to_openai_responses(conv)["input"][1])OpenAI Responses text='Start around 60 psi.' native=openai: ['reasoning', 'message']
Anthropic text='Start around 60 psi.' native=anthropic: ['thinking', 'text']
Gemini generate_content text='Start around 60 psi.' native=gemini: ['text+thought_signature']
Gemini Interactions text='Start around 60 psi.' native=gemini_interactions: ['thought', 'model_output']
OpenRouter text='Start around 60 psi.' native=openrouter: ['content+reasoning_details+role']
to Anthropic (same): ['thinking', 'text']
to OpenAI (different): {'role': 'assistant', 'content': 'Start around 60 psi.'}Notice that the OpenRouter fixture's reasoning_details field, which isn't part of OpenAI's schema, survived: the openai SDK keeps unknown fields (in model_extra), and model_dump() includes them, so the native payload replays it unchanged. The Interaction class is imported from a private module path (google.genai._gaos...) because SDK 2.34.0 doesn't re-export it publicly; in application code you'd only ever receive it from client.interactions.create, never import it.
6.5 What this means for you as an engineer#
- Convert at the edges, store the canonical form plus the native payload, and test the round trip.
- Keep converters boring: pure functions, no network, no hidden state. Everything that can fail at runtime (the call itself, retries, errors) belongs in the client layer (lesson 03.11).
- Decide what an empty turn means before you ship: placeholder, omit or error (
on_empty), and write the decision down (5.4). - When a provider adds a new part type, your converter should fail loudly (or keep it in the native payload), never silently drop it. The
UnknownContent/UnknownStepclasses in google-genai 2.34.0's Interactions types ("A Content variant the SDK doesn't recognize. Preserves the raw payload.") are a good model.
Part 7: Server-side conversation state: the API mechanics#
Deep-dive
Lesson 02.7, 3.5 covered what server-side state is: the provider stores the history and feeds all of it to the model on every turn, which saves you bandwidth and code but not tokens, and moves your data under the provider's retention rules. This part is the engineering reference for each API: the parameters, the methods, what is and isn't carried over, retention, and how it fails. All values are as of November 2026.
7.1 OpenAI: store and previous_response_id chaining#
In the Responses API:
storedefaults totrue. The reference: "If set to true, response data will be stored for at least 30 days, subject to the data retention exceptions." (The conversation-state guide says "saved for 30 days by default"; treat 30 days as the minimum, not a deletion guarantee. Separately from this stored application state, OpenAI keeps abuse-monitoring logs, see 10.1.)previous_response_idchains a new response to a stored one. The server loads the chain (the earlier responses' input and output items, reasoning items included) and prepends it to your newinput.- Billing doesn't change. OpenAI: "Even when using
previous_response_id, all previous input tokens for responses in the chain are billed as input tokens in the API." instructionsare not carried over. The reference: "When using along withprevious_response_id, the instructions from a previous response will not be carried over to the next response. This makes it simple to swap out system (or developer) messages in new responses." Developer or system messages that you put ininput, by contrast, are part of the stored items and are carried over.
sequenceDiagram
participant App as Your app
participant API as OpenAI Responses API
participant Store as Stored responses (30+ days)
App->>API: create(instructions=I, input="Hi, I'm Priya")
API->>Store: save resp_1 (input items + output items)
API-->>App: resp_1
App->>API: create(instructions=I, previous_response_id=resp_1, input="My name?")
API->>Store: load the chain behind resp_1
Note over API: model reads I + resp_1 items + new input<br/>(all billed as input tokens)
API->>Store: save resp_2
API-->>App: resp_2 "Your name is Priya."
App->>API: delete(resp_2), delete(resp_1)
API->>Store: remove both7.2 OpenAI: retrieve, list input items, delete#
Stored responses are resources with their own methods (SDK 3.42.1 signatures):
| Method | What it does |
|---|---|
client.responses.retrieve(response_id, include=..., stream=..., starting_after=...) |
Returns the stored Response object |
client.responses.input_items.list(response_id, after=..., limit=..., order=..., include=...) |
"Returns a list of input items for a given response", paginated (limit 1–100, default 20; order defaults to desc, newest first) |
client.responses.delete(response_id) |
Deletes it. The HTTP API returns {"id": ..., "object": "response.deleted", "deleted": true}; the Python SDK method returns None |
client.responses.cancel(response_id) |
Cancels a background response (lesson 03.9) |
This sample chains two turns, reads the stored response back, and deletes the chain:
# s7_1_openai_chain.py
"""OpenAI Responses: server-side chaining with previous_response_id, then cleanup."""
import openai
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
INSTRUCTIONS = "You are a bike-shop assistant. Answer in one short sentence."
first = client.responses.create(
model="gpt-6-luna",
instructions=INSTRUCTIONS,
input="Hi, I'm Priya. I ride a 2019 Trek FX 3.",
store=True, # the default, written out to make the choice visible
reasoning={"effort": "none"},
)
second = client.responses.create(
model="gpt-6-luna",
instructions=INSTRUCTIONS, # NOT carried over by previous_response_id: resend it
previous_response_id=first.id, # the server prepends the stored turn
input="What's my name, and which bike do I ride?",
reasoning={"effort": "none"},
)
print("answer:", second.output_text)
print("chained to turn 1:", second.previous_response_id == first.id)
print("input tokens billed for turn 2:", second.usage.input_tokens if second.usage else None)
# Stored responses can be read back...
stored = client.responses.retrieve(second.id)
print("retrieved:", stored.status, "| instructions:", stored.instructions)
newest = client.responses.input_items.list(second.id, limit=1) # newest first by default
for item in newest.data: # .data is this page only; looping over `newest` itself would fetch every page
print("newest input item:", item.type, getattr(item, "role", None))
# ...and deleted. Delete every response in the chain, not just the last one.
for response_id in (second.id, first.id):
client.responses.delete(response_id) # returns None on success
print("deleted 2 stored responses")
try: # chaining to a deleted response fails
client.responses.create(model="gpt-6-luna", previous_response_id=first.id,
input="Still there?", reasoning={"effort": "none"})
except openai.APIStatusError as e:
print("after delete:", type(e).__name__, e.status_code)answer: You're Priya, and you ride a 2019 Trek FX 3.
chained to turn 1: True
input tokens billed for turn 2: 64
retrieved: completed | instructions: You are a bike-shop assistant. Answer in one short sentence.
newest input item: message user
deleted 2 stored responses
after delete: BadRequestError 400Notes on this sample:
- The input-token count for turn 2 includes turn 1's items, exactly as if you had re-sent them.
reasoning={"effort": "none"}keeps the demo cheap and fast ongpt-6-luna; with reasoning on, the chain also carries the reasoning items for you.- The last line is not documented behaviour. OpenAI's docs don't state the HTTP error for chaining to a deleted, expired or never-stored response. The only documented code is for WebSocket mode,
previous_response_not_found("Retry with full input context andprevious_response_idset to null"). The one first-hand report we found, in OpenAI's community forum ("Response's previous_response_id reliable?"), shows an HTTP 400 with the text "Previous response with id '...' not found", so that is what the illustrative output shows; some stacks may surface a 404 instead. Catch bothopenai.BadRequestErrorandopenai.NotFoundErroron chained calls, check the message orparam == "previous_response_id", and fall back to your own copy of the history (7.10 shows the pattern). Handling onlyNotFoundErrorwould miss the failure the report describes. - Locally, this sample can't do what it says: Ollama accepts
previous_response_idand silently ignores it, then returns 404 forresponses.retrieve(7.9).
A third way to reuse stored items: item_reference. An item in input can be {"type": "item_reference", "id": "<item id>"}. OpenAI's reference defines it only as "An internal identifier for an item to reference", with the fields id and type. It lets you assemble an input list from items the server already holds instead of re-sending their content, and the items of a Conversation (7.3) are the same kind of object. OpenAI documents nothing more, so treat the following as reasoning to test against the real API, not as documented behaviour: the item has to still exist on the server, so it can only work for items that were stored (store=True, or inside a conversation); under store=False and under ZDR (7.5) nothing is stored, so there is nothing to reference; and a reference to an expired or deleted item will fail like an expired previous_response_id, so keep your own copy and the fallback.
7.3 OpenAI: the Conversations API#
A Conversation is a durable server-side object that holds items (messages, reasoning items, tool calls and outputs). Unlike a previous_response_id chain, you don't need to track the latest response ID: you pass the conversation ID, and the API both reads and updates it.
| Method (SDK 3.42.1) | What it does |
|---|---|
client.conversations.create(items=..., metadata=...) |
Creates a conversation, optionally seeded with items ("You may add up to 20 items at a time") |
client.conversations.retrieve(conversation_id) / .update(conversation_id, metadata=...) |
Reads it / replaces its metadata (the only updatable field) |
client.conversations.delete(conversation_id) |
Deletes the conversation. "Items in the conversation will not be deleted" |
client.conversations.items.create(conversation_id, items=..., include=...) |
Appends up to 20 items without calling the model |
client.conversations.items.list(conversation_id, after=..., limit=..., order=..., include=...) |
Lists items (limit 1–100, default 20; order defaults to desc) |
client.conversations.items.retrieve(item_id, conversation_id=...) / .delete(item_id, conversation_id=...) |
Reads / deletes one item (delete returns the parent conversation) |
client.responses.create(conversation=conversation_id, ...) |
"Items from this conversation are prepended to input_items for this response request. Input items and output items from this response are automatically added to this conversation after this response completes." |
sequenceDiagram
participant App as Your app
participant API as Responses API
participant Conv as Conversation conv_1 (no 30-day TTL)
App->>API: conversations.create(items, metadata)
API-->>App: conv_1
App->>API: responses.create(conversation=conv_1, instructions=I, input=Q)
API->>Conv: read all items, prepend to input
API->>Conv: append Q and the output items
API-->>App: response
App->>API: conversations.items.create(conv_1, items=[note])
API->>Conv: append note (no model call)
App->>API: conversations.items.list(conv_1)
API-->>App: items, oldest or newest first# s7_3_openai_conversations.py
"""OpenAI Conversations API: a durable server-side conversation object."""
import openai
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
INSTRUCTIONS = "You are a bike-shop assistant. Answer in one short sentence."
# 1. Create the conversation, optionally seeded with up to 20 items
conversation = client.conversations.create(
items=[{"type": "message", "role": "user", "content": "Hi, I'm Priya. I ride a Trek FX 3."}],
metadata={"app_conversation_id": "cv_12161198ad1b"}, # your own ID: never PII
)
print("created:", conversation.object, "| metadata:", conversation.metadata)
# 2. Generate a reply: the conversation's items are prepended, and the new input
# and output items are appended to the conversation automatically
reply = client.responses.create(model="gpt-6-luna", instructions=INSTRUCTIONS,
conversation=conversation.id,
input="Which tyre width suits it?",
reasoning={"effort": "none"})
print("reply:", reply.output_text)
# 3. Add items WITHOUT generating (e.g. a note from a human agent, as a user message)
client.conversations.items.create(conversation.id, items=[
{"type": "message", "role": "user", "content": "(Shop note: customer prefers puncture-resistant tyres.)"}])
# 4. List what the server holds, oldest first
items = list(client.conversations.items.list(conversation.id, order="asc"))
for item in items:
print("item:", item.type, getattr(item, "role", None))
# 5. Mixing the two chaining styles is rejected
try:
client.responses.create(model="gpt-6-luna", conversation=conversation.id,
previous_response_id=reply.id, input="Thanks!")
except openai.BadRequestError as e:
print("conversation + previous_response_id:", e.status_code)
# 6. Delete the items, then the conversation: deleting a conversation does NOT delete
# its items. (Collect the IDs first, so we don't page through a list we're shrinking.)
for item in list(client.conversations.items.list(conversation.id)):
client.conversations.items.delete(str(item.id), conversation_id=conversation.id)
deleted = client.conversations.delete(conversation.id)
print("conversation deleted:", deleted.deleted)created: conversation | metadata: {'app_conversation_id': 'cv_12161198ad1b'}
reply: For a Trek FX 3, tyres between 35 and 40 mm wide work well.
item: message user
item: message user
item: message assistant
item: message user
conversation + previous_response_id: 400
conversation deleted: TrueRules worth memorizing:
conversationandprevious_response_idare mutually exclusive. The reference says ofprevious_response_id: "Cannot be used in conjunction withconversation."- Retention differs from stored responses. "Conversation objects and items in them are not subject to the 30 day TTL [time to live, the automatic expiry]. Any response attached to a conversation will have its items persisted with no 30 day TTL." OpenAI's data-controls page lists conversations and their items as kept "Until deleted". That's convenient for long-lived threads, and it means deletion is your job (Part 10).
- Conversations are not ZDR-eligible. OpenAI's data-controls page lists
/v1/conversationsas "Until deleted" for application state and for abuse-monitoring retention, and "No" for Zero Data Retention eligibility. Under a ZDR agreement, don't plan on this API (7.5, 10.1). - Deleting a conversation doesn't delete its items, so the sample deletes the items first. Whether the orphaned items remain retrievable by ID isn't documented; if you need them gone, delete them explicitly.
instructionsstill aren't stored. Pass them on everyresponses.create, as with chaining.- The Assistants API's threads were the previous way to do this. The Assistants API was shut down on 26 August 2026; Responses plus Conversations replaces it (lesson 03.1).
7.4 OpenAI: truncation and compaction#
Server-side history grows like any other. The Responses API has two features for it:
truncation:"disabled"(the default; if the input would exceed the context window, "the request will fail with a 400 error") or"auto"(the API drops "items from the beginning of the conversation" to fit). As of November 2026, the API reference markstruncationas deprecated. Silent truncation was always risky (lesson 02.7, 2.6); prefer compaction or your own trimming.- Compaction (lesson 02.7, 4.5 covers the idea), in two forms:
- Automatic:
context_management=[{"type": "compaction", "compact_threshold": 200000}](an array;compact_thresholdhas a minimum of 1000). When the context crosses the threshold, the response includes an encryptedcompactionitem. OpenAI's compaction guide: "If you are using previous_response_id, pass only the new user message each turn"; if you manage history yourself, you "can drop items that came before the most recent compaction item", but "if you use previous_response_id chaining, do not manually prune." - On demand:
client.responses.compact(model=..., input=..., instructions=..., previous_response_id=...)returns a compacted response object (object: "response.compaction") whoseoutputholds the compacted window, including acompactionitem withencrypted_content. The guide: "do not prune /responses/compact output … pass it into your next /responses call as-is." It's "fully stateless and ZDR-friendly", and the compaction item is "opaque and not intended to be human-interpretable".
- Automatic:
# s7_4_openai_compaction.py
"""OpenAI compaction as an API feature: automatic (context_management) and on demand."""
from typing import Any
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
INSTRUCTIONS = "You are a bike-shop assistant."
history: list[Any] = [{"role": "user", "content": "Help me plan a 3-day bike tour of the Loire."}]
# 1. Automatic: when the rendered context crosses the threshold, the server compacts it
# and the output includes an encrypted `compaction` item. Keep it in your history.
response = client.responses.create(
model="gpt-6-luna", instructions=INSTRUCTIONS, input=history, store=False,
context_management=[{"type": "compaction", "compact_threshold": 200_000}],
)
history += response.output
print("output item types:", [item.type for item in response.output])
# 2. On demand: compact the whole window yourself, then send the result back AS-IS
compacted = client.responses.compact(model="gpt-6-luna", instructions=INSTRUCTIONS, input=history)
print("compacted object:", compacted.object, "| items:", [item.type for item in compacted.output])
history = list(compacted.output) + [{"role": "user", "content": "Now add a rest day."}]
follow_up = client.responses.create(model="gpt-6-luna", instructions=INSTRUCTIONS,
input=history, store=False)
print(follow_up.output_text[:80])output item types: ['reasoning', 'message']
compacted object: response.compaction | items: ['message', 'compaction']
Day 1 can stay as planned; I'd make day 3 a rest day in Amboise, with an optionalA short conversation doesn't cross a 200,000-token threshold, so the first call returns just a reasoning item and a message; in a long agent session you'd see a compaction item appear in response.output. Against the local stand-in, context_management is accepted and ignored, and responses.compact returns 404 (not supported locally).
Anthropic: compaction and context editing
Anthropic has the same idea in three forms. All three are beta as of November 2026, and in Python you use client.beta.messages for them:
- Compaction at a token threshold. Send the beta header
compact-2026-01-12andcontext_management={"edits": [{"type": "compact_20260112", "trigger": {"type": "input_tokens", "value": 150_000}}]}. The trigger's type must beinput_tokensand its value at least 50,000 (the default is 150,000). When the conversation reaches it, the reply starts with acompactionblock (itscontentis the summary text, plus asignature). You append the reply as usual, and on later requests "the API automatically drops all content blocks prior to thecompactionblock". The edit also takespause_after_compactionandinstructions(a custom summarization prompt that replaces the default one). - Compaction on demand. Send the beta header
compact-2026-09-04and the top-level parametercompaction={"type": "summarize"}. The API summarizes every message in the request, generates no reply, and returns the block alone withstop_reason: "compaction". You then swap it in: the block goes first inmessagesand the messages it summarized are removed (leaving any of them in front of the block is a 400,compaction_block_misplaced). You can't combinecompactionwithcontext_managementin one request. - Context editing. Send
context-management-2025-06-27with an edit of typeclear_tool_uses_20250919orclear_thinking_20251015. It clears old tool results or old thinking blocks by rule instead of summarizing them, and reports what it did incontext_management.applied_edits.
The rule is the same as on OpenAI: pass the compaction block back unchanged, signature included. Two details from Anthropic's pages: if you serialize blocks yourself, use to_dict() or model_dump(exclude_none=True), because a plain model_dump() adds text: null and citations: null to the block and the API then returns a 400 (message_from_anthropic already uses exclude_none=True); and on Claude 5.1 and later, thinking blocks from before a compaction block aren't carried forward, so strip thinking blocks from reinserted turns or you can hit the prefix check from 5.5.
# s7_4_anthropic_compaction.py
"""Anthropic server-side compaction (beta, at a token threshold): pass the compaction block back unchanged."""
import anthropic
from anthropic.types.beta import BetaMessageParam
from dotenv import load_dotenv
load_dotenv()
client = anthropic.Anthropic()
SYSTEM = "You are a bike-shop assistant."
history: list[BetaMessageParam] = [
{"role": "user", "content": "Help me plan a 3-day bike tour of the Loire."}]
response = client.beta.messages.create( # client.beta, not client.messages, for beta fields
model="claude-haiku-5-5", max_tokens=4_000, system=SYSTEM, messages=history,
betas=["compact-2026-01-12"],
# When input reaches the trigger (at least 50,000 tokens), the API summarizes the
# conversation and puts a `compaction` block first in the reply.
context_management={"edits": [{"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": 150_000}}]},
)
print("block types:", [block.type for block in response.content])
# Append the WHOLE reply, compaction block included. On later requests the API drops
# everything before that block, so you don't prune the history yourself.
history.append({"role": "assistant", "content": response.content})
history.append({"role": "user", "content": "Now add a rest day."})block types: ['thinking', 'text']A short conversation never reaches a 150,000-token trigger, so the reply has no compaction block; in a long agent session it would start with one. Run against the local stand-in, the sample runs end to end, but Ollama ignores context_management and the beta header (not supported locally). As of November 2026 Module 02 lists no built-in compaction for Gemini (lesson 02.7, 4.5; not re-checked here), and OpenRouter's middle-out compression truncates rather than summarizes.
Storing compaction items
A compaction item isn't an ordinary message. It replaces many turns, has no text you could show a user, and is opaque. So the store keeps it as an assistant message with no portable parts and the item in native (for OpenAI's responses.compact, the whole compacted window; for Anthropic's threshold compaction, the block inside the normal reply). Then mark_compacted() sets compacted_by on every earlier turn. The rows stay: load() skips them, so it returns exactly what you should send (the compaction message plus later turns), and load(raw=True) returns the full transcript for audits and for switching providers. The builders replay a compaction item only to the provider that made it, and raise EmptyTurnError for any other, because a placeholder there would silently throw the whole summarized history away. Keep the raw transcript: the compacted state is a provider-specific cache of it.
# s7_4_store_compaction.py
"""Store an OpenAI compaction item next to the raw transcript (no network).
The fixture follows the documented shape of `client.responses.compact(...)`: an object of type
"response.compaction" whose `output` holds the compacted window, ending in an opaque `compaction`
item. The encrypted content is a made-up placeholder.
"""
import os
from openai.types.responses import CompactedResponse
from chatfmt import EmptyTurnError, message_from_openai, text, to_anthropic, to_openai_responses
from convo_store import ConversationStore
DB = "out/compaction_demo.db"
if os.path.exists(DB):
os.remove(DB)
store = ConversationStore(DB)
cid = store.create(user_ref="u_9f2c41d0", system_prompt="You are a bike-shop assistant.")
# Four ordinary turns, stored as usual (the raw transcript)
for i in range(1, 3):
store.append(cid, text("user", f"Question {i} about a Loire bike tour"))
store.append(cid, text("assistant", f"Answer {i}"))
# responses.compact(...) returned this. Store it as ONE assistant message: no portable text,
# the whole compacted window in `native`, so it can only be replayed to OpenAI, unchanged.
compacted = CompactedResponse.model_validate({
"id": "resp_compact_demo", "object": "response.compaction", "created_at": 0,
"output": [{"type": "compaction", "id": "cmp_demo", "encrypted_content": "gAAAA...demo"}],
"usage": {"input_tokens": 900, "output_tokens": 120, "total_tokens": 1020,
"input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
"output_tokens_details": {"reasoning_tokens": 0}}})
seq = store.append(cid, message_from_openai(compacted), provider_response_id=compacted.id)
print("turns marked as compacted:", store.mark_compacted(cid, seq))
store.append(cid, text("user", "Now add a rest day."))
active = store.load(cid) # what you SEND: the compaction item + the new turn
full = store.load(cid, raw=True) # what you KEEP: the full transcript
print("active turns:", len(active.messages), "| full transcript:", len(full.messages))
print("to OpenAI, input items:", [i.get("type") or i["role"] for i in to_openai_responses(active)["input"]])
try:
to_anthropic(active) # an opaque OpenAI summary means nothing to Claude
except EmptyTurnError as e:
print("to Anthropic, compacted view:", type(e).__name__)
print("to Anthropic, full transcript: ", len(to_anthropic(full)["messages"]), "messages")turns marked as compacted: 4
active turns: 2 | full transcript: 5
to OpenAI, input items: ['compaction', 'user']
to Anthropic, compacted view: EmptyTurnError
to Anthropic, full transcript: 5 messages7.5 OpenAI: retention, Zero Data Retention and failure cases#
| Situation | What happens (as of November 2026) |
|---|---|
store omitted |
Stored: "for at least 30 days" |
store=False |
Not stored. You can't chain to it later or retrieve it. Reasoning items come back with encrypted_content so you can send them yourself |
| Zero Data Retention (ZDR) organization | "The store parameter for /v1/responses and v1/chat/completions will always be treated as false, even if the request attempts to set the value to true." So chaining by ID isn't available; use client-managed history with encrypted reasoning, and stateless compaction. The Conversations API isn't ZDR-eligible (7.3). ZDR also excludes customer content from abuse-monitoring logs, which otherwise keep API usage for up to 30 days (10.1) |
Chain to an expired, deleted or store=False response |
An error; the HTTP status isn't documented (a community report shows 400 "Previous response with id ... not found"; others may see 404). Catch BadRequestError and NotFoundError, and fall back to sending the full history from your store (7.10) |
Pass both conversation and previous_response_id |
Rejected ("Cannot be used in conjunction with conversation") |
Change model mid-chain |
Not prohibited in the docs. Reasoning from a different model family is omitted ("persisted reasoning can be reused only within the same model family"), so continuity is lost silently |
Forget instructions on a chained call |
Accepted; the model runs without your instructions |
store=True on Chat Completions |
Different feature: stores completions for distillation and evals; default false; no chaining |
Who can request ZDR, and what else it changes, is a contract question covered in lesson 02.9, Part 9.
7.6 Gemini Interactions: previous_interaction_id#
The Interactions API offers the same pattern:
storedefaults totrue: "By default, the API stores all Interaction objects". Retention: 55 days on the paid tier (configurable in AI Studio to 7, 14, 28 or 55 days) and 1 day on the free tier.previous_interaction_idchains a new interaction to a stored one.- Only the history carries over. Google: "The
previous_interaction_idparameter preserves only the conversation history (inputs and outputs)… The other parameters are interaction-scoped…tools,system_instruction,generation_config(includingthinking_level,temperature, etc.). This means you must re-specify these parameters in each new interaction if you want them to apply." store=Falselimits you. It "is incompatible with background execution and prevents usingprevious_interaction_idfor subsequent turns";background=Truewithstore=Falseis a 400.- Methods:
client.interactions.get(id, include_input=...)returns the stored interaction (withinclude_input=True, including theuser_inputsteps),client.interactions.delete(id)deletes it, andclient.interactions.cancel(id)cancels a running background interaction.
# s7_6_gemini_chain.py
"""Gemini Interactions: server-side chaining with previous_interaction_id."""
from typing import Any
from dotenv import load_dotenv
from google import genai
load_dotenv()
client = genai.Client()
SYSTEM = "You are a bike-shop assistant. Answer in one short sentence."
TOOLS: list[Any] = [{
"type": "function",
"name": "check_stock",
"description": "Check whether a product is in stock at the shop.",
"parameters": {"type": "object", "properties": {"sku": {"type": "string"}},
"required": ["sku"]},
}]
GENERATION: Any = {"thinking_level": "low", "max_output_tokens": 1_000}
turn1 = client.interactions.create(
model="gemini-3.8-flash",
input="Hi, I'm Priya. I ride a 2019 Trek FX 3.",
system_instruction=SYSTEM, tools=TOOLS, generation_config=GENERATION,
) # store defaults to True
assert turn1.id
turn2 = client.interactions.create(
model="gemini-3.8-flash",
input="What's my name, and which bike do I ride?",
previous_interaction_id=turn1.id, # only the HISTORY carries over...
system_instruction=SYSTEM, tools=TOOLS, generation_config=GENERATION, # ...so resend these
)
assert turn2.id
print("answer:", turn2.output_text)
print("status:", turn2.status, "| chained to turn 1:", turn2.previous_interaction_id == turn1.id)
if turn2.usage:
print("input tokens for turn 2:", turn2.usage.total_input_tokens)
# Read a stored interaction back, including the user_input steps
stored = client.interactions.get(turn2.id, include_input=True)
print("stored steps:", [s.type for s in stored.steps or []])
# Delete both turns when you no longer need them
for interaction_id in (turn2.id, turn1.id):
client.interactions.delete(interaction_id)
print("deleted 2 stored interactions")answer: You're Priya, and you ride a 2019 Trek FX 3.
status: completed | chained to turn 1: True
input tokens for turn 2: 118
stored steps: ['user_input', 'thought', 'model_output']
deleted 2 stored interactionsgenerate_content has no chaining. It's stateless; you send contents every time (or let the chat helper do it, Part 8). Its config does have a store field, which the SDK documents as configuring "the logging behavior for a given request" and which takes precedence over the project-level logging setting: a request-logging control, not conversation state.
7.7 Anthropic: stateless Messages, message threads (beta) and Managed Agents#
Anthropic's documentation is explicit: "The Messages API is stateless, which means that you always send the full conversational history to the API." There's no store parameter and no response retrieval. Two newer features change the picture slightly:
Message threads (beta, message-threads-2026-08-12). "A message thread keeps a conversation on the server for a short time. You send the full conversation once, with your system prompt and tools. On each later turn, you send only the new messages and the id of the previous response." It's an optimization for time to first token (TTFT: how long before the first output appears) in long agent loops, not durable storage:
- Create with
thread={"type": "create"}; continue withthread={"type": "continue", "previous_message_id": <previous response id>}and only the new messages. systemandtoolsare create-only: sending either on a continue request "even asnull, returns a 400 error". Fields such asmodel,tool_choice,thinkingandoutput_configare fixed: a different value is a 400thread_fingerprint_mismatch.- "It expires 5 minutes after its last request, and the API deletes it no more than 1 hour after its last use." A continue request on an expired thread returns 404 with
error_codethread_not_found; you then replay the full conversation in a new create request. Each responseidcan be continued only once (thread_already_continued). - "Your application stays the source of truth for the conversation." Threads are not eligible for Zero Data Retention (their contents are held in memory, encrypted, for at most an hour).
- The SDK has a helper,
client.beta.messages.thread(...), that keeps the conversation in memory and replays automatically onthread_not_found.
# s7_7_anthropic_thread.py
"""Anthropic message threads (beta): send only the new messages on later turns."""
import anthropic
from anthropic.types.beta import BetaMessageParam
from dotenv import load_dotenv
load_dotenv()
client = anthropic.Anthropic()
BETA = ["message-threads-2026-08-12"]
SYSTEM = "You are a bike-shop assistant. Answer in one short sentence."
history: list[BetaMessageParam] = [ # YOUR copy stays the source of truth
{"role": "user", "content": "Hi, I'm Priya. I ride a 2019 Trek FX 3."}]
first = client.beta.messages.create(
model="claude-haiku-5-5", max_tokens=1_000, system=SYSTEM, # system/tools: create only
messages=history, thread={"type": "create"}, betas=BETA)
history.append({"role": "assistant", "content": first.content})
new_turn: BetaMessageParam = {
"role": "user", "content": "What's my name, and which bike do I ride?"}
history.append(new_turn)
try:
second = client.beta.messages.create(
model="claude-haiku-5-5", max_tokens=1_000, # fixed fields: keep identical
messages=[new_turn], # only what's new
thread={"type": "continue", "previous_message_id": first.id}, betas=BETA)
except anthropic.NotFoundError: # thread_not_found: expired etc.
second = client.beta.messages.create( # replay the full conversation
model="claude-haiku-5-5", max_tokens=1_000, system=SYSTEM,
messages=history, thread={"type": "create"}, betas=BETA)
print(next(b.text for b in second.content if b.type == "text"))You're Priya, and you ride a 2019 Trek FX 3.Against the local stand-in the sample runs end to end, but Ollama ignores thread, so the continue turn ran without the earlier message (and the local model didn't know the name). Not supported locally.
Managed Agents (beta, managed-agents-2026-04-01) is a different product: an Anthropic-hosted agent harness with agents, environments and sessions, which Anthropic describes as "stateful by design: sessions are long-running, resume cleanly after pauses, and store conversation history, sandbox state, and outputs server-side". Sessions persist until you delete them. It's an agent platform rather than a message API, so Module 08A covers it.
7.8 OpenRouter: stateless by design#
OpenRouter's Chat Completions API is stateless, and so is its Responses-compatible endpoint: "This API is stateless - each request is independent and no conversation state is persisted between requests. … Requests that set store: true or a non-null previous_response_id are rejected with a 400 error." Send the full history on every request.
Two OpenRouter fields are related to conversations without storing them:
session_id(inextra_body, or thex-session-idheader; at most 256 characters) groups related requests in OpenRouter's logs and acts as a sticky routing key (requests with the same key go to the same upstream provider), which helps prompt-cache hits (lesson 03.7).reasoning_details, which you must send back unchanged (3.6).
7.9 Try it free: what the local stand-in does with server-side state#
Can you practise server-side state locally? This probe asks Ollama (the only local stand-in; Gemini's Interactions API has none), and compares the input-token count of a chained request with an unchained one:
# s7_9_local_state_probe.py
"""What does the local stand-in do with server-side state parameters? (runs free, locally)"""
import openai
SYSTEM = "Answer in one short sentence."
FACT, QUESTION = "My name is Priya.", "What is my name?"
# --- Ollama, OpenAI format ---------------------------------------------------------------
oai = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
first = oai.responses.create(model="gpt-6-luna", instructions=SYSTEM, input=FACT, max_output_tokens=30)
second = oai.responses.create(model="gpt-6-luna", instructions=SYSTEM, input=QUESTION,
previous_response_id=first.id, max_output_tokens=30)
baseline = oai.responses.create(model="gpt-6-luna", instructions=SYSTEM, input=QUESTION,
max_output_tokens=30)
print("Ollama previous_response_id: accepted, echoed back as", second.previous_response_id)
print(f" input tokens chained={second.usage.input_tokens if second.usage else '?'} "
f"unchained={baseline.usage.input_tokens if baseline.usage else '?'}")
for label, call in [("responses.retrieve", lambda: oai.responses.retrieve(first.id)),
("conversations.create", lambda: oai.conversations.create())]:
try:
call()
except openai.APIStatusError as e:
print(f"Ollama {label}: {type(e).__name__} {e.status_code}")Ollama previous_response_id: accepted, echoed back as None
input tokens chained=24 unchained=24
Ollama responses.retrieve: NotFoundError 404
Ollama conversations.create: NotFoundError 404Ollama accepts the chaining parameter and silently ignores it: the chained request carried no history (the same 24 input tokens as the unchained one), and the response doesn't echo the previous ID. It has no stored responses or conversations at all (404s). Gemini's previous_interaction_id (7.6) can't be probed locally, because Ollama doesn't speak Gemini's API, so that sample is hosted-only and illustrative. So:
- The local stand-in can't teach server-side state. It can run the code path, not the behaviour. The samples in this part are illustrative for that reason.
- Don't let tests pass on a server that ignores the feature. A test suite that runs against a local OpenAI-compatible server would "pass" with a broken chaining implementation. Assert on what the response says (
previous_response_id == first.id), or test chaining against the real API in a small, budgeted contract test (a test that checks your code against the real API's behaviour, lesson 03.10).
7.10 Choosing client-managed or server-managed state#
| Concern | Client-managed (you store and resend the history) | Server-managed (previous_response_id, Conversations, previous_interaction_id) |
|---|---|---|
| Portability | Any provider, any model; switch mid-conversation (5.4) | Tied to one provider; migrating means exporting items |
| Privacy and deletion | Your database, your retention rules, one place to delete | A second copy under the provider's retention (OpenAI responses 30+ days, conversations until deleted; Gemini 55 days paid, 1 day free); deletion means API calls per object. Not available under ZDR |
| Cost | You pay for the full history every turn | The same: history is still billed as input tokens |
| Caching | Works if your prefix is stable (lesson 03.7) | Works; Google says chaining helps implicit caching on Interactions |
| Reasoning continuity | You must keep and resend encrypted reasoning, signatures and thought steps yourself | The provider keeps them in the exact format it needs |
| Bandwidth and latency | The whole history is uploaded every turn | Only the new input is uploaded (Anthropic's message threads exist for exactly this) |
| Editing history | Easy: trim, summarize, redact, branch | Hard: chains are append-only; you'd start a new chain |
| Debugging | You can log and replay the exact request | The real input lives on the server; you need retrieve/input_items.list/get to see it |
| Failure modes | Overflow and your own bugs | Expired or deleted IDs, forgotten per-request parameters, mixing modes, provider outages affecting history |
A sensible default for most products: client-managed history as the source of truth, always, with store=False where you don't need the provider's stored copy of the conversation (the provider may still keep abuse-monitoring logs, 10.1). Add server-side state as an optimization where it clearly pays (long, tool-heavy agent sessions on a single provider), and keep your own copy so you can replay when an ID fails. That's also the explicit design of Anthropic's message threads.
Chain when you can, replay when you can't
That default is easy to describe and easy to get wrong, so here it is as code. send_turn stores the user turn first, then tries the cheap path: previous_response_id plus only the new message (and instructions, which aren't carried over). If OpenAI answers that the previous response is gone, it forgets the dead ID, replays the full stored history with to_openai_responses, and records the new response ID in the conversation's provider_state column. The server is a mock (an httpx2.MockTransport) that stores response IDs and rejects an unknown previous_response_id with a 400. The error's message follows the community report quoted in 7.2, and its other fields are plausible rather than documented, so the exact error JSON is illustrative. That's why the sample runs with no key, and why it proves the control flow, not OpenAI's behaviour:
# s7_10_chain_or_replay.py
"""Server-side chaining as an optimization: chain when you can, replay your own history when you can't.
Runs against a MOCK server (httpx2.MockTransport) that behaves like the Responses API for this
purpose: it stores responses, and rejects a previous_response_id it doesn't know with a 400. The
message text and `param` of that error are modelled on a community report (OpenAI doesn't
document the status), so the exact error JSON is illustrative. Uses chatfmt.py and convo_store.py.
"""
import json
import os
import httpx2
import openai
from openai import OpenAI
from chatfmt import message_from_openai, text, to_openai_responses, usage_from_openai
from convo_store import ConversationStore
stored: set[str] = set() # the mock server's "database" of stored responses
bodies: list[dict] = [] # every request body the SDK sent
def handler(request: httpx2.Request) -> httpx2.Response:
body = json.loads(request.content)
bodies.append(body)
previous = body.get("previous_response_id")
if previous and previous not in stored: # expired, deleted or never stored
return httpx2.Response(400, json={"error": {
"message": f"Previous response with id '{previous}' not found.",
"type": "invalid_request_error", "param": "previous_response_id", "code": None}})
response_id = f"resp_{len(bodies)}"
if body.get("store", True):
stored.add(response_id)
return httpx2.Response(200, json={
"id": response_id, "object": "response", "created_at": 0, "model": "gpt-6-luna",
"status": "completed", "parallel_tool_calls": True, "tool_choice": "auto", "tools": [],
"output": [{"type": "message", "id": f"msg_{len(bodies)}", "role": "assistant",
"status": "completed",
"content": [{"type": "output_text", "text": f"reply {len(bodies)}", "annotations": []}]}],
"usage": {"input_tokens": 10, "output_tokens": 3, "total_tokens": 13,
"input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
"output_tokens_details": {"reasoning_tokens": 0}}})
client = OpenAI(api_key="sk-test", max_retries=0,
http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))
INSTRUCTIONS = "You are a bike-shop assistant."
def is_missing_response(e: openai.APIStatusError) -> bool:
"""OpenAI doesn't document the status for a missing previous_response_id (reports say 400;
some stacks may answer 404), so accept both and look at the parameter or the message."""
return e.status_code in (400, 404) and (
getattr(e, "param", None) == "previous_response_id" or "previous response" in e.message.lower())
def send_turn(store: ConversationStore, cid: str, user_text: str) -> str:
store.append(cid, text("user", user_text)) # the store stays the source of truth
previous = store.get_provider_state(cid).get("openai_previous_response_id")
response = None
if previous: # 1. try the cheap path: new turn only
try:
response = client.responses.create(
model="gpt-6-luna", instructions=INSTRUCTIONS, # NOT carried over: resend
previous_response_id=previous, input=[{"role": "user", "content": user_text}])
except openai.APIStatusError as e:
if not is_missing_response(e):
raise # any other error is not ours to hide
store.set_provider_state(cid, "openai_previous_response_id", None) # forget the dead ID
if response is None: # 2. replay the whole stored history
response = client.responses.create(model="gpt-6-luna", **to_openai_responses(store.load(cid)))
store.append(cid, message_from_openai(response), usage=usage_from_openai(response.usage),
provider_response_id=response.id)
store.set_provider_state(cid, "openai_previous_response_id", response.id)
return response.output_text
def show(label: str, body: dict) -> None:
sent = body.get("input")
n = len(sent) if isinstance(sent, list) else 1
print(f"{label}: previous_response_id={body.get('previous_response_id')} "
f"instructions={'yes' if body.get('instructions') else 'NO'} input_items={n}")
DB = "out/chain_or_replay.db"
if os.path.exists(DB):
os.remove(DB)
store = ConversationStore(DB)
cid = store.create(user_ref="u_9f2c41d0", system_prompt=INSTRUCTIONS)
send_turn(store, cid, "Hi, I'm Priya. I ride a 2019 Trek FX 3.")
show("turn 1 (nothing to chain to)", bodies[-1])
send_turn(store, cid, "Which tyre width suits it?")
show("turn 2 (chained) ", bodies[-1])
stored.clear() # simulate: the server forgot everything
send_turn(store, cid, "What's my name?")
show("turn 3, chained, rejected ", bodies[-2])
show("turn 3, replayed ", bodies[-1])
print("state now:", store.get_provider_state(cid), "| turns in the store:", len(store.load(cid).messages))turn 1 (nothing to chain to): previous_response_id=None instructions=yes input_items=1
turn 2 (chained) : previous_response_id=resp_1 instructions=yes input_items=1
turn 3, chained, rejected : previous_response_id=resp_2 instructions=yes input_items=1
turn 3, replayed : previous_response_id=None instructions=yes input_items=5
state now: {'openai_previous_response_id': 'resp_4'} | turns in the store: 6Read the four lines as a story. Turn 2 sent one input item and the ID. Turn 3 tried the same, was rejected (the mock "forgot" every stored response, as an expiry would), and was replayed with all five stored items and no previous_response_id. Nothing was lost, because the store held the history all along; and provider_state now points at the newest response, so turn 4 chains again. Two details matter in real code: any error that isn't "previous response not found" is re-raised, so a real outage isn't hidden behind a silent replay; and the same shape works for Gemini Interactions (previous_interaction_id, resending system_instruction, tools and generation_config, 7.6), with its own not-found check.
Part 8: Gemini's chat helper#
Deep-dive
8.1 client.chats: client-side history in a Python object#
The google-genai SDK has a convenience layer for multi-turn chat on generate_content. Google's migration guide calls it a "client-side chat helper": it keeps the history in memory and resends it on every call. Nothing is stored at Google by the helper itself.
| Method (SDK 2.34.0) | What it does |
|---|---|
client.chats.create(model=..., config=..., history=...) |
Creates a Chat object, optionally starting from an existing history (a list of Content) |
chat.send_message(message, config=...) |
Sends the curated history plus the new message; records both |
chat.send_message_stream(message, config=...) |
The same, streaming (lesson 03.3) |
chat.get_history(curated=False) |
Returns the comprehensive history by default, or the curated one |
There is no equivalent helper for the Interactions API; there you chain with previous_interaction_id or resend steps (2.6).
8.2 Curated vs comprehensive history#
The SDK's docstring defines them: "The comprehensive history contains all turns (user input and model responses), including any invalid or rejected model outputs", and the curated history keeps "only the valid turns". A model turn is valid if the response had a candidate with content, and that content has non-empty parts. When a model turn is invalid, the curated history drops it and the user message that caused it. Crucially, send_message sends the curated history to the model.
This demo makes the difference visible. The mock server answers turns 1 and 3 and blocks turn 2 (a response with no candidates and a blockReason, as documented for blocked prompts):
# s8_gemini_chat_history.py
"""Gemini's chat helper: curated vs comprehensive history, against a mock server.
The mock answers turns 1 and 3 normally and BLOCKS turn 2 (no candidates, a block reason),
using the documented generateContent response shape.
"""
import json
import httpx
from google import genai
from google.genai import types
sent_roles: list[list[str]] = []
replies = iter([
{"candidates": [{"content": {"role": "model", "parts": [{"text": "Hi Priya!"}]},
"finishReason": "STOP"}]},
{"promptFeedback": {"blockReason": "SAFETY"}}, # turn 2: blocked, no candidate
{"candidates": [{"content": {"role": "model", "parts": [{"text": "You ride a Trek FX 3."}]},
"finishReason": "STOP"}]},
])
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
sent_roles.append([f"{c['role']}:{c['parts'][0]['text'][:14]}" for c in body["contents"]])
return httpx.Response(200, json=next(replies))
client = genai.Client(api_key="test-key", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=httpx.MockTransport(handler))))
chat = client.chats.create(model="gemini-3.8-flash",
config=types.GenerateContentConfig(system_instruction="Be brief."))
for text in ["I'm Priya, I ride a Trek FX 3.", "(a message the API blocks)", "Which bike do I ride?"]:
response = chat.send_message(text)
print(f"sent {text[:30]!r:34} -> {response.text!r} block_reason="
f"{response.prompt_feedback.block_reason if response.prompt_feedback else None}")
def summary(history: list[types.Content]) -> list[str]:
return [f"{c.role}:{(c.parts[0].text or '')[:14] if c.parts else '<no parts>'}" for c in history]
print("\ncomprehensive:", summary(chat.get_history())) # curated=False is the default
print("curated: ", summary(chat.get_history(curated=True)))
print("turn 3 actually sent:", sent_roles[2])sent "I'm Priya, I ride a Trek FX 3." -> 'Hi Priya!' block_reason=None
sent '(a message the API blocks)' -> None block_reason=BlockedReason.SAFETY
sent 'Which bike do I ride?' -> 'You ride a Trek FX 3.' block_reason=None
comprehensive: ["user:I'm Priya, I r", 'model:Hi Priya!', 'user:(a message the', 'model:<no parts>', 'user:Which bike do ', 'model:You ride a Tre']
curated: ["user:I'm Priya, I r", 'model:Hi Priya!', 'user:Which bike do ', 'model:You ride a Tre']
turn 3 actually sent: ["user:I'm Priya, I r", 'model:Hi Priya!', 'user:Which bike do ']- The blocked turn returned
response.text=None, not an exception. Checkprompt_feedback.block_reasonand the candidates' finish reasons (lesson 03.8). - The comprehensive history kept the blocked exchange (with an empty model turn); the curated history dropped it.
- Turn 3 was sent without turn 2: the model never saw the blocked message. Usually that's what you want. But if your UI shows the blocked message, what the user sees and what the model sees now differ, and you should show that (for example, mark the message as "not sent").
8.3 When to use your own store instead#
The chat helper is handy for scripts, notebooks and prototypes. For a product, prefer your own store (Part 5):
- The
Chatobject lives in one process's memory. A restart, a second server or a serverless function loses it. You can rebuild one withclient.chats.create(..., history=stored_contents), but then your store is the source of truth anyway. - It works only with
generate_contentand only with Gemini, so it can't carry a conversation across providers. - You can't see or control usage, request IDs, trimming or redaction per turn without wrapping it.
If you do use it, persist chat.get_history() (the comprehensive one, so you keep an audit trail) after each turn, with model_dump(mode="json") to keep thought signatures as base64.
Part 9: The common request parameters and how they map#
9.1 The mapping table#
This table is the module's reference for parameter names. For what each parameter does (and why sampling knobs are disappearing), see lesson 02.5, Part 6. As of November 2026:
| Concept | OpenAI Responses | OpenAI Chat Completions | Anthropic Messages | Gemini generate_content (config) |
Gemini Interactions | OpenRouter (Chat Completions) |
|---|---|---|---|---|---|---|
| Output cap (includes reasoning tokens) | max_output_tokens |
max_completion_tokens (legacy max_tokens is deprecated and "not compatible with o-series models") |
max_tokens, required |
max_output_tokens |
generation_config.max_output_tokens |
max_tokens (its full reference marks it deprecated in favour of max_completion_tokens; "some providers enforce a minimum of 16") |
| Stop sequences | ❌ not in the Responses API | stop, up to 4 (not supported on some reasoning models) |
stop_sequences (stop_reason: "stop_sequence", and stop_sequence holds the match) |
stop_sequences, up to 5 |
generation_config.stop_sequences |
stop, up to 4 |
| Reasoning effort (lesson 02.8, Part 3) | reasoning={"effort": ...}: none, minimal, low, medium, high, xhigh, max (model-dependent) |
reasoning_effort |
output_config={"effort": ...}: low, medium, high, xhigh, max |
thinking_config=ThinkingConfig(thinking_level=...): MINIMAL, LOW, MEDIUM, HIGH (per model) |
generation_config.thinking_level: minimal…high |
reasoning={"effort": ...} (max…none) via extra_body |
| Request metadata | metadata: up to 16 pairs, keys ≤ 64 chars, values ≤ 512 chars |
metadata (same limits) |
metadata has only user_id |
labels (keys and values ≤ 63 chars, lowercase letters, digits, _ and -; keys start with a letter) |
labels (same rules) |
metadata (same limits as OpenAI); passed to its observability destinations |
| End-user identifier | safety_identifier (≤ 128 chars), replacing user |
safety_identifier |
metadata.user_id (≤ 512 chars) |
labels={"safety_identifier": <hashed id>}: Google's documented convention for "safety identifiers from aggregators"; label keys and values ≤ 63 chars, lowercase letters, digits, _ and - |
labels with the same key, by analogy: the Interactions reference lists labels but not the safety_identifier convention, so check it before relying on it |
user |
| Removed or ignored sampling knobs | temperature, top_p only with reasoning effort none on GPT-6 |
same | temperature, top_p, top_k: a 400 under anthropic-version: 2026-10-21, even at defaults |
temperature, top_p, top_k "deprecated and ignored" from Gemini 3.6 Flash / 3.5 Flash-Lite; candidate_count unsupported on Gemini 3+ |
not in the reference's generation_config (the SDK still has temperature, top_p) |
passed through to the model, if supported |
n: multiple candidates |
❌ make separate calls | n, 1–128; billed for every choice |
❌ make separate calls | candidate_count; unsupported on Gemini 3+ |
❌ not in generation_config (one answer per interaction) |
❌ not documented |
| Logit bias | ❌ | logit_bias: token ID → bias −100…100 |
❌ | ❌ | ❌ | ✅ where supported (mainly OpenAI and open-weight models) |
| Repetition penalties | ❌ | presence_penalty, frequency_penalty: −2…2, default 0 |
❌ | presence_penalty, frequency_penalty documented, but custom values return an error on Gemini 3.6 Flash and later |
❌ | −2…2, where supported |
| Seed (02.5, Part 7) | ❌ | seed: best effort; determinism not guaranteed |
❌ | seed: best effort |
generation_config.seed |
seed: best effort, passed through |
| Server-side storage | store (default true) |
store (default false, for evals/distillation) |
none (message threads beta aside) | store: a request-logging setting, not conversation state |
store (default true) |
none; store: true on its Responses endpoint is a 400 |
The four rows above the storage row (n, logit bias, repetition penalties and seed) are the legacy knobs you will meet in older code and in OpenRouter migrations. Two names need care: best_of belongs to the older /completions endpoint, not to chat, so it has no column here; and on OpenAI max_tokens in Chat Completions is the deprecated alias of max_completion_tokens (the first row). Whether a frontier model still honours n, logit_bias, the penalties or seed — versus silently ignoring them — is a per-model question covered in 02.5, Part 6; on OpenRouter, provider: {"require_parameters": true} routes only to backends that support the parameter.
9.2 Try it: one set of options, six parameter shapes#
Here is the mapping as code, with OpenAI's metadata limits checked locally (OpenRouter documents the same limits):
# s9_param_map.py
"""Map one set of portable request options to each provider's parameter names."""
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Options:
max_output_tokens: int = 1_000 # includes reasoning/thinking tokens everywhere
stop: list[str] = field(default_factory=list)
effort: str | None = None # "low" | "medium" | "high"
end_user: str | None = None # an opaque, hashed user ID (see Part 10)
metadata: dict[str, str] = field(default_factory=dict)
def check_metadata(metadata: dict[str, str]) -> None:
"""OpenAI's documented limits; OpenRouter documents the same ones."""
if len(metadata) > 16:
raise ValueError("metadata: at most 16 key-value pairs")
for key, value in metadata.items():
if len(key) > 64 or len(value) > 512:
raise ValueError(f"metadata {key!r}: keys up to 64 chars, values up to 512")
def gemini_labels(o: Options) -> dict[str, str]:
"""Gemini `labels`: keys and values up to 63 chars, lowercase letters, digits, `_` and `-`."""
labels = {k.lower()[:63]: v.lower()[:63] for k, v in o.metadata.items()} # simplistic: see below
if o.end_user:
labels["safety_identifier"] = o.end_user[:63] # Google's documented key for end-user IDs
return labels
def to_params(api: str, o: Options) -> dict[str, Any]:
check_metadata(o.metadata)
if api == "openai_responses":
p: dict[str, Any] = {"max_output_tokens": o.max_output_tokens}
if o.effort:
p["reasoning"] = {"effort": o.effort}
if o.end_user:
p["safety_identifier"] = o.end_user # replaces the deprecated `user`
if o.metadata:
p["metadata"] = o.metadata
# no stop sequences in the Responses API
elif api in ("openai_chat", "openrouter"):
p = {"max_completion_tokens": o.max_output_tokens} # `max_tokens` is the legacy name
if o.stop:
p["stop"] = o.stop[:4] # up to 4
if o.effort and api == "openai_chat":
p["reasoning_effort"] = o.effort
elif o.effort: # OpenRouter's unified object,
p["extra_body"] = {"reasoning": {"effort": o.effort}} # not an openai SDK argument
if o.end_user:
p["safety_identifier" if api == "openai_chat" else "user"] = o.end_user
if o.metadata:
p["metadata"] = o.metadata
elif api == "anthropic":
p = {"max_tokens": o.max_output_tokens} # required
if o.stop:
p["stop_sequences"] = o.stop
if o.effort:
p["output_config"] = {"effort": o.effort}
if o.end_user:
p["metadata"] = {"user_id": o.end_user} # Anthropic's only metadata field
elif api == "gemini": # goes inside GenerateContentConfig
p = {"max_output_tokens": o.max_output_tokens}
if o.stop:
p["stop_sequences"] = o.stop[:5] # up to 5
if o.effort:
p["thinking_config"] = {"thinking_level": o.effort.upper()}
if o.metadata or o.end_user:
p["labels"] = gemini_labels(o)
elif api == "gemini_interactions":
gen: dict[str, Any] = {"max_output_tokens": o.max_output_tokens}
if o.stop:
gen["stop_sequences"] = o.stop
if o.effort:
gen["thinking_level"] = o.effort
p = {"generation_config": gen} # resend on every turn
if o.metadata or o.end_user:
p["labels"] = gemini_labels(o) # the Interactions reference lists `labels` too
else:
raise ValueError(api)
return p
opts = Options(max_output_tokens=2_000, stop=["\n\nUser:"], effort="low",
end_user="u_9f2c41d0", metadata={"feature": "tyre-advisor"})
for api in ["openai_responses", "openai_chat", "anthropic", "gemini", "gemini_interactions", "openrouter"]:
print(f"{api:20s} {to_params(api, opts)}")openai_responses {'max_output_tokens': 2000, 'reasoning': {'effort': 'low'}, 'safety_identifier': 'u_9f2c41d0', 'metadata': {'feature': 'tyre-advisor'}}
openai_chat {'max_completion_tokens': 2000, 'stop': ['\n\nUser:'], 'reasoning_effort': 'low', 'safety_identifier': 'u_9f2c41d0', 'metadata': {'feature': 'tyre-advisor'}}
anthropic {'max_tokens': 2000, 'stop_sequences': ['\n\nUser:'], 'output_config': {'effort': 'low'}, 'metadata': {'user_id': 'u_9f2c41d0'}}
gemini {'max_output_tokens': 2000, 'stop_sequences': ['\n\nUser:'], 'thinking_config': {'thinking_level': 'LOW'}, 'labels': {'feature': 'tyre-advisor', 'safety_identifier': 'u_9f2c41d0'}}
gemini_interactions {'generation_config': {'max_output_tokens': 2000, 'stop_sequences': ['\n\nUser:'], 'thinking_level': 'low'}, 'labels': {'feature': 'tyre-advisor', 'safety_identifier': 'u_9f2c41d0'}}
openrouter {'max_completion_tokens': 2000, 'stop': ['\n\nUser:'], 'extra_body': {'reasoning': {'effort': 'low'}}, 'user': 'u_9f2c41d0', 'metadata': {'feature': 'tyre-advisor'}}Read it as a checklist when porting code: the stop sequence silently disappears on the Responses API, the end-user ID has a different name on every provider (on Gemini it's the safety_identifier key inside labels), Gemini's generate_content takes uppercase level names (LOW, a ThinkingLevel enum in the SDK) where Interactions and the others take lowercase strings, and on Interactions everything except labels lives inside generation_config, which must be resent on every chained turn (7.6). The label sanitizing here is simplistic: real code should map keys to the allowed character set and reject what it can't map. The end_user value is truncated to 63 characters for Gemini, which is why the 64-character hex ID from 10.3 needs one character cut.
Part 10: Privacy and data handling of message data#
Deep-dive
Conversations contain your users' words, so every copy is personal data until proven otherwise. Policy questions (contracts, ZDR eligibility, data residency, training use) are covered in lesson 02.9, Part 9; PII handling as a security topic is Module 12's. This part covers what the APIs in this lesson store, and how to remove it.
10.1 What store keeps, and how to delete it#
| Provider / feature | What's kept by default | Retention (as of November 2026) | How to delete |
|---|---|---|---|
OpenAI Responses (store defaults to true) |
The response: input items, output items, reasoning, instructions | "At least 30 days" | client.responses.delete(id) per response; or send store=False (this controls the stored response only: see the logs below) |
| OpenAI Conversations | Every item in the conversation | "Until deleted"; not ZDR-eligible | conversations.items.delete per item, then conversations.delete (which doesn't delete items) |
| OpenAI Chat Completions | No stored application state unless store=True (abuse-monitoring logs still apply: see below) |
— | Set store=False (the default) |
| Anthropic Messages | No stored conversation. Anthropic's privacy centre: "we automatically delete inputs and outputs on our backend within 30 days of receipt or generation", with exceptions (for example longer-retention services such as the Files API, Usage Policy enforcement, legal requirements) | Up to 30 days | Nothing to call; ZDR by agreement |
| Anthropic message threads (beta) | The thread, in memory, encrypted | Deleted "no more than 1 hour after the thread's last use" | Let it expire |
| Anthropic Managed Agents (beta) | Session history, sandbox state, outputs | "Transcripts persist until you delete them" | Delete the session (Module 08A) |
Gemini Interactions (store defaults to true) |
The interaction: inputs and steps | 55 days on the paid tier (configurable down to 7), 1 day on the free tier | client.interactions.delete(id); or store=False (losing chaining and background) |
Gemini generate_content |
Nothing conversation-shaped; store controls request logging |
Per your project's logging settings, plus Google's own logging (below) (lesson 02.9, Part 9) | — |
| OpenRouter | "OpenRouter does not store your prompts or responses" unless you opt in to logging; it stores request metadata such as token counts and latency | — | Logging is off by default; the upstream provider's own policy also applies |
10.2 No personal data in metadata or identifiers#
Metadata fields are for your bookkeeping and the provider's abuse detection; they are not protected like message content and often appear in dashboards, logs and exports:
- OpenAI
safety_identifier: "We recommend hashing their username or email address, in order to avoid sending us any identifying information." - Anthropic
metadata.user_id: "This should be a uuid, hash value, or other opaque identifier… Do not include any identifying information such as name, email address, or phone number." - OpenRouter
user: "Per-end-user identifier for abuse isolation. Use a stable ID, hash, or pseudonym." - Gemini
labels["safety_identifier"]: Google'sgenerateContentreference says, underlabels, "Safety identifiers from aggregators: Use the keysafety_identifier" (for example{"safety_identifier": "user_session_123"}). Labels are free-form request metadata, so the same rule applies: a hash, never a name or email. Labels follow Cloud label rules: keys start with a letter, and keys and values are at most 63 characters of lowercase letters, digits,_and-. metadataandlabels: put feature names, experiment IDs and your own opaque conversation IDs there, never names, emails, phone numbers, order contents or free text from the user.
10.3 Pseudonymous user IDs#
A plain hash of an email isn't anonymous: anyone with a list of emails can hash them and match. Use a keyed hash (an HMAC) with a secret that never leaves your systems, and a "purpose" string so that the ID you send to one provider can't be linked to the ID you use elsewhere:
# s10_hash_user_ids.py
"""Pseudonymous end-user IDs: a keyed hash, so the provider never sees who the user is."""
import hashlib
import hmac
import os
# A secret "pepper" kept in your secret store, never sent to a provider, never in the code.
# With a plain SHA-256, anyone could hash a list of known emails and match them; the key
# prevents that. Run: USER_ID_PEPPER=demo-pepper python s10_hash_user_ids.py
PEPPER = os.environ["USER_ID_PEPPER"].encode()
def end_user_id(internal_user_id: str, purpose: str = "llm-abuse-v1") -> str:
"""Stable per user and purpose; 64 hex characters (fits every provider's limit)."""
message = f"{purpose}:{internal_user_id}".encode()
return hmac.new(PEPPER, message, hashlib.sha256).hexdigest()
uid = end_user_id("user-48213")
print("safety_identifier / metadata.user_id / user:", uid, f"({len(uid)} chars)")
print("same input, same ID:", uid == end_user_id("user-48213"))
print("another purpose, unlinkable ID:", end_user_id("user-48213", "analytics-v1")[:16] + "...")
print("Gemini labels[\"safety_identifier\"] (63-char limit):", uid[:63])safety_identifier / metadata.user_id / user: 154129066f3d2a971b46871a0934d2f25e6123846143f37001f5a07996039a94 (64 chars)
same input, same ID: True
another purpose, unlinkable ID: 322b33965f2d466d...
Gemini labels["safety_identifier"] (63-char limit): 154129066f3d2a971b46871a0934d2f25e6123846143f37001f5a07996039a9The same user always gets the same ID (so the provider's abuse systems can still group their requests), and the 64-character hex string fits every limit in 9.1 except Gemini's 63-character label values, where you truncate it by one character (the last line of the output). The sample reads the secret from the USER_ID_PEPPER environment variable and fails if it's unset, so a real secret never lives in code; run it as USER_ID_PEPPER=demo-pepper python s10_hash_user_ids.py. Rotating the pepper breaks the link to all old IDs, which is useful if it leaks.
One scheme for the whole module. This is the only recipe the module uses: HMAC-SHA256 with a secret (USER_ID_PEPPER) over purpose:user_id. Only the purpose changes. The ID you send to a provider uses "llm-abuse-v1" (above). The IDs you write to your own cost records and logs use the same function with the purpose "logs-v1", truncated to 16 hex characters to keep log lines short: lesson 03.7, 5.1, 03.10, 4.2 and 03.11 all do. Because the purposes differ, a provider's abuse report (which carries the first ID) can't be matched to your logs (which carry the second) by anyone who holds both, and the same pepper variable serves every lesson. Use a third purpose, such as "storage-v1", for the user_ref column of the store in Part 5.
10.4 Deleting a conversation everywhere#
A user's "delete my conversation" must reach every copy you control: your database, the provider-side objects your requests created, uploaded files (lesson 03.6), explicit caches (lesson 03.7) and your logs (lesson 03.10). Say plainly which copies you don't control: the providers' abuse-monitoring and request logs (10.1). Because the store in Part 5 records each turn's provider and response ID, the provider part is a loop. This function goes in the same folder as convo_store.py:
# s10_4_delete_everywhere.py
"""Delete a conversation from your store AND the provider-side copies it created.
Uses convo_store.py from Part 5 (same folder). Provider objects exist only for turns
sent with store=True (OpenAI Responses) or the Interactions default store=True.
"""
import openai
from dotenv import load_dotenv
from google import genai
from convo_store import ConversationStore
load_dotenv()
def is_not_found(e: Exception) -> bool:
"""A 404 from either SDK. google-genai 2.34.0 raises Interactions errors from a private
module path, so test the status code instead of importing the class."""
return getattr(e, "status_code", None) == 404
def delete_everywhere(store: ConversationStore, conversation_id: str) -> None:
store.soft_delete(conversation_id) # first: hide it from the app, keep the rows
rows = store.db.execute(
"SELECT provider, provider_response_id FROM messages"
" WHERE conversation_id = ? AND provider_response_id IS NOT NULL",
(conversation_id,)).fetchall()
oai, gemini = openai.OpenAI(), genai.Client()
for provider, response_id in rows:
try:
if provider == "openai":
oai.responses.delete(response_id)
elif provider == "gemini_interactions":
gemini.interactions.delete(response_id)
# anthropic, openrouter, gemini generate_content: nothing stored to delete
except Exception as e:
if not is_not_found(e):
raise # keep the soft-deleted rows: retry later
# a 404 means already expired or deleted: fine
store.delete(conversation_id) # last, so a failure above can be retried
print(f"deleted {conversation_id}: {len(rows)} stored response IDs checked")
if __name__ == "__main__":
delete_everywhere(ConversationStore("conversations.db"), "cv_12161198ad1b")deleted cv_12161198ad1b: 4 stored response IDs checkedNotes: the function soft-deletes first (load() and append() stop seeing the conversation at once, while the rows stay so a failure can be retried) and hard-deletes last. A 404 is treated as "already gone", and any other error is re-raised so the soft-deleted rows survive for a retry. It tests status_code == 404 instead of importing google-genai's Interactions exception class, which lives under a private module path in SDK 2.34.0 (google.genai._gaos.lib.compat_errors): a pin-or-break import is a poor default for code you'll copy into production. Smoke-run against the stand-in, the function ran end to end on an empty database; deleting real provider objects needs a key (not supported locally).
What this means for you as an engineer: treat every provider-side copy as a record in your data inventory. If you can't list it (no stored IDs), you can't delete it on request. Prefer store=False plus your own store, and when you do use provider storage, record the IDs at the moment you create them.
10.5 Compliance frameworks: HIPAA, SOC 2 and data residency#
Three names come up in every vendor review and procurement questionnaire. They are different kinds of thing, and each bites somewhere different in an API call:
- HIPAA and the BAA. HIPAA is the US health-privacy law. A vendor that stores or processes protected health information (PHI) on your behalf must sign a Business Associate Agreement (BAA) and meet HIPAA's safeguard requirements. "HIPAA-eligible" or "HIPAA-ready" means the vendor offers a BAA and limits which endpoints and features it covers — it is not a certification you inherit by calling the API.
- SOC 2 Type II. An independent auditor's report on a company's security controls, renewed on a schedule. It is evidence for your own risk review, not a legal safe harbour: it says the vendor's controls were designed and operated as described, not that your particular use is compliant.
- Data residency. A promise about where prompts and outputs are processed and stored — a region or a contractual addendum. It is orthogonal to the other two: a US-resident endpoint can still sit outside a BAA, and an EU endpoint says nothing about training use.
What each provider offers through its API, as of November 2026 (verify on the linked pages before you rely on it; this is the API surface, not legal advice — 02.9, Part 9 covers the policy questions, and Module 12 covers handling regulated data):
| Offering | OpenAI | Anthropic | Gemini API | OpenRouter |
|---|---|---|---|---|
| HIPAA / BAA | The API is HIPAA-eligible with an executed BAA (OpenAI's "Business Associate and Healthcare Addendum") and an org ID provisioned for a qualifying retention arrangement. OpenAI's HIPAA guide (July 2026) calls the requirement "Modified Retention", a family that includes Modified Abuse Monitoring and Zero Data Retention, while its data-controls guide names "Private Retention with Private Safety Processing" and "Safety Retention" for BAA-eligible endpoints (both read 11 November 2026), so use the term in your own contract paperwork. The help centre's BAA article describes accepting the standard BAA in the API Platform settings for organizations with established API usage (seen as a search excerpt on 11 November 2026; the signing route has changed before, so confirm it with OpenAI). Eligibility is per endpoint — the current list is on the help centre's "HIPAA eligible products and functionality" page. Web Search with live internet access is not HIPAA-eligible | The Claude API is "HIPAA-ready" with a signed BAA and a HIPAA-enabled org; eligible organizations can review and execute the BAA and enable HIPAA readiness from the Claude Console (API and data retention; Anthropic's separate BAA help article describes the Primary Owner signing and then contacting Anthropic, so expect a possible manual step). Covers the Claude API (api.anthropic.com) and Claude in Microsoft Foundry — not PHI in the Console, consumer plans, Claude Code, Amazon Bedrock, Google Cloud's Agent Platform or Claude Platform on AWS |
No HIPAA or BAA coverage is stated for the plain Gemini API (generativelanguage.googleapis.com) in the Gemini API terms and docs pages checked in November 2026, and its terms say not to submit sensitive, confidential or personal information to the unpaid services; regulated workloads go through Google Cloud: its HIPAA page (read 11 November 2026) lists "Generative AI on Agent Platform" and "Gemini Enterprise Agent Platform" among the products under the Google Cloud BAA and does not mention the Gemini API or AI Studio |
No HIPAA programme of its own: it is a processor/router, so PHI coverage runs through the downstream provider's terms |
| SOC 2 | SOC 2 reports via the OpenAI Trust Portal | SOC 2 Type II report via Anthropic's Trust Center | Via Google Cloud (no certification is stated on the Gemini API pages checked) | SOC 2 Type II (trust.openrouter.ai), plus a DPA |
| Residency | Regional processing endpoints for eligible models (a documented price uplift applies); regional storage in many regions | inference_geo: "us" keeps inference in the US; workspace data at rest is US-only |
Via Google Cloud regions on Agent Platform; the plain API's logged data may be cached in any country where Google has facilities | EU and US in-region routing on Business and Enterprise plans; otherwise provider.only can pin region-specific endpoints |
Three consequences for the code in this lesson:
- Eligibility is per endpoint and per feature. OpenAI's HIPAA endpoint list includes
/v1/responsesand/v1/chat/completionsbut not every API; Anthropic's page carries a feature-eligibility table, and its Batch and Files APIs sit outside the ZDR arrangement (10.1 notes the Files API's longer retention). Check the current table before you route PHI through a feature — the lists change. - A BAA changes the retention arrangement, not the API shape. OpenAI's API HIPAA path requires a provisioned retention arrangement (its HIPAA guide says Modified Retention); Anthropic's HIPAA readiness is a different arrangement from ZDR (encryption, access controls and audit logging rather than immediate deletion — a HIPAA org does not also need ZDR). Your
store=and caching choices (10.1, lesson 03.7) interact with these arrangements: a feature that is ZDR-eligible may still sit outside a BAA, and vice versa. - OpenRouter moves the compliance question downstream. Its SOC 2 and DPA cover OpenRouter's own processing; whether PHI may flow at all depends on the provider each request routes to, which is why its routing filters (
zdr,data_collection: "deny",provider.only) exist (02.9, 5.4).
Common misconceptions#
| Misconception | Reality |
|---|---|
| "The system prompt is a message like any other." | Only in Chat Completions. Responses has instructions, Anthropic a top-level system, Gemini a system_instruction, and each treats it differently on chained turns (2.1). |
"developer and system are different priority levels in the API." |
In the Responses API they sit at the same level, above user. In OpenAI's Model Spec, "System" means OpenAI's own instructions; your application's are "Developer" (2.2). |
"Gemini uses assistant like everyone else." |
It uses model, and the Interactions API uses step types instead of roles (2.5, 2.6). |
| "Storing the reply text is enough to continue the conversation." | Reasoning items, thinking blocks and thought signatures must be sent back unchanged for continuity, and in tool loops for validity (3.6). |
| "Prefilling the assistant turn is a reliable way to force JSON." | Current Claude (4.6+) and Gemini (3.6 Flash, 3.5 Flash-Lite and later) models reject it with a 400. Use structured output (4.2). |
| "It passed against the local server, so the shape is valid." | The stand-in enforces almost none of the shape rules and silently ignores server-side state parameters (4.3, 7.9). |
"previous_response_id keeps my instructions." |
It doesn't: instructions are per request. The same goes for system_instruction, tools and generation_config on Gemini Interactions (7.1, 7.6). |
| "Server-side state saves tokens." | The whole history is still billed as input on every turn. It saves bandwidth and code, not tokens (7.10). |
| "Deleting an OpenAI conversation deletes its contents." | "Items in the conversation will not be deleted." Delete the items too (7.3). |
"Anthropic's input_tokens is the total input." |
It excludes cached tokens; add cache_read_input_tokens and cache_creation_input_tokens (5.1). |
| "The Anthropic Messages API now stores conversations." | It's stateless. Message threads (beta) hold a conversation for minutes as a latency optimization, and you remain the source of truth (7.7). |
"store=False (or deleting the response) means the provider kept nothing." |
It removes stored application state only. OpenAI keeps abuse-monitoring logs for up to 30 days unless ZDR or Modified Abuse Monitoring applies, and Google logs paid-tier prompts for a limited period to detect violations (10.1). |
| "Every provider can take an end-user ID except Gemini." | Gemini takes it as labels["safety_identifier"] (9.1). |
| "A reply always has text I can store." | Tool-only replies, refusals and replies cut off while thinking have none; sending them back as empty turns is a request bug (5.4). |
| "The provider signed a BAA (or has SOC 2), so our app is HIPAA-compliant." | A BAA covers only the endpoints and features the vendor lists, and only when your account is set up for it (for example a provisioned retention arrangement on OpenAI). SOC 2 is an auditor's report on the vendor's controls, not a licence for your use. Compliance for your product is still yours to build and document (10.5). |
| "A hashed email is anonymous." | A plain hash can be reversed by hashing candidate emails. Use a keyed hash with a secret (10.3). |
Key takeaways#
- A request has three layers: instructions, turns and parts. Every provider has them, under different names and shapes; print the wire to see them (Part 1).
- Instructions go in
instructionsor adevelopermessage (OpenAI Responses), adeveloper/systemmessage (Chat Completions, OpenRouter), top-levelsystem(Anthropic, string or text blocks) orsystem_instruction(Gemini). Anthropic's current models also accept mid-conversation system messages after a user turn. - Roles:
user/assistanteverywhere except Gemini (user/model) and Interactions (steps:user_input,model_output,thought...). Anthropic merges consecutive same-role turns. - Store content in the full typed form, and keep each reply in two views: portable parts and the provider-native payload, replayed unchanged to the same provider and dropped for others.
- Append the full reply: OpenAI output items (with
encrypted_contentwhenstore=False), Anthropic thinking blocks with signatures, Gemini content with thought signatures, Interactions thought steps, OpenRouterreasoning_details. - No prefill on current Claude and Gemini models; check the last turn before sending. Shape errors are deterministic 400s: catch them with type checking and a pre-flight check, and never retry them.
- A SQLite (or Postgres) store with conversations, messages and parts, plus provider, model, usage (normalized, with Anthropic's cached tokens added back), request IDs and response IDs, gives you persistence, auditing, cost data, provider switching and deletion.
- Server-side state moves storage, not cost: OpenAI
store(defaulttrue, 30+ days) withprevious_response_idor the Conversations API (no TTL; mutually exclusive with chaining); Geminiprevious_interaction_id(default stored, 55 days paid / 1 day free). Resendinstructions, and on Interactionssystem_instruction,toolsandgeneration_config, every turn. - Anthropic and OpenRouter are stateless (message threads are a short-lived beta optimization); the local stand-in silently ignores chaining.
- Default to client-managed history as the source of truth,
store=Falseunless you need the provider's stored copy (abuse-monitoring logs may remain, and the Conversations API isn't ZDR-eligible), pseudonymous keyed-hash user IDs (safety_identifieron OpenAI,metadata.user_idon Anthropic,labels["safety_identifier"]on Gemini,useron OpenRouter), no PII in metadata, and a delete path that reaches every provider-side copy you control. - Replies with no text (tool-only, refusals, cut off while thinking) are never sent back as empty turns or replayed natively:
chatfmt.pysubstitutes a placeholder, omits them or raises, andNoOutputErrorcovers a 200 with nothing to read. - Compaction items (OpenAI, Anthropic) are opaque and go back unchanged, only to the provider that made them; store them next to the raw transcript.
- A chained call can fail when its ID expires: catch both 400 and 404, and replay your stored history (7.10).
- HIPAA, SOC 2 and data residency are different things: a BAA is per provider, per endpoint and per account arrangement (OpenAI needs a provisioned retention arrangement; the plain Gemini API states no BAA or certification coverage; OpenRouter passes the question to the downstream provider); SOC 2 is evidence, not permission; residency is about where processing happens (10.5).
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Role | The label on a turn saying who produced it (user, assistant/model, system/developer, tool), which sets how much authority the model gives it |
developer message |
OpenAI's role for application instructions; ranked above user messages, and the recommended replacement for system on reasoning models |
| Instruction hierarchy (chain of command) | OpenAI's ranking of instruction sources: OpenAI's own system rules, then developer, then user, with tool output and quoted text having no authority by default |
instructions |
The Responses API's top-level system/developer text; applies to one request only and is not carried over by previous_response_id |
system_instruction |
Gemini's instruction field: in GenerateContentConfig for generate_content, top level for Interactions |
| Mid-conversation system message | A {"role": "system"} message inside Anthropic's messages, placed after a user turn, accepted by current Claude models |
| Content block / content part / Part | A typed piece of a turn's content (text, image, tool call, thinking...), as Anthropic, OpenAI and Gemini respectively call it |
| Output item | One typed element of an OpenAI Responses output list (message, reasoning, function_call, compaction...) |
| Step | One typed element of a Gemini Interactions conversation (user_input, model_output, thought, function_call...); Interactions has no roles |
| Thinking signature | The encrypted copy of Claude's reasoning on a thinking block, which must be sent back unchanged |
| Thought signature | Gemini's opaque encrypted reasoning value on a Part (or a thought step), required for reasoning continuity |
Encrypted reasoning (encrypted_content) |
OpenAI's opaque reasoning payload on reasoning items in stateless mode, which you resend to keep continuity |
| Assistant prefill | Ending a request with a partial assistant turn for the model to continue; rejected by current Claude and Gemini models |
| Turn merging | Anthropic's rule that consecutive same-role turns are combined into one |
| Provider-native payload | A reply exactly as the provider returned it, stored so it can be replayed unchanged to the same provider |
| Canonical message format | Your own provider-neutral representation of a conversation, converted to each provider's shape at the edges |
| Client-managed state | Your application stores the conversation and sends all of it on every request |
| Server-managed state | The provider stores the conversation and you reference it by ID (previous_response_id, a conversation ID, previous_interaction_id) |
store (Responses / Interactions) |
The flag that makes OpenAI Responses or Gemini Interactions keep a copy of the request and response (default true on both) |
previous_response_id |
OpenAI Responses parameter that chains a request to a stored response |
| Conversations API | OpenAI's durable server-side conversation object, with items you can add, list and delete |
previous_interaction_id |
Gemini Interactions parameter that chains a request to a stored interaction |
| Message thread | Anthropic's beta feature that holds a conversation on the server for minutes so later turns send only new messages |
| Compaction item / block | An opaque summary of earlier context that you pass back unchanged: OpenAI's encrypted compaction item (context_management, responses.compact) or Anthropic's compaction block (beta) |
item_reference |
An OpenAI Responses input item that points at an item the server already holds, by ID |
| Portable content | The non-empty text and image parts of a turn; a turn without any is never replayed natively or sent as empty content |
| Curated vs comprehensive history | In Gemini's chat helper: only valid turns (what's sent to the model) vs every turn including blocked or empty ones |
safety_identifier |
OpenAI's end-user identifier for abuse detection, replacing user; should be a hash |
| Keyed hash (HMAC) | A hash of a user ID, mixed with a secret key and a purpose string, so providers (or your logs) can group one user's requests without learning who they are, and IDs made for different purposes cannot be linked |
| HIPAA | The US health-privacy law; sending protected health information to an API requires the vendor's Business Associate Agreement and HIPAA-eligible endpoints |
| Business Associate Agreement (BAA) | The contract that makes a vendor a permitted handler of PHI under HIPAA; offered per provider, sometimes self-serve, always with endpoint restrictions |
| SOC 2 Type II | An auditor's report on a company's security controls over a period; procurement evidence, not a legal safe harbour |
| Data residency | The contractual or architectural promise about which region processes and stores your prompts and outputs |
All terms are also collected in the glossary.
Exercises#
- Wire diff (1.2): add a fourth user turn to
s1_2_three_turns_wire.pythat sends an image (use the 1x1 PNG froms6_converter_demo.pyand the local vision modelqwen3-vl:2bif you have it). Print the bodies again and list the five different ways the image is represented. - Developer messages (2.2): extend
s2_roles_wire.pywith a Chat Completions call that has both adeveloperand asystemmessage. What does the SDK send? Then write down which of the two you'd use for a new project, and why. - Mid-conversation system (2.4): the checker in
s4_4_preflight.pysimplifies Anthropic's placement rule to "directly after a user turn". Make it exact: also allow an assistant turn that ends in a server tool result, require the system message to be followed by an assistant turn or to end the list, allow empty-content effort-only system messages anywhere, and flag a system message between atool_useand itstool_result. Add a test case for each rule. - Shape errors (4.3): add a B4 case to
s4_3_shape_errors.py: a mock Anthropic 413request_too_largeresponse. Which exception class does the SDK raise? (Hint: look atanthropic.RequestTooLargeError.) - Store (5.3): add a
parent_idcolumn tomessagesand aload_branch(conversation_id, leaf_message_id)method that follows parents back to the root. Use it to implement "regenerate the last answer" without deleting the old one. - Usage (5.1): write
usage_from_interactions(usage)for the Interactionsusageobject and store it froms5_4_switch_providers.pywith a fourth turn onclient.interactions.create. Which fields come backNone? - Converter (6.2): add a
to_openrouter_responsesbuilder (OpenRouter's stateless Responses-compatible endpoint) and include it in the round-trip test. What, if anything, differs fromto_openai_responses? - Server-side state (7.1, 7.9): write a test that would fail against a server that ignores
previous_response_id. Run it against the local stand-in and confirm it fails. - Gemini chat (8.2): change the mock in
s8_gemini_chat_history.pyso turn 2 returns a candidate withfinishReason: "SAFETY"and emptyparts. Is the turn curated out? Explain using the SDK's validity rule. - Parameters (9.2): add
"verbosity"toOptionsand map it per provider using lesson 02.5, 6.4. Which providers have nowhere to put it? - Privacy (10.4): extend
delete_everywhereto also delete OpenAI Conversations recorded in the conversation'sprovider_statecolumn (write the ID there withstore.set_provider_state(cid, "openai_conversation", conversation.id)when you create it), items first. Conversations aren't ZDR-eligible, so also write one sentence for your data inventory about the logs that this function can't delete. - Empty turns (5.4): add a Chat Completions reply with
finish_reason: "length"andcontent: ""tos6_empty_turns_demo.py. What doeshas_portable_contentsay, and what does each builder send underon_empty="placeholder","omit"and"error"? Then change the default in your own copy and decide which one your product should use. - Chain or replay (7.10): extend
s7_10_chain_or_replay.pyso that the mock answers 404 instead of 400 for an unknown ID. Doesis_missing_responsestill catch it? Then make the mock return a 400 about something else (a badmodel) and confirm thatsend_turnre-raises instead of replaying.
Check yourself#
- Name the field or role that carries standing instructions in each of: OpenAI Responses, Chat Completions, Anthropic, Gemini
generate_content, Gemini Interactions.Responses:instructions(or adeveloper/systemmessage ininput). Chat Completions: adeveloper(orsystem) message inmessages. Anthropic: the top-levelsystemparameter (string or text blocks). Geminigenerate_content:system_instructioninGenerateContentConfig. Interactions: the top-levelsystem_instructionstring. - In OpenAI's API, how do
developerandsystemmessages rank relative to each other and tousermessages? What does "System" mean in the Model Spec?They're at the same level in the API: "Instructions given with the developer or system role take precedence over instructions given with the user role." In the Model Spec, "System" means OpenAI's own instructions, which developers can't override; your instructions are "Developer". Usedeveloper(orinstructions) for new code. - What are the placement rules for a mid-conversation
systemmessage on current Claude models?It must immediately follow auserturn (including one carryingtool_resultblocks) or an assistant turn ending in a server tool result, must precede an assistant turn or end the array, can't be first when it has content, and can't sit between atool_useand itstool_result. Otherwise it's a 400. - What role name does Gemini use for the model's turns, and how does the Interactions API represent turns instead?
model. Interactions uses steps whosetypesays who produced them:user_input,model_output, plusthought,function_calland others. - What happens if you send Anthropic two consecutive
usermessages?They're combined into a single user turn. - Why should you append
response.contentto a Claude history rather than the reply's text? Give the OpenAI and Gemini equivalents.response.contentincludes thinking (and redacted-thinking) blocks with their signatures, which the model needs for continuity and which tool loops require. OpenAI: append allresponse.outputitems (reasoning included). Gemini: appendresponse.candidates[0].content(keeping thought signatures); on Interactions, append every returned step. - You call OpenAI with
store=False. How do you keep reasoning continuity on the next turn?Keep thereasoningitems fromresponse.output(they carryencrypted_contentby default in stateless mode;include=["reasoning.encrypted_content"]is still accepted) and send them back in the next request'sinput, unchanged and in order. - Your app prefills
{as the last assistant turn to force JSON, and it starts failing after a model upgrade. Why, and what should you do instead?Current Claude (4.6 and later) and Gemini (3.6 Flash, 3.5 Flash-Lite and later) models reject a request ending in an assistant/model turn with a 400. Use structured output (lesson 03.4) and remove trailing assistant turns from stored histories. - Why did all the "bad shape" requests in 4.3 part B need a mock server?The local stand-in doesn't enforce those rules: Ollama accepted prefills and wrong roles, and the stand-in model doesn't produce thinking blocks at all. The mock returns the provider's documented error so the real SDK's error handling can be shown. Note what the mocks are: the Anthropic fixtures use the error text Anthropic documents, but for Gemini, Google documents the sentence, not a full error envelope, so the surrounding JSON in B3 (
code,status) is illustrative. - Anthropic reports
input_tokens: 120,cache_read_input_tokens: 4000,cache_creation_input_tokens: 0. How many input tokens did the request contain?120 + 4,000 + 0 = 4,120. Anthropic'sinput_tokenscounts only tokens after the last cache breakpoint. - You chain a Responses call with
previous_response_idbut omitinstructions. What happens?The request succeeds, but the model runs without your instructions, becauseinstructionsaren't carried over by chaining. Behaviour changes silently. - What's the difference between OpenAI's stored responses and Conversations in retention, and what does
conversations.deletenot do?Stored responses are kept "at least 30 days"; conversation items aren't subject to the 30-day TTL and are kept until deleted.conversations.deletedoesn't delete the conversation's items; delete them first if they must go. - Which three Gemini Interactions parameters are not carried over by
previous_interaction_id, and what's the retention of stored interactions?system_instruction,toolsandgeneration_config. Stored interactions are kept 55 days on the paid tier (configurable shorter) and 1 day on the free tier. - Can you use
previous_response_idthrough OpenRouter? Under OpenAI Zero Data Retention?No: OpenRouter's Responses endpoint rejectsstore: trueandprevious_response_idwith a 400. Under ZDR,storeis always treated as false, so there's nothing to chain to; send the history yourself. - In Gemini's chat helper, what's sent to the model on the next turn after a blocked response: the curated or the comprehensive history?The curated history: the blocked exchange (and the user message that caused it) is dropped from what's sent.
- Why is HMAC-SHA256 with a secret better than SHA-256 for a
safety_identifier?Anyone with a list of candidate emails or user IDs can SHA-256 them and match the results. With a secret key, only you can compute the mapping, so the identifier reveals nothing to the provider. - A customer in healthcare asks whether your app may send patient data to the Gemini API, and whether Anthropic's SOC 2 report is enough. What do you answer, using 10.5?Not through the plain Gemini API, and SOC 2 alone is not enough. Protected health information needs a signed BAA with the vendor and a setup the BAA covers. No BAA or compliance-certification coverage is stated for the plain Gemini API on the Google pages checked in November 2026, and Google's migration page says to use the Gemini platform API on Google Cloud when you need specific enterprise controls, so regulated workloads go through Google Cloud (Google Cloud's HIPAA page lists Generative AI on Agent Platform and Gemini Enterprise Agent Platform under the Google Cloud BAA); OpenAI and Anthropic offer a BAA only for listed endpoints and an account arrangement (a provisioned retention arrangement such as Modified Retention on OpenAI, a HIPAA-enabled organization on Anthropic). A SOC 2 Type II report is evidence about the vendor's controls, useful for risk review, but it is neither a BAA nor a licence for your use. Check the current endpoint and feature lists before routing PHI anywhere (verify on the providers' pages: these lists change).
Further resources#
- OpenAI, "Conversation state":
previous_response_id, the Conversations API and retention, from the source. - OpenAI, Responses API reference and Conversations API reference: every parameter used in Part 7.
- OpenAI, "Reasoning" and "Compaction" guides: encrypted reasoning,
reasoning.context, and compaction. - OpenAI, Model Spec: the chain of command behind
developerandsystem. - Anthropic, "Working with the Messages API", "Mid-conversation system messages" and "Message threads".
- Anthropic, "Migrating to API version 2026-10-21": the removed parameters and new message-shape errors.
- Google, "Interactions API overview" and create-interaction reference: steps, server-side state and retention.
- Anthropic, "Compaction" (and its on-demand and threshold pages) and "Context editing": the beta server-side ways to shrink a long conversation.
- OpenAI, "Data controls in the OpenAI platform" and Google, Gemini API additional terms: what is logged and retained beyond the objects you can delete.
- Compliance (10.5): OpenAI's HIPAA guide, Anthropic's API and data retention page and Google Cloud's HIPAA compliance page: the vendor-side wording to check before routing PHI.
- Google, "Thought signatures" and "What's new in Gemini 3.6" (prefill validation and sampling deprecation).
- OpenRouter, API overview and Responses API overview: roles, prefill support and the stateless Responses endpoint.
- google-genai
chats.py: the curated-history logic, short and worth reading.
← 03.1 — The Provider APIs and Your First Calls | Module 03 overview | 03.3 — Streaming Responses →