Personal AI, On Personal Devices
Python
feat: add Anthropic prompt cache breakpoint annotation
Tarun Suresh981f665913e7
diff --git a/src/openjarvis/engine/cloud.py b/src/openjarvis/engine/cloud.pyindex cacf651f..8181a4b7 100644--- a/src/openjarvis/engine/cloud.py+++ b/src/openjarvis/engine/cloud.py@@ -113,6 +113,31 @@ def estimate_cost(model: str, prompt_tokens: int, completion_tokens: int) -> floreturn input_cost + output_cost+def _annotate_anthropic_cache(messages: list[dict]) -> list[dict]:+ """Add cache_control to system message for Anthropic prompt caching."""+ result = []+ for msg in messages:+ if msg.get("role") == "system":+ content = msg["content"]+ if isinstance(content, str):+ content = [+ {+ "type": "text",+ "text": content,+ "cache_control": {"type": "ephemeral"},+ }+ ]+ elif isinstance(content, list):+ content = [+ {**block, "cache_control": {"type": "ephemeral"}}+ for block in content+ ]+ result.append({**msg, "content": content})+ else:+ result.append(msg)+ return result++def _convert_tools_to_anthropic(openai_tools: List[Dict[str, Any]],) -> List[Dict[str, Any]]:@@ -816,4 +841,4 @@ class CloudEngine(InferenceEngine):self._openrouter_client = None-__all__ = ["CloudEngine", "PRICING", "estimate_cost"]+__all__ = ["CloudEngine", "PRICING", "_annotate_anthropic_cache", "estimate_cost"]diff --git a/tests/engine/test_cache_breakpoint.py b/tests/engine/test_cache_breakpoint.pynew file mode 100644index 00000000..1ea5e543--- /dev/null+++ b/tests/engine/test_cache_breakpoint.py@@ -0,0 +1,37 @@+from __future__ import annotations+++def test_anthropic_cache_breakpoint_added():+ from openjarvis.engine.cloud import _annotate_anthropic_cache++ messages = [+ {"role": "system", "content": "You are Jarvis. ## Persona\nHelpful assistant."},+ {"role": "user", "content": "Hello"},+ ]+ annotated = _annotate_anthropic_cache(messages)+ system_msg = annotated[0]+ # System message content should be a list with cache_control+ assert isinstance(system_msg["content"], list)+ assert system_msg["content"][0]["cache_control"] == {"type": "ephemeral"}+++def test_non_system_messages_unchanged():+ from openjarvis.engine.cloud import _annotate_anthropic_cache++ messages = [+ {"role": "user", "content": "Hello"},+ {"role": "assistant", "content": "Hi there"},+ ]+ annotated = _annotate_anthropic_cache(messages)+ assert annotated[0]["content"] == "Hello"+ assert annotated[1]["content"] == "Hi there"+++def test_already_list_content_gets_cache_control():+ from openjarvis.engine.cloud import _annotate_anthropic_cache++ messages = [+ {"role": "system", "content": [{"type": "text", "text": "You are Jarvis."}]},+ ]+ annotated = _annotate_anthropic_cache(messages)+ assert annotated[0]["content"][0]["cache_control"] == {"type": "ephemeral"}