Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Cache Copilot's Claude prompts (SKY-17680) (#8780)
Andrew Neilsonb81be31e20c9
diff --git a/skyvern/forge/sdk/copilot/cache_envelope.py b/skyvern/forge/sdk/copilot/cache_envelope.pyindex f33022ce4..278e51c6e 100644--- a/skyvern/forge/sdk/copilot/cache_envelope.py+++ b/skyvern/forge/sdk/copilot/cache_envelope.py@@ -5,6 +5,7 @@ import jsonfrom dataclasses import dataclassfrom typing import Any, cast+import litellmfrom agents.handoffs import Handofffrom agents.items import TResponseInputItemfrom agents.model_settings import ModelSettings@@ -12,6 +13,7 @@ from agents.models.chatcmpl_converter import Converter, ShouldReplayReasoningConfrom agents.tool import Toolfrom agents.util._json import _to_dump_compatiblefrom litellm.completion_extras import responses_api_bridge+from litellm.types.llms.openai import ChatCompletionTextObject_DIRECT_OPENAI_GPT56_MODELS = {"gpt-5.6",@@ -22,12 +24,8 @@ _DIRECT_OPENAI_GPT56_MODELS = {class CacheableSystemInstructions(str):- """A behavior-identical system prompt with an explicit stable-prefix seam.-- The Agents SDK still receives a string and therefore sees exactly the same- instructions as before. ``CopilotLitellmModel`` uses the attached parts only- when it builds a direct-OpenAI GPT-5.6 wire request.- """+ """The joined system prompt string, carrying its stable prefix and dynamic suffix so ``CopilotLitellmModel`` can+ cache the prefix: as a GPT Responses envelope, or as two Claude system blocks with the same text."""stable_prefix: strdynamic_suffix: str@@ -111,6 +109,43 @@ def _cache_key(return f"copilot:{digest[:48]}"+def model_chain(model: str, model_settings: ModelSettings) -> list[str]:+ fallbacks: list[str | dict[str, Any]] = (model_settings.extra_args or {}).get("fallbacks") or []+ return [model, *(hop["model"] if isinstance(hop, dict) else hop for hop in fallbacks)]+++def _is_anthropic_model(model: str) -> bool:+ try:+ provider_model, provider, _, _ = litellm.get_llm_provider(model)+ except litellm.exceptions.BadRequestError:+ return False+ return provider == "anthropic" or (provider == "bedrock" and "anthropic." in provider_model)+++def anthropic_cached_system_blocks(+ *,+ model: str,+ model_settings: ModelSettings,+ system_instructions: str | None,+) -> list[ChatCompletionTextObject] | None:+ if not isinstance(system_instructions, CacheableSystemInstructions) or not system_instructions.stable_prefix:+ return None+ if (model_settings.extra_args or {}).get("cache_control_injection_points"):+ return None+ if not all(_is_anthropic_model(candidate) for candidate in model_chain(model, model_settings)):+ return None+ blocks: list[ChatCompletionTextObject] = [+ {+ "type": "text",+ "text": system_instructions.stable_prefix,+ "cache_control": {"type": "ephemeral"},+ }+ ]+ if system_instructions.dynamic_suffix:+ blocks.append({"type": "text", "text": system_instructions.dynamic_suffix})+ return blocks++def build_explicit_cache_envelope(*,model: str,diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex 04b0c5aca..1d53d9c8d 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -14,6 +14,7 @@ from urllib.parse import urlparseimport structlogfrom agents.exceptions import MaxTurnsExceeded+from agents.items import TResponseInputItemfrom agents.memory.session import Sessionfrom agents.model_settings import ModelSettingsfrom agents.run import Runner@@ -989,6 +990,30 @@ def unread_tool_output_indices(items: Sequence[Any]) -> set[int]:return unread+def stable_prefix_anchor(items: Sequence[TResponseInputItem]) -> int | None:+ """Return the index of the last tool output or real user message that precedes both the compaction window and+ every unpruned screenshot. Later model calls resend every item up to that index unchanged."""+ fc_indices = [i for i, item in enumerate(items) if _item_field(item, "type") == "function_call"]+ fco_indices = [i for i, item in enumerate(items) if _item_field(item, "type") == "function_call_output"]+ unstable = {+ *fc_indices[-KEEP_RECENT_TOOL_OUTPUTS:],+ *fco_indices[-KEEP_RECENT_TOOL_OUTPUTS:],+ *unread_tool_output_indices(items),+ *(+ i+ for i, item in enumerate(items)+ if is_screenshot_message(item) and _item_field(item, "content") != SCREENSHOT_PLACEHOLDER+ ),+ }+ for index in range(min(unstable, default=len(items)) - 1, -1, -1):+ item = items[index]+ if _item_field(item, "type") == "function_call_output" or (+ _item_field(item, "role") == "user" and not is_synthetic_user_message(item)+ ):+ return index+ return None++def _prune_input_list(items: list[Any]) -> list[Any]:"""Drop all but the most recent screenshot, compress older tool outputs,and summarize the arguments of older tool CALLS so bulky payloads (likediff --git a/skyvern/forge/sdk/copilot/model_telemetry.py b/skyvern/forge/sdk/copilot/model_telemetry.pyindex c8ccf8f36..6ad259ac5 100644--- a/skyvern/forge/sdk/copilot/model_telemetry.py+++ b/skyvern/forge/sdk/copilot/model_telemetry.py@@ -6,7 +6,7 @@ import jsonimport reimport timefrom collections.abc import AsyncIterator, Callable, Iterator-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom types import SimpleNamespacefrom typing import Any, Literal, cast, overloadfrom urllib.parse import urlparse@@ -46,8 +46,11 @@ from skyvern.forge.sdk.api.llm.copilot_model_usage import (from skyvern.forge.sdk.copilot.cache_envelope import (CacheableSystemInstructions,ExplicitCacheEnvelope,+ anthropic_cached_system_blocks,build_explicit_cache_envelope,+ model_chain,)+from skyvern.forge.sdk.copilot.enforcement import stable_prefix_anchorfrom skyvern.forge.sdk.copilot.model_input_capture import attach_tool_surface_to_pending_capturefrom skyvern.forge.sdk.copilot.pending_operation import pending_operation@@ -138,6 +141,8 @@ class CopilotModelCallTelemetry:cache_write = _usage_field(details, "cache_write_tokens")if cache_write is None:cache_write = (getattr(details, "model_extra", None) or {}).get("cache_write_tokens")+ if cache_write is None:+ cache_write = _usage_field(details, "cache_creation_tokens")if isinstance(cache_write, int) and not isinstance(cache_write, bool):self.cache_write_tokens = cache_write@@ -409,9 +414,7 @@ def _is_gemini_model(model: str) -> bool:def _gemini_on_model_chain(model: str, model_settings: ModelSettings) -> bool:- fallbacks: list[str | dict[str, Any]] = (model_settings.extra_args or {}).get("fallbacks") or []- models = [hop["model"] if isinstance(hop, dict) else hop for hop in fallbacks]- return any(_is_gemini_model(candidate) for candidate in [model, *models])+ return any(_is_gemini_model(candidate) for candidate in model_chain(model, model_settings))def _has_ref_key(value: object) -> bool:@@ -629,8 +632,45 @@ class CopilotLitellmModel(LitellmModel):stream,)else:+ sent_instructions = str(system_instructions) if system_instructions is not None else None+ anthropic_system_blocks = anthropic_cached_system_blocks(+ model=self.model,+ model_settings=model_settings,+ system_instructions=system_instructions,+ )+ if anthropic_system_blocks is not None:+ breakpoint_count = 1+ anchor = stable_prefix_anchor(input) if isinstance(input, list) else None+ if anchor is not None:+ anchor_messages = Converter.items_to_messages(+ input[: anchor + 1],+ base_url=self.base_url,+ preserve_thinking_blocks=model_settings.reasoning is not None+ and model_settings.reasoning.effort is not None,+ preserve_tool_output_all_content=True,+ model=self.model,+ should_replay_reasoning_content=self.should_replay_reasoning_content,+ )+ # The recent tool window is rewritten and frames are later replaced by a placeholder, so the marker+ # sits on the anchor before them; the count mirrors the SDK's tool-call split, with system at 0.+ rolling_index = len(self._fix_tool_message_ordering(anchor_messages))+ model_settings = replace(+ model_settings,+ extra_args={+ **(model_settings.extra_args or {}),+ "cache_control_injection_points": [{"location": "message", "index": rolling_index}],+ },+ )+ breakpoint_count += 1+ # The SDK inserts system content verbatim, so a block list reaches LiteLLM as list-form system content.+ sent_instructions = cast(str, anthropic_system_blocks)+ telemetry = current_model_call_telemetry()+ if telemetry is not None:+ telemetry.cache_mode = "explicit"+ telemetry.cache_breakpoint_count = breakpoint_count+ telemetry.cache_stable_prefix_chars = len(anthropic_system_blocks[0]["text"])result = await super()._fetch_response(- str(system_instructions) if system_instructions is not None else None,+ sent_instructions,input,model_settings,tools,diff --git a/tests/unit/test_copilot_model_telemetry.py b/tests/unit/test_copilot_model_telemetry.pyindex ae80790b4..4c6b9b2e3 100644--- a/tests/unit/test_copilot_model_telemetry.py+++ b/tests/unit/test_copilot_model_telemetry.py@@ -4,17 +4,20 @@ import asyncioimport contextlibimport copyimport json-from collections.abc import AsyncIterator, Iterator+from collections.abc import AsyncIterator, Callable, Iteratorfrom types import SimpleNamespacefrom typing import Any, Self, castfrom unittest.mock import AsyncMock, MagicMock+import litellmimport pytestfrom agents import ItemHelpers, ModelSettings, RunContextWrapper, function_toolfrom agents.extensions.models.litellm_model import LitellmModelfrom agents.items import TResponseInputItemfrom agents.mcp import MCPServer, MCPUtilfrom agents.models.interface import ModelTracing+from litellm.integrations.anthropic_cache_control_hook import AnthropicCacheControlHook+from litellm.llms.anthropic.chat.transformation import AnthropicConfigfrom litellm.llms.vertex_ai.gemini.transformation import _gemini_convert_messages_with_historyfrom litellm.types.llms.openai import ResponsesAPIResponsefrom litellm.types.utils import Delta@@ -32,6 +35,7 @@ from skyvern.forge.sdk.copilot import model_telemetry as model_telemetry_modulefrom skyvern.forge.sdk.copilot.browser_ablation import CopilotEvalModefrom skyvern.forge.sdk.copilot.cache_envelope import CacheableSystemInstructionsfrom skyvern.forge.sdk.copilot.config import CopilotConfig+from skyvern.forge.sdk.copilot.enforcement import NUDGE_SENTINEL, SCREENSHOT_SENTINEL, _prune_input_listfrom skyvern.forge.sdk.copilot.mcp_adapter import _copilot_to_call_tool_resultfrom skyvern.forge.sdk.copilot.model_telemetry import (CopilotLitellmModel,@@ -46,6 +50,7 @@ from skyvern.forge.sdk.copilot.pending_operation import (pending_operation,pending_operation_fields,)+from skyvern.forge.sdk.copilot.session_factory import copilot_session_input_callbackfrom skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequest@@ -406,7 +411,13 @@ async def test_cacheable_system_instructions_survive_provider_message_copy(else:response = await _get_response(model, system_instructions=prompt)- assert copied_messages[0][0] == {"role": "system", "content": str(prompt)}+ assert copied_messages[0][0] == {+ "role": "system",+ "content": [+ {"type": "text", "text": "stable instructions", "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "\ndynamic context"},+ ],+ }assert ItemHelpers.extract_last_text(response.output[-1]) == "42"@@ -659,6 +670,33 @@ def test_model_call_cost_uses_runtime_litellm_pricing(monkeypatch: pytest.Monkey}+def test_anthropic_cache_writes_and_reads_are_priced_at_their_own_rates() -> None:+ usage = AnthropicConfig().calculate_usage(+ usage_object={+ "input_tokens": 1200,+ "cache_creation_input_tokens": 3000,+ "cache_read_input_tokens": 20000,+ "output_tokens": 400,+ },+ reasoning_content=None,+ )+ telemetry = model_telemetry_module.CopilotModelCallTelemetry(model_call_index=1)+ telemetry.capture(usage)+ rates = litellm.model_cost["claude-sonnet-5-5"]++ assert (rates["cache_creation_input_token_cost"], rates["cache_read_input_token_cost"]) == (+ pytest.approx(1.25 * rates["input_cost_per_token"]),+ pytest.approx(0.1 * rates["input_cost_per_token"]),+ )+ assert (telemetry.cache_read_tokens, telemetry.cache_write_tokens) == (20000, 3000)+ assert model_telemetry_module._model_call_cost(telemetry, "claude-sonnet-5-5") == pytest.approx(+ 1200 * rates["input_cost_per_token"]+ + 3000 * rates["cache_creation_input_token_cost"]+ + 20000 * rates["cache_read_input_token_cost"]+ + 400 * rates["output_cost_per_token"]+ )++def test_model_call_cost_normalizes_dated_gpt56_response_model(monkeypatch: pytest.MonkeyPatch) -> None:priced_models: list[str] = []@@ -1410,13 +1448,15 @@ async def _block_schema_tool_output(block_type: str) -> tuple[object, str]:return output, cast(Any, call_result.content[0]).text-async def _sent_messages(+async def _sent_request(monkeypatch: pytest.MonkeyPatch,model: LitellmModel,turn: list[TResponseInputItem],extra_args: dict[str, Any] | None,stream: bool = False,-) -> list[dict[str, Any]]:+ system_instructions: str = "You are concise.",+ model_settings: ModelSettings | None = None,+) -> dict[str, Any]:requests: list[dict[str, Any]] = []async def fake_acompletion(**kwargs: Any) -> LiteLLMModelResponse | AsyncStream[ChatCompletionChunk]:@@ -1425,9 +1465,9 @@ async def _sent_messages(monkeypatch.setattr("litellm.acompletion", fake_acompletion)call = {- "system_instructions": "You are concise.",+ "system_instructions": system_instructions,"input": turn,- "model_settings": ModelSettings(extra_args=extra_args),+ "model_settings": model_settings or ModelSettings(extra_args=extra_args),"tools": [],"output_schema": None,"handoffs": [],@@ -1438,7 +1478,188 @@ async def _sent_messages(passelse:await model.get_response(**call)- return requests[0]["messages"]+ return requests[0]+++async def _sent_messages(+ monkeypatch: pytest.MonkeyPatch,+ model: LitellmModel,+ turn: list[TResponseInputItem],+ extra_args: dict[str, Any] | None,+ stream: bool = False,+) -> list[dict[str, Any]]:+ return (await _sent_request(monkeypatch, model, turn, extra_args, stream))["messages"]+++_SONNET_ROUTES = ["anthropic/claude-sonnet-5-5", "bedrock/global.anthropic.claude-sonnet-5-5"]+_CACHED_PROMPT = CacheableSystemInstructions("stable instructions", "\ndynamic timestamp", cache_namespace="wcc_test")+_FRAME: TResponseInputItem = {+ "role": "user",+ "content": [+ {"type": "input_text", "text": SCREENSHOT_SENTINEL + "Frame"},+ {"type": "input_image", "image_url": "data:image/png;base64,AAAA", "detail": "low"},+ ],+}+_NUDGE: TResponseInputItem = {"role": "user", "content": NUDGE_SENTINEL + "Keep going."}+++def _provider_messages(model_name: str, request: dict[str, Any]) -> list[dict[str, Any]]:+ _, messages, _ = AnthropicCacheControlHook().get_chat_completion_prompt(+ model=model_name,+ messages=request["messages"],+ non_default_params={"cache_control_injection_points": request.get("cache_control_injection_points")},+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ )+ return messages+++def _marked_indices(messages: list[dict[str, Any]]) -> list[int]:+ return [index for index, message in enumerate(messages) if '"cache_control"' in json.dumps(message)]+++def _cache_usage(logs: list[dict[str, Any]]) -> tuple[str, int, int | None]:+ (usage,) = (entry for entry in logs if entry.get("log_code") == "copilot_model_usage")+ return (+ usage["copilot.cache.mode"],+ usage["copilot.cache.breakpoint_count"],+ usage.get("copilot.cache.stable_prefix_chars"),+ )+++def _tool_round(call_id: str) -> list[TResponseInputItem]:+ return [+ {"type": "function_call", "call_id": call_id, "name": "evaluate", "arguments": json.dumps({"code": "x" * 400})},+ {"type": "function_call_output", "call_id": call_id, "output": json.dumps({"ok": True, "text": "y" * 400})},+ ]++[email protected]("model_name", _SONNET_ROUTES)+ ("turn", "marked", "breakpoints"),+ [+ (_tool_turn("tool result"), [0, 1], 2),+ (_tool_turn("tool result") + [_FRAME], [0, 1], 2),+ (_tool_turn("tool result") + [_FRAME, _NUDGE], [0, 1], 2),+ ([_FRAME], [0], 1),+ ],+)+async def test_anthropic_route_marks_stable_system_prefix_and_the_stable_anchor(+ monkeypatch: pytest.MonkeyPatch,+ model_name: str,+ turn: list[TResponseInputItem],+ marked: list[int],+ breakpoints: int,+) -> None:+ model_settings = ModelSettings(extra_args={"fallbacks": ["bedrock/global.anthropic.claude-sonnet-5-5"]})+ with capture_logs() as logs:+ request = await _sent_request(+ monkeypatch,+ CopilotLitellmModel(model=model_name, next_model_call_index=lambda: 1),+ turn,+ None,+ system_instructions=_CACHED_PROMPT,+ model_settings=model_settings,+ )++ stable_block, dynamic_block = request["messages"][0]["content"]+ assert stable_block["cache_control"] == {"type": "ephemeral"}+ assert "cache_control" not in dynamic_block+ assert stable_block["text"] + dynamic_block["text"] == str(_CACHED_PROMPT)+ assert _marked_indices(_provider_messages(model_name, request)) == marked+ assert _cache_usage(logs) == ("explicit", breakpoints, len("stable instructions"))+ assert model_settings.extra_args == {"fallbacks": ["bedrock/global.anthropic.claude-sonnet-5-5"]}++[email protected]("model_name", _SONNET_ROUTES)+ "next_call_input",+ [copilot_session_input_callback, lambda history, new_items: _prune_input_list([*history, *new_items])],+ ids=["session", "no_session"],+)+ ("mid_history", "anchor_call_id"),+ [([_FRAME, _NUDGE], "call_1"), ([_NUDGE], "call_2")],+ ids=["frame_then_nudge", "nudge"],+)+async def test_anthropic_rolling_marker_prefix_is_resent_unchanged_on_the_next_call(+ monkeypatch: pytest.MonkeyPatch,+ model_name: str,+ next_call_input: Callable[[list[TResponseInputItem], list[TResponseInputItem]], list[TResponseInputItem]],+ mid_history: list[TResponseInputItem],+ anchor_call_id: str,+) -> None:+ (call_0a, output_0a), (call_0b, output_0b) = _tool_round("call_0a"), _tool_round("call_0b")+ history: list[TResponseInputItem] = [+ {"role": "user", "content": "Build the workflow"},+ {+ "type": "message",+ "role": "assistant",+ "id": "msg_0",+ "status": "completed",+ "content": [{"type": "output_text", "text": "Checking the page.", "annotations": []}],+ },+ call_0a,+ call_0b,+ output_0a,+ output_0b,+ *_tool_round("call_1"),+ *mid_history,+ *_tool_round("call_2"),+ *_tool_round("call_3"),+ *_tool_round("call_4"),+ *_tool_round("call_5"),+ ]+ requests = []+ for turn in (+ next_call_input(history, []),+ next_call_input([*history, *_tool_round("call_6")], [_FRAME, _NUDGE]),+ ):+ requests.append(+ await _sent_request(+ monkeypatch,+ CopilotLitellmModel(model=model_name, next_model_call_index=lambda: 1),+ turn,+ None,+ system_instructions=_CACHED_PROMPT,+ )+ )++ provider_messages = _provider_messages(model_name, requests[0])+ rolling = _marked_indices(provider_messages)[-1]+ assert requests[0]["messages"][: rolling + 1] == requests[1]["messages"][: rolling + 1]+ assert provider_messages[rolling]["tool_call_id"] == anchor_call_id+++ ("model_name", "extra_args"),+ [+ ("openai/gpt-5.5", None),+ ("anthropic/claude-sonnet-5-5", {"fallbacks": ["openai/gpt-5.5"]}),+ ("anthropic/claude-sonnet-5-5", {"cache_control_injection_points": [{"location": "message", "role": "user"}]}),+ ],+)+async def test_anthropic_cache_breakpoints_opt_out_off_an_all_anthropic_chain_or_with_caller_points(+ monkeypatch: pytest.MonkeyPatch,+ model_name: str,+ extra_args: dict[str, Any] | None,+) -> None:+ with capture_logs() as logs:+ request = await _sent_request(+ monkeypatch,+ CopilotLitellmModel(model=model_name, next_model_call_index=lambda: 1),+ _tool_turn("tool result"),+ extra_args,+ system_instructions=_CACHED_PROMPT,+ )++ assert request["messages"][0] == {"role": "system", "content": str(_CACHED_PROMPT)}+ assert request.get("cache_control_injection_points") == (extra_args or {}).get("cache_control_injection_points")+ assert _cache_usage(logs)[:2] == ("implicit", 0)def _tool_message(messages: list[dict[str, Any]]) -> dict[str, Any]: