Prompt cache: a mid-conversation system message that ends a request after a user message is not read back on the next turn
まだ誰も着手していません。
評価
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 初心者へのやさしさ
- 45/100
- issue の種類
- バグ
- 明瞭さ
- 明確に書かれている
- 活発さ
- 活発
- 技術スタック
- python
調査の方向性
Start with the supplied repro.py and run its --dry-run option to inspect the three request shapes; then run the text and tools cases against the Messages API and compare turn 3 cache usage and diagnostics. The issue reports a reproducible mismatch for mid-conversation system messages, but has not isolated which request-shape difference causes it. Done means identifying whether the behavior comes from SDK request handling or the API and documenting a verified explanation or reproduction.
索引モデルが issue の本文から書いたものです。
説明
Model: claude-sonnet-5-5 on the Claude API, anthropic-version: 2023-06-01, non-streaming
When: 2026-11-25, 18:28 to 19:05 UTC, one run per case
Impact: cost and a little latency, no errors. An agent that adds tools at the start of each turn this way pays, on every later turn, to write the turn before's tool changes again (about 15,700 tokens a turn in our app).
Expected
From Mid-conversation system messages, § Combining with prompt caching:
A mid-conversation system message is itself cacheable. Once it is in the conversation, it becomes part of the stable history. On the next turn you can move your cache breakpoint past it (or rely on automatic caching to do so) and the system message is read from cache like any other turn.
Shape
- Turn 1:
[user text] - Turn 2:
[user, assistant text, user text, SYSTEM]. The system message is the last message. - Turn 3: turn 2's messages unchanged, then
[assistant text, user text, SYSTEM].
Cache marks: cache_control on the last tool definition, on the user message where the turn before began, on this turn's user message, and top-level automatic caching (4 breakpoints). The requests were seconds apart.
Observed
In every case turn 2 read all of turn 1, and its diagnostics were null. Turn 3 read only through turn 2's second user message, then wrote turn 2's system message again.
| Case | Turn 2's system message | Turn 2 request / prompt tokens | Turn 3 request / cache read | Short by | Turn 3 diagnostics |
|---|---|---|---|---|---|
| A | 20 tool_addition by value + 20 tool_removal |
req_011ChQ7uVnQur2MohPxo9ZL4 / 14,901 |
req_011ChQ7ubBcTP32ax3tqEM91 / 9,374 |
5,527 | not requested |
| C | as A | req_011ChQ99UznpiHW889zwVkP5 / 14,888 |
req_011ChQ99ZKzdFxciQTWQiFJC / 9,361 |
5,527 | messages_changed, 6,658 |
| D | 20 tool_addition by value, no removals |
req_011ChQARgnGZHro1eHj3F6fy / 14,810 |
req_011ChQARo2a3MxDqCxVh2JvG / 9,384 |
5,426 | messages_changed, 6,594 |
| G | tools declared with defer_loading, added by tool_reference |
req_011ChQAYjdNsHvuJB6bGfJ1y / 15,002 |
req_011ChQAYr5KkQED8t7cg99mB / 9,475 |
5,527 | messages_changed, 6,785 |
| H | one plain text block, no tool changes |
req_011ChQAa5ZxbR7mvJw91VecG / 12,752 |
req_011ChQAaHyKpUJh9e8bUp5pn / 9,368 |
3,384 | messages_changed, 4,082 |
| I | as H; turn 3 also marks the exact block turn 2 ended on | req_011ChQAfXGBD9kzc5FB8B2yj / 12,765 |
req_011ChQAfoFbVkf41DnmTmgY5 / 9,381 |
3,384 | messages_changed, 4,098 |
"Prompt tokens" is input_tokens + cache_read_input_tokens + cache_creation_input_tokens. Cases A, C, D and G sent inline-tools-2026-09-15. C to I sent cache-diagnosis-2026-04-07 with a diagnostics object on every request. The beta header set was the same on turn 2 and turn 3 in every case.
What we ruled out
- The system message's content. Tool changes by value, by reference, with and without removals, and a single plain text block all miss the same way.
- Breakpoint placement and the 20-block lookback. Turn 2 left 2 input tokens uncached, so its automatic breakpoint wrote an entry covering the whole system message. In case I, turn 3 put
cache_controlon that same block and still read only through the user message before it. So the entry exists, but turn 3's prefix hash at the same block does not match it. - An edit to the history. Turn 3's messages are turn 2's messages byte for byte (
cache_controlaside). In cases A and C, turn 2's reply had no thinking block, so turn 3 sent it back exactly as the API returned it. In cases D, G, H and I, turn 2's reply did have a thinking block, and we sent the reply back as its text only. Model, system and tools were identical across the turns. The diagnostics still saymessages_changed, which the cache diagnostics page defines as "an earlier entry in messages was altered, reordered, or removed rather than appended to".
The shape that does read back
From an earlier probe on 2026-11-24, same model and API version, automatic caching only:
req_011ChNre722mC2J3MEc4LjPjends with a system message after atool_result:[user, assistant (thinking, text, tool_use), user (tool_result), SYSTEM (one tool_addition by value)]. Prompt: 5,983 tokens.req_011ChNreAbbPUfLkwoqJVzcuis that request plus[assistant (tool_use), user (tool_result), SYSTEM (one tool_removal)]. It read 5,981 tokens, all of the earlier request.
Between this pair and the failing cases, four things differ:
- What comes before the system message: a
tool_resulthere, a user text message in the failing cases. - What follows it on the next request: a
tool_usehere, an assistant text reply in the failing cases. - This pair sent
thinking: {"type": "adaptive"},output_config.effort: "high"andthinking-binding-controls-2026-08-01. The failing cases sent no thinking setting. - This pair used automatic caching only. The failing cases also used block-level marks.
We have not isolated which of the four matters.
Not tested
Models other than claude-sonnet-5-5; anthropic-version: 2026-10-21; streaming; Amazon Bedrock or Google Cloud; a system message after a tool_result that is followed by a new user turn.
How our requests were sent
Our requests went through our app's local pass-through to POST /v1/messages. By our reading of its code, it parses the body and writes it out again with its keys sorted, replaces the model name and sets "stream": false. It changes no message, no cache_control and no header we sent (anthropic-version and anthropic-beta included), and the same input always gives the same bytes. The repro below (repro.py) calls the API directly with the official Python SDK, using the same tools, words and marks as cases H (--shape text) and C (--shape tools). It reads the API key from the environment, prints usage and diagnostics for each turn, and ends with a PASS or MISS verdict. --dry-run builds and checks the three requests without sending them.
pip install anthropic
python3 repro.py # case H's shape
python3 repro.py --shape tools # case C's shape
python3 repro.py --api-version 2026-10-21
Questions
- Is this expected? If it is, could the page say which shapes are read back on the next turn? As written, it says every mid-conversation system message is.
- If it is not expected: is there a shape we can use now that keeps a turn's added tools in the cached history for the next turn?
repro.py
"""Repro: a mid-conversation system message that ends a request right after a user text message is not
read back from the prompt cache on the next turn.
Three turns of one conversation on the Messages API, with made-up tools and words:
turn 1: [user]
turn 2: [user, assistant, user, SYSTEM] (the SYSTEM message is the last message)
turn 3: turn 2's messages unchanged, then [assistant, user, SYSTEM]
Expected (Mid-conversation system messages, "Combining with prompt caching"): turn 3 reads all of turn 2's
prompt from cache, including turn 2's system message. Observed on claude-sonnet-5-5: turn 3 reads only up
to turn 2's second user message and writes turn 2's system message again; cache diagnostics on turn 3
report messages_changed.
Cache marks, as in the requests we observed: the last tool definition, the user message where the turn before
began, this turn's user message, and top-level automatic caching (4 breakpoints at most).
--shape text (default) the system messages are plain text; no tool-change beta.
--shape tools the system messages add 20 tools by value (tool_addition) and withdraw 20 (tool_removal),
with inline-tools-2026-09-15 on all three requests.
--api-version the anthropic-version header (default 2023-06-01, the version the observed requests used;
the installed SDK may default to a newer one).
--text-only-replies send each assistant reply back as its text blocks only, as our observed requests did.
By default each reply goes back exactly as the API returned it, thinking blocks included.
--dry-run build the three requests, check that turn 3 begins with turn 2's messages, print them, and
send nothing.
The API key is read from the environment by the SDK (ANTHROPIC_API_KEY or another credential the SDK
resolves). Every request carries cache-diagnosis-2026-04-07 and a diagnostics object. The beta header set is
the same on all three requests. Each run uses a fresh nonce in the system prompt, so no earlier run's cache
is read. One run costs about 0.05 USD on claude-sonnet-5-5 with --shape text, about 0.08 USD with --shape tools.
Requires: pip install anthropic
"""
import argparse
import copy
import json
import sys
import time
import anthropic
DIAGNOSIS = "cache-diagnosis-2026-04-07"
INLINE_TOOLS = "inline-tools-2026-09-15"
MARK = {"type": "ephemeral"}
SUFFIX = " Do not call any tool. Reply with one short line naming the single tool you would use."
def tool(name, i):
desc = ("Probe tool %s. It handles the %s task for a record and reports what it did. " % (name, name.replace("_", " "))
+ " ".join("Rule %d for %s: read the record first, change nothing else, and say what changed." % (k, name)
for k in range(1, 7)))
return {"name": name, "description": desc,
"input_schema": {"type": "object",
"properties": {"record": {"type": "string", "description": "The record %d names." % i}},
"required": ["record"]}}
FIRST = [tool("first_%02d" % i, i) for i in range(30)]
TURN2 = [tool("second_%02d" % i, 100 + i) for i in range(20)]
TURN3 = [tool("third_%02d" % i, 200 + i) for i in range(20)]
GONE2 = ["first_%02d" % i for i in range(10, 30)]
GONE3 = ["first_%02d" % i for i in range(0, 10)] + ["second_%02d" % i for i in range(10, 20)]
def system_prompt(nonce):
return ("You are a careful assistant with tools. Conversation %s.\n" % nonce
+ "\n".join("Guideline %d: answer plainly and name the tool that fits." % i for i in range(1, 41)))
def text_note(word):
return {"role": "system", "content": [{"type": "text", "text": "\n".join(
"Note %s %d: when the record is %s, read it first, change nothing else, and say what changed. " % (word, i, word)
+ " ".join("Rule %d of note %d: keep the answer short and name the tool." % (k, i) for k in range(1, 7))
for i in range(20))}]}
def tool_change(added, removed):
return {"role": "system", "content": [
{"type": "tool_addition", "tool": {"type": "tool_definition", "definition": t}} for t in added
] + [{"type": "tool_removal", "tool": {"type": "tool_reference", "name": n}} for n in removed]}
def user(text, marked=False):
block = {"type": "text", "text": text}
if marked:
block["cache_control"] = MARK
return {"role": "user", "content": [block]}
def tools_with_mark():
rows = copy.deepcopy(FIRST)
rows[-1]["cache_control"] = MARK
return rows
def reply(message, text_only):
blocks = [b.model_dump(exclude_none=True) for b in message.content]
if text_only:
blocks = [{"type": "text", "text": b["text"]} for b in blocks if b["type"] == "text"]
return {"role": "assistant", "content": blocks or [{"type": "text", "text": "ok"}]}
def unmarked(value):
if isinstance(value, dict):
return {k: unmarked(v) for k, v in value.items() if k != "cache_control"}
if isinstance(value, list):
return [unmarked(v) for v in value]
return value
def total(usage):
return (usage.input_tokens or 0) + (usage.cache_read_input_tokens or 0) + (usage.cache_creation_input_tokens or 0)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="claude-sonnet-5-5")
ap.add_argument("--shape", choices=["text", "tools"], default="text")
ap.add_argument("--api-version", default="2023-06-01")
ap.add_argument("--text-only-replies", action="store_true")
ap.add_argument("--dry-run", action="store_true")
args = ap.parse_args()
nonce = "%s-%d" % (args.shape, int(time.time()))
betas = [DIAGNOSIS] + ([INLINE_TOOLS] if args.shape == "tools" else [])
w1, w2, w3 = ("Which tool reads a record?" + SUFFIX, "Which tool files a record?" + SUFFIX,
"Which tool archives a record?" + SUFFIX)
if args.shape == "tools":
said2, said3 = tool_change(TURN2, GONE2), tool_change(TURN3, GONE3)
else:
said2, said3 = text_note("filed"), text_note("archived")
client = None if args.dry_run else anthropic.Anthropic(default_headers={"anthropic-version": args.api_version})
print(json.dumps({"model": args.model, "shape": args.shape, "anthropic-version": args.api_version,
"anthropic-beta": betas, "sdk": anthropic.__version__, "textOnlyReplies": args.text_only_replies,
"nonce": nonce}))
def send(turn, messages, previous_id):
params = dict(model=args.model, max_tokens=1024, system=system_prompt(nonce), tools=tools_with_mark(),
messages=messages, cache_control=MARK, betas=betas,
diagnostics={"previous_message_id": previous_id})
if args.dry_run:
print(json.dumps({"turn": turn, "request": params}))
return None
try:
message = client.beta.messages.create(**params)
except anthropic.APIStatusError as e:
sys.exit("turn %d failed: HTTP %s, request-id %s: %s" % (turn, e.status_code, e.request_id, e.message))
except anthropic.APIConnectionError as e:
sys.exit("turn %d failed: no connection: %s" % (turn, e))
u = message.usage
print(json.dumps({"turn": turn, "requestId": message._request_id, "messageId": message.id,
"stop": message.stop_reason, "blocks": [b.type for b in message.content],
"usage": {"input_tokens": u.input_tokens, "cache_read_input_tokens": u.cache_read_input_tokens,
"cache_creation_input_tokens": u.cache_creation_input_tokens,
"output_tokens": u.output_tokens, "total_prompt": total(u)},
"diagnostics": message.diagnostics.model_dump() if message.diagnostics else None}))
if message.stop_reason != "end_turn":
sys.exit("turn %d stopped with %s, not end_turn, so the next turn cannot be built; run again" % (turn, message.stop_reason))
return message
placeholder = {"role": "assistant", "content": [{"type": "text", "text": "first_00"}]}
m1 = send(1, [user(w1, marked=True)], None)
a1 = reply(m1, args.text_only_replies) if m1 else placeholder
turn2 = [user(w1, marked=True), a1, user(w2, marked=True), said2]
m2 = send(2, turn2, m1.id if m1 else None)
a2 = reply(m2, args.text_only_replies) if m2 else placeholder
turn3 = [user(w1), a1, user(w2, marked=True), said2, a2, user(w3, marked=True), said3]
if unmarked(turn3[:len(turn2)]) != unmarked(turn2):
sys.exit("BUG in this script: turn 3 does not begin with turn 2's messages")
m3 = send(3, turn3, m2.id if m2 else None)
if args.dry_run:
print(json.dumps({"check": "turn 3 begins with turn 2's messages (cache_control aside)", "ok": True}))
return
sent2, read3 = total(m2.usage), m3.usage.cache_read_input_tokens or 0
print(json.dumps({"verdict": "PASS" if read3 >= sent2 - 8 else "MISS", "turn2Prompt": sent2, "turn3Read": read3,
"shortBy": max(0, sent2 - read3),
"expected": "turn 3 reads at least turn 2's whole prompt (a few uncached tail tokens aside)"}))
if __name__ == "__main__":
main()
- 主要言語
- Python
- スター
- 4.1k
- フォーク
- 915
- PR マージ指標
- 30日以内にマージされた PR はありません
環境構築
このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートなし
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
anthropics/anthropic-sdk-python のほかの issue
-
beta_tool validation errors reach the model as "Invalid arguments for function X" with no detail対応中かも @mangeshraut712 が 32 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
anthropics/anthropic-sdk-python#2033 · コメント 3 件 ·
-
`AnthropicBedrock` 2.x sends `anthropic_version: 2026-10-21`, which Bedrock rejects for Claude Sonnet 4.5, Opus 4.5 and Opus 4.6対応中かも @charan-rathore が 36 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 70/100
anthropics/anthropic-sdk-python#2031 · コメント 1 件 ·
-
Three symlink tests in test_agent_toolset.py are missing the needs_symlinks marker対応中かも @okxint が 82 日前に担当しました。 オープン
難易度 1/5 1時間未満 初心者へのやさしさ 92/100
anthropics/anthropic-sdk-python#1915 · コメント 3 件 ·
-
Messages.parse (and AsyncMessages.parse) don't take cache_control?対応中かも @AlphaFDE が 86 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
anthropics/anthropic-sdk-python#1907 · コメント 2 件 ·
-
Windows: os.fchmod in credential write-back bricks the OAuth refresh token対応中かも @OllieinCanada が 98 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
anthropics/anthropic-sdk-python#1868 · コメント 1 件 ·
anthropics/anthropic-sdk-python の issue をすべて見る
似ている issue
-
bug harness
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
mruangutai/harness#2687 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
modal-labs/modal-client#4158 ·
-
good first issue
難易度 1/5 1時間未満 初心者へのやさしさ 72/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 半日 初心者へのやさしさ 72/100
The-Swarm-Corporation/swarms-rs#168 ·
メンテナーはふだん 1 日以内に返信
-
[BUG] SMTP listener now binds to EMAIL_PORT instead of 2525 since the gunicorn switch 5.0.3-ls373オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
linuxserver/docker-healthchecks#137 · コメント 1 件 ·