File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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 (
Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments