Files
DeepTutor/deeptutor/runtime/agentic/prompt_caching.py
greenhand-fjm a943eb0b1e fix(runtime): add gateway cache breakpoints to the tool loops (#3115)
The research, question and page-index loops (run_labeled_step) and the context explorer call the SDK client directly, so an anthropic/ model on OpenRouter got no cache_control breakpoint and cached nothing on any round. Move the chat loop's check into runtime/agentic/prompt_caching.py and apply it in all three places. Refs #3087.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01J2vr2J41oqPYhmpP8CzSJA
2026-12-01 21:38:18 +08:00

64 lines
2.3 KiB
Python

"""Prompt-caching breakpoints for loops that call the SDK client directly.
Every agentic loop builds its own ``chat.completions.create`` kwargs and calls
the SDK client itself, so none of them pass through
``OpenAICompatProvider._build_kwargs``, the provider path that adds Anthropic
``cache_control`` breakpoints. An ``anthropic/`` model on a prompt-caching
gateway (OpenRouter) caches a prefix only at such a breakpoint, so without
this helper each round of a tool loop pays the full input rate for the system
prompt, the tool schemas and every earlier round (#3087).
"""
from __future__ import annotations
from typing import Any
def binding_marks_cache_in_loop(binding: str | None) -> bool:
"""Whether a loop must add the breakpoints itself for *binding*.
Only OpenAI-compatible bindings that support prompt caching need it. Native
Anthropic-backed bindings apply their own ``cache_control`` inside their
provider, so marking those requests here would stack a second set of
breakpoints on top.
"""
if not binding:
return False
from deeptutor.services.provider_registry import find_by_name
spec = find_by_name(binding)
if spec is None or not spec.supports_prompt_caching:
return False
return spec.backend == "openai_compat"
def apply_gateway_prompt_caching(
kwargs: dict[str, Any],
binding: str | None,
*,
stable_history_end: bool = False,
) -> None:
"""Add ``cache_control`` breakpoints to *kwargs* in place when needed.
Reuses the provider's helper so the loops and the provider mark requests
the same way. ``stable_history_end`` also marks the end of the durable
history, for the chat loop, whose transient per-turn context message would
otherwise make the next turn's prefix diverge.
"""
from deeptutor.services.llm.provider_core.openai_compat_provider import (
OpenAICompatProvider,
)
if not OpenAICompatProvider.supports_prompt_caching_for(str(kwargs.get("model") or "")):
return
if not binding_marks_cache_in_loop(binding):
return
messages, tools = OpenAICompatProvider._apply_cache_control(
kwargs["messages"],
kwargs.get("tools"),
stable_history_end=stable_history_end,
)
kwargs["messages"] = messages
if tools is not None:
kwargs["tools"] = tools