Prompt cache: a mid-conversation system message that ends a request after a user message is not read back on the next turn

Aperta
#2,080 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
45/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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_control on 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_control aside). 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 say messages_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_011ChNre722mC2J3MEc4LjPj ends with a system message after a tool_result: [user, assistant (thinking, text, tool_use), user (tool_result), SYSTEM (one tool_addition by value)]. Prompt: 5,983 tokens.
  • req_011ChNreAbbPUfLkwoqJVzcu is 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:

  1. What comes before the system message: a tool_result here, a user text message in the failing cases.
  2. What follows it on the next request: a tool_use here, an assistant text reply in the failing cases.
  3. This pair sent thinking: {"type": "adaptive"}, output_config.effort: "high" and thinking-binding-controls-2026-08-01. The failing cases sent no thinking setting.
  4. 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

  1. 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.
  2. 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()
Lingua principale
Python
Stelle
4.1k
Fork
915
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di anthropics/anthropic-sdk-python

Tutte le issue di anthropics/anthropic-sdk-python

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.