mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-04 13:49:43 +08:00
fix(llm): reuse multi-turn prefixes with explicit GPT-5.6 cache breakpoints
This commit is contained in:
@@ -9,12 +9,14 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
import hashlib
|
||||
import inspect
|
||||
import re
|
||||
import secrets
|
||||
import string
|
||||
import sys
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import json_repair
|
||||
from loguru import logger
|
||||
@@ -36,7 +38,9 @@ from deeptutor.services.llm.provider_core.openai_responses import (
|
||||
convert_messages,
|
||||
convert_tool_choice,
|
||||
convert_tools,
|
||||
mark_stable_history_breakpoint,
|
||||
parse_response_output,
|
||||
supports_explicit_prompt_cache,
|
||||
)
|
||||
from deeptutor.services.llm.reasoning_params import (
|
||||
build_openai_compatible_reasoning_kwargs,
|
||||
@@ -241,9 +245,17 @@ class OpenAICompatProvider(LLMProvider):
|
||||
sdk_max_retries=0,
|
||||
)
|
||||
)
|
||||
try:
|
||||
self._prompt_cache_options_supported = (
|
||||
"prompt_cache_options"
|
||||
in inspect.signature(self._client.responses.create).parameters
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
self._prompt_cache_options_supported = False
|
||||
self._responses_failures: dict[str, int] = {}
|
||||
self._responses_tripped_at: dict[str, float] = {}
|
||||
self._responses_without_message_status_models: set[str] = set()
|
||||
self._responses_without_prompt_cache_models: set[str] = set()
|
||||
|
||||
@staticmethod
|
||||
def _status_code(exc: Exception) -> int | None:
|
||||
@@ -675,6 +687,51 @@ class OpenAICompatProvider(LLMProvider):
|
||||
sanitized_items.append(item)
|
||||
return {**body, "input": sanitized_items} if has_status else None
|
||||
|
||||
@staticmethod
|
||||
def _responses_body_without_prompt_cache(body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Strip explicit-cache fields for a provider that rejected them."""
|
||||
|
||||
sanitized = {key: value for key, value in body.items() if key != "prompt_cache_options"}
|
||||
input_items = body.get("input")
|
||||
if not isinstance(input_items, list):
|
||||
return sanitized
|
||||
cleaned_items: list[Any] = []
|
||||
for item in input_items:
|
||||
if not isinstance(item, dict):
|
||||
cleaned_items.append(item)
|
||||
continue
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list):
|
||||
cleaned_items.append(item)
|
||||
continue
|
||||
cleaned_content = []
|
||||
for block in content:
|
||||
if isinstance(block, dict) and "prompt_cache_breakpoint" in block:
|
||||
cleaned_content.append(
|
||||
{
|
||||
key: value
|
||||
for key, value in block.items()
|
||||
if key != "prompt_cache_breakpoint"
|
||||
}
|
||||
)
|
||||
else:
|
||||
cleaned_content.append(block)
|
||||
cleaned_items.append({**item, "content": cleaned_content})
|
||||
return {**sanitized, "input": cleaned_items}
|
||||
|
||||
@classmethod
|
||||
def _is_prompt_cache_rejection(cls, exc: Exception) -> bool:
|
||||
status_code = cls._status_code(exc)
|
||||
if status_code not in {400, 422}:
|
||||
return False
|
||||
response = getattr(exc, "response", None)
|
||||
body = (
|
||||
getattr(exc, "body", None)
|
||||
or getattr(exc, "doc", None)
|
||||
or (getattr(response, "text", None) if response is not None else None)
|
||||
)
|
||||
return "prompt_cache" in str(body).lower()
|
||||
|
||||
async def _create_responses_with_status_retry(
|
||||
self,
|
||||
body: dict[str, Any],
|
||||
@@ -686,6 +743,8 @@ class OpenAICompatProvider(LLMProvider):
|
||||
try:
|
||||
return await self._create_with_key_rotation(self._client.responses.create, request_body)
|
||||
except Exception as exc:
|
||||
if self._is_prompt_cache_rejection(exc):
|
||||
return await self._retry_without_prompt_cache(model_name, request_body)
|
||||
item_index = self._rejected_input_item_status_index(exc)
|
||||
if item_index is None:
|
||||
raise
|
||||
@@ -693,7 +752,21 @@ class OpenAICompatProvider(LLMProvider):
|
||||
if retry_body is None:
|
||||
raise
|
||||
self._responses_without_message_status_models.add(model_name)
|
||||
return await self._create_with_key_rotation(self._client.responses.create, retry_body)
|
||||
try:
|
||||
return await self._create_with_key_rotation(
|
||||
self._client.responses.create, retry_body
|
||||
)
|
||||
except Exception as retry_exc:
|
||||
if not self._is_prompt_cache_rejection(retry_exc):
|
||||
raise
|
||||
return await self._retry_without_prompt_cache(model_name, retry_body)
|
||||
|
||||
async def _retry_without_prompt_cache(self, model_name: str, body: dict[str, Any]) -> Any:
|
||||
"""Retry once without explicit cache fields and remember the refusal."""
|
||||
|
||||
self._responses_without_prompt_cache_models.add(model_name)
|
||||
fallback = self._responses_body_without_prompt_cache(body)
|
||||
return await self._create_with_key_rotation(self._client.responses.create, fallback)
|
||||
|
||||
@staticmethod
|
||||
def _should_fallback_from_responses_error(exc: Exception) -> bool:
|
||||
@@ -791,6 +864,28 @@ class OpenAICompatProvider(LLMProvider):
|
||||
disable_forced_tool_choice_at_runtime(self._binding_name(), target)
|
||||
return True
|
||||
|
||||
def _supports_explicit_prompt_cache(self, model_name: str) -> bool:
|
||||
"""Gate explicit breakpoints to native OpenAI GPT-5.6+.
|
||||
|
||||
Other OpenAI-compatible endpoints often reject unknown fields, so the
|
||||
marker stays off unless the binding is the official endpoint (or a
|
||||
custom binding pointed at it).
|
||||
"""
|
||||
if not supports_explicit_prompt_cache(model_name):
|
||||
return False
|
||||
if not self._prompt_cache_options_supported:
|
||||
return False
|
||||
if str(model_name or "").strip().lower() in self._responses_without_prompt_cache_models:
|
||||
return False
|
||||
spec_name = str(getattr(self._spec, "name", "") or "").lower()
|
||||
if spec_name == "openai":
|
||||
return True
|
||||
try:
|
||||
host = (urlsplit(self._effective_base or "").hostname or "").lower()
|
||||
except ValueError:
|
||||
return False
|
||||
return host == "api.openai.com"
|
||||
|
||||
def _build_responses_body(
|
||||
self,
|
||||
messages: list[dict[str, Any]],
|
||||
@@ -816,6 +911,13 @@ class OpenAICompatProvider(LLMProvider):
|
||||
"store": False,
|
||||
"stream": False,
|
||||
}
|
||||
if self._supports_explicit_prompt_cache(model_name):
|
||||
if mark_stable_history_breakpoint(input_items):
|
||||
# Explicit-only mode: the breakpoint above is the reusable
|
||||
# prefix. Last-turn assistant text and tool output stay
|
||||
# uncached but small; the next turn matches everything before
|
||||
# the trailing runtime snapshot (#2297).
|
||||
body["prompt_cache_options"] = {"mode": "explicit", "ttl": "30m"}
|
||||
|
||||
if self._supports_temperature(model_name, reasoning_effort):
|
||||
body["temperature"] = temperature
|
||||
|
||||
@@ -6,7 +6,9 @@ from .converters import (
|
||||
convert_tool_choice,
|
||||
convert_tools,
|
||||
convert_user_message,
|
||||
mark_stable_history_breakpoint,
|
||||
split_tool_call_id,
|
||||
supports_explicit_prompt_cache,
|
||||
)
|
||||
from .parsing import (
|
||||
FINISH_REASON_MAP,
|
||||
@@ -24,6 +26,8 @@ __all__ = [
|
||||
"convert_tool_choice",
|
||||
"convert_tools",
|
||||
"convert_user_message",
|
||||
"mark_stable_history_breakpoint",
|
||||
"supports_explicit_prompt_cache",
|
||||
"split_tool_call_id",
|
||||
"iter_sse",
|
||||
"consume_sse",
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from deeptutor.services.session.provider_response_state import (
|
||||
@@ -79,6 +80,72 @@ def convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str
|
||||
return system_prompt, input_items
|
||||
|
||||
|
||||
# GPT-5.6 introduced explicit cache breakpoints in the Responses API.
|
||||
_EXPLICIT_CACHE_MODEL = re.compile(r"^gpt-(\d+)(?:\.(\d+))?")
|
||||
|
||||
|
||||
def supports_explicit_prompt_cache(model: str | None) -> bool:
|
||||
"""Whether *model* accepts ``prompt_cache_options``/breakpoints."""
|
||||
name = str(model or "").strip().lower().rsplit("/", 1)[-1]
|
||||
match = _EXPLICIT_CACHE_MODEL.match(name)
|
||||
if match is None:
|
||||
return False
|
||||
major = int(match.group(1))
|
||||
minor = int(match.group(2) or 0)
|
||||
return (major, minor) >= (5, 6)
|
||||
|
||||
|
||||
# Responses allows four cache writes per request. A sliding window of the
|
||||
# last four durable user messages keeps the previous turn's newest breakpoint
|
||||
# present in the next request, so the lookup can match the cache entry it just
|
||||
# wrote instead of only the newest (still uncached) boundary.
|
||||
_EXPLICIT_CACHE_BREAKPOINTS = 4
|
||||
|
||||
|
||||
def mark_stable_history_breakpoint(input_items: list[dict[str, Any]]) -> bool:
|
||||
"""Place explicit cache breakpoints before the trailing user block.
|
||||
|
||||
The answer loop appends the current runtime snapshot and the learner's
|
||||
message as consecutive ``user`` items. Everything before them is durable,
|
||||
but the last durable item is usually the assistant reply, whose
|
||||
``output_text`` block cannot carry ``prompt_cache_breakpoint``. Step back
|
||||
to durable user messages: their ``input_text`` blocks are supported
|
||||
breakpoints and the next turn's prefix still matches.
|
||||
|
||||
Marking a sliding window (not just the newest message) is what makes the
|
||||
previous turn's cache entry discoverable: the new request must still
|
||||
contain the breakpoint boundary that the old request wrote.
|
||||
"""
|
||||
|
||||
last_user = None
|
||||
for index, item in enumerate(input_items):
|
||||
if item.get("role") == "user":
|
||||
last_user = index
|
||||
if last_user is None:
|
||||
return False
|
||||
|
||||
start = last_user
|
||||
while start > 0 and input_items[start - 1].get("role") == "user":
|
||||
start -= 1
|
||||
|
||||
marked = 0
|
||||
for index in range(start - 1, -1, -1):
|
||||
if marked >= _EXPLICIT_CACHE_BREAKPOINTS:
|
||||
break
|
||||
item = input_items[index]
|
||||
if item.get("role") != "user":
|
||||
continue
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for block in reversed(content):
|
||||
if block.get("type") == "input_text" and block.get("text"):
|
||||
block["prompt_cache_breakpoint"] = {"mode": "explicit"}
|
||||
marked += 1
|
||||
break
|
||||
return marked > 0
|
||||
|
||||
|
||||
def convert_user_message(content: Any) -> dict[str, Any]:
|
||||
"""Convert user message content to Responses API blocks."""
|
||||
if isinstance(content, str):
|
||||
|
||||
168
tests/services/llm/test_responses_prompt_cache.py
Normal file
168
tests/services/llm/test_responses_prompt_cache.py
Normal file
@@ -0,0 +1,168 @@
|
||||
"""Explicit prompt-cache breakpoints for GPT-5.6+ on the native Responses API.
|
||||
|
||||
The answer loop appends the runtime snapshot and the learner's message as
|
||||
consecutive user items. GPT-5.6+ implicit caching only writes a breakpoint at
|
||||
the end of the latest eligible message, so that trailing block never matches
|
||||
the previous turn. One explicit breakpoint before the trailing block makes the
|
||||
durable history reusable again (#2297).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProvider
|
||||
from deeptutor.services.llm.provider_core.openai_responses import (
|
||||
mark_stable_history_breakpoint,
|
||||
supports_explicit_prompt_cache,
|
||||
)
|
||||
from deeptutor.services.provider_registry import find_by_name
|
||||
|
||||
_MESSAGES: list[dict[str, Any]] = [
|
||||
{"role": "system", "content": "You are DeepTutor."},
|
||||
{"role": "user", "content": "First question"},
|
||||
{"role": "assistant", "content": "First answer"},
|
||||
{"role": "user", "content": "[Runtime context: workspace]\nCurrent turn"},
|
||||
{"role": "user", "content": "Second question"},
|
||||
]
|
||||
|
||||
|
||||
def _provider(spec_name: str, base_url: str, model: str) -> OpenAICompatProvider:
|
||||
return OpenAICompatProvider(
|
||||
api_key="test-key",
|
||||
api_base=base_url,
|
||||
default_model=model,
|
||||
spec=find_by_name(spec_name),
|
||||
provider_name=spec_name,
|
||||
)
|
||||
|
||||
|
||||
def _body(provider: OpenAICompatProvider, model: str) -> dict[str, Any]:
|
||||
return provider._build_responses_body(_MESSAGES, None, model, 256, 0.7, None, None)
|
||||
|
||||
|
||||
def test_gpt_6_marks_the_last_durable_user_message() -> None:
|
||||
provider = _provider("openai", "https://api.openai.com/v1", "gpt-6.1-terra")
|
||||
|
||||
body = _body(provider, "gpt-6.1-terra")
|
||||
|
||||
assert body["prompt_cache_options"] == {"mode": "explicit", "ttl": "30m"}
|
||||
items = body["input"]
|
||||
first_user = next(
|
||||
item for item in items if item.get("content", [{}])[0].get("text") == "First question"
|
||||
)
|
||||
assert first_user["content"][0]["prompt_cache_breakpoint"] == {"mode": "explicit"}
|
||||
# The transient snapshot and the current message stay outside the breakpoint.
|
||||
trailing = [item for item in items if item is not first_user and item.get("role") == "user"]
|
||||
assert all(
|
||||
"prompt_cache_breakpoint" not in block
|
||||
for item in trailing
|
||||
for block in item.get("content", [])
|
||||
)
|
||||
|
||||
|
||||
def test_breakpoint_window_keeps_the_previous_turn_discoverable() -> None:
|
||||
provider = _provider("openai", "https://api.openai.com/v1", "gpt-6.1-terra")
|
||||
messages: list[dict[str, Any]] = [{"role": "system", "content": "You are DeepTutor."}]
|
||||
for index in range(6):
|
||||
messages.append({"role": "user", "content": f"question {index}"})
|
||||
messages.append({"role": "assistant", "content": f"answer {index}"})
|
||||
messages.append({"role": "user", "content": "[Runtime context: workspace]\nsnapshot"})
|
||||
messages.append({"role": "user", "content": "current"})
|
||||
|
||||
body = provider._build_responses_body(messages, None, "gpt-6.1-terra", 256, 0.7, None, None)
|
||||
|
||||
marked = {
|
||||
block["text"]
|
||||
for item in body["input"]
|
||||
for block in item.get("content", [])
|
||||
if "prompt_cache_breakpoint" in block
|
||||
}
|
||||
assert marked == {"question 2", "question 3", "question 4", "question 5"}
|
||||
|
||||
|
||||
def test_older_model_keeps_implicit_caching() -> None:
|
||||
provider = _provider("openai", "https://api.openai.com/v1", "gpt-5.5")
|
||||
|
||||
body = _body(provider, "gpt-5.5")
|
||||
|
||||
assert "prompt_cache_options" not in body
|
||||
|
||||
|
||||
def test_non_openai_endpoint_keeps_implicit_caching() -> None:
|
||||
provider = _provider("deepseek", "https://api.deepseek.com", "gpt-6.1-terra")
|
||||
|
||||
body = _body(provider, "gpt-6.1-terra")
|
||||
|
||||
assert "prompt_cache_options" not in body
|
||||
|
||||
|
||||
def test_first_turn_keeps_implicit_caching() -> None:
|
||||
provider = _provider("openai", "https://api.openai.com/v1", "gpt-6.1-terra")
|
||||
messages = [
|
||||
{"role": "system", "content": "You are DeepTutor."},
|
||||
{"role": "user", "content": "Only question"},
|
||||
]
|
||||
|
||||
body = provider._build_responses_body(messages, None, "gpt-6.1-terra", 256, 0.7, None, None)
|
||||
|
||||
assert "prompt_cache_options" not in body
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_prompt_cache_rejection_retries_without_the_fields(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
provider = _provider("openai", "https://api.openai.com/v1", "gpt-6.1-terra")
|
||||
body = _body(provider, "gpt-6.1-terra")
|
||||
seen: list[dict[str, Any]] = []
|
||||
|
||||
class Rejected(Exception):
|
||||
status_code = 400
|
||||
body = {"error": {"message": "Unknown parameter: prompt_cache_options"}}
|
||||
|
||||
async def fake_create(_create: Any, request_body: dict[str, Any]) -> Any:
|
||||
seen.append(request_body)
|
||||
if len(seen) == 1:
|
||||
raise Rejected()
|
||||
return {"ok": True}
|
||||
|
||||
monkeypatch.setattr(provider, "_create_with_key_rotation", fake_create)
|
||||
|
||||
assert await provider._create_responses_with_status_retry(body) == {"ok": True}
|
||||
assert "prompt_cache_options" not in seen[1]
|
||||
assert all(
|
||||
"prompt_cache_breakpoint" not in block
|
||||
for item in seen[1]["input"]
|
||||
for block in item.get("content", [])
|
||||
)
|
||||
assert provider._supports_explicit_prompt_cache("gpt-6.1-terra") is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model", "expected"),
|
||||
[
|
||||
("gpt-5.6", True),
|
||||
("gpt-5.6-codex", True),
|
||||
("gpt-6", True),
|
||||
("openai/gpt-6.1-terra", True),
|
||||
("gpt-5.5", False),
|
||||
("gpt-5.1-codex", False),
|
||||
("claude-sonnet-4", False),
|
||||
("", False),
|
||||
],
|
||||
)
|
||||
def test_explicit_cache_model_gate(model: str, expected: bool) -> None:
|
||||
assert supports_explicit_prompt_cache(model) is expected
|
||||
|
||||
|
||||
def test_breakpoint_requires_a_durable_user_message() -> None:
|
||||
assert mark_stable_history_breakpoint([]) is False
|
||||
assert (
|
||||
mark_stable_history_breakpoint(
|
||||
[{"role": "user", "content": [{"type": "input_text", "text": "only"}]}]
|
||||
)
|
||||
is False
|
||||
)
|
||||
Reference in New Issue
Block a user