Skip to content

Commit 59ee5ec

Browse files
committed
#239: Fix cache control to account for limits by only caching last and penultimate messages
1 parent 4b3b41b commit 59ee5ec

2 files changed

Lines changed: 26 additions & 3 deletions

File tree

aider/coders/chat_chunks.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,25 @@ def add_cache_control_headers(self):
6262
# The history is ephemeral on its own.
6363
self.add_cache_control(self.done)
6464

65+
# Per this: https://github.com/BerriAI/litellm/issues/10226
66+
# The first and second to last messages are cache optimal
67+
# Since caches are also written to incrementally and you need
68+
# the past and current states to properly append and gain
69+
# efficiencies/savings in cache writing
6570
def add_cache_control(self, messages):
66-
if not messages:
71+
if not messages or len(messages) < 2:
6772
return
6873

74+
content = messages[-2]["content"]
75+
if type(content) is str:
76+
content = dict(
77+
type="text",
78+
text=content,
79+
)
80+
content["cache_control"] = {"type": "ephemeral"}
81+
82+
messages[-2]["content"] = [content]
83+
6984
content = messages[-1]["content"]
7085
if type(content) is str:
7186
content = dict(

aider/models.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -977,11 +977,19 @@ async def send_completion(
977977
dump(kwargs)
978978
kwargs["messages"] = messages
979979

980-
# Cache System Prompts When Possible
980+
# Per this: https://github.com/BerriAI/litellm/issues/10226
981+
# The first and second to last messages are cache optimal
982+
# Since caches are also written to incrementally and you need
983+
# the past and current states to properly append and gain
984+
# efficiencies/savings in cache writing
981985
kwargs["cache_control_injection_points"] = [
982986
{
983987
"location": "message",
984-
"role": "system",
988+
"index": -1,
989+
},
990+
{
991+
"location": "message",
992+
"index": -2,
985993
},
986994
]
987995

0 commit comments

Comments
 (0)