From d062239fb1aa3b33910b14429bd87f1bda86990d Mon Sep 17 00:00:00 2001 From: Keval Shah Date: Sat, 28 Nov 2026 14:05:41 +0530 Subject: [PATCH] Cache the Claude conversation between turns in the anthropic plugin --- plugins/anthropic/tests/test_anthropic_llm.py | 22 +++++++++++++++++++ .../plugins/anthropic/anthropic_llm.py | 7 +++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/plugins/anthropic/tests/test_anthropic_llm.py b/plugins/anthropic/tests/test_anthropic_llm.py index da95f142d6..19c0afcd83 100644 --- a/plugins/anthropic/tests/test_anthropic_llm.py +++ b/plugins/anthropic/tests/test_anthropic_llm.py @@ -134,6 +134,28 @@ async def test_the_model_is_told_once_a_second_person_has_spoken( assert told == ["be brief", "be brief", "be brief\n\n" + SEVERAL_SPEAKERS] assert bodies[-1]["messages"][-1] == {"role": "user", "content": "Bob: Me too"} + # Building the Anthropic client stats files, which blockbuster refuses in a loop. + @pytest.mark.skip_blockbuster + async def test_each_turn_asks_to_cache_the_conversation( + self, anthropic_api: tuple[str, list[dict]] + ): + url, bodies = anthropic_api + conversation = InMemoryConversation("", []) + llm = ClaudeLLM( + model="test", client=anthropic.AsyncAnthropic(api_key="test", base_url=url) + ) + llm.set_conversation(conversation) + llm.set_instructions("be brief") + + for text in ("Hi", "Hello?"): + await answer(llm, conversation, ALICE, text) + await llm.close() + + assert [body.get("cache_control") for body in bodies] == [ + {"type": "ephemeral"}, + {"type": "ephemeral"}, + ] + # Building the Anthropic client stats files, which blockbuster refuses in a loop. @pytest.mark.skip_blockbuster async def test_a_named_turn_already_in_the_conversation_is_sent_once(self): diff --git a/plugins/anthropic/vision_agents/plugins/anthropic/anthropic_llm.py b/plugins/anthropic/vision_agents/plugins/anthropic/anthropic_llm.py index 8a0f608c44..3a284d42ee 100644 --- a/plugins/anthropic/vision_agents/plugins/anthropic/anthropic_llm.py +++ b/plugins/anthropic/vision_agents/plugins/anthropic/anthropic_llm.py @@ -86,8 +86,13 @@ async def simple_response( llm.simple_response("say hi to the user, be mean") """ + kwargs: Dict[str, Any] = {} + if isinstance(self.client, anthropic.AsyncAnthropic): + # The instructions, tools and conversation so far are read from the + # cache on the next turn: https://platform.claude.com/docs/en/build-with-claude/prompt-caching + kwargs["cache_control"] = {"type": "ephemeral"} async for item in self._stream_message( - messages=[{"role": "user", "content": text}], max_tokens=1000 + messages=[{"role": "user", "content": text}], max_tokens=1000, **kwargs ): yield item