@@ -179,30 +179,38 @@ class Anthropic extends BaseLLM {
179179 ) ;
180180
181181 const msgs = this . convertMessages ( messages ) ;
182+
183+ // Merge default headers with custom headers
184+ const headers : any = {
185+ "Content-Type" : "application/json" ,
186+ Accept : "application/json" ,
187+ "anthropic-version" : "2023-06-01" ,
188+ "x-api-key" : this . apiKey as string ,
189+ ...this . requestOptions ?. headers ,
190+ } ;
191+
192+ // Handle the special case for anthropic-beta
193+ this . setBetaHeaders ( headers , shouldCacheSystemMessage ) ;
194+
195+ // Create the request body
196+ const requestBody = {
197+ ...this . convertArgs ( options ) ,
198+ messages : msgs ,
199+ system : shouldCacheSystemMessage
200+ ? [
201+ {
202+ type : "text" ,
203+ text : this . systemMessage ,
204+ cache_control : { type : "ephemeral" } ,
205+ } ,
206+ ]
207+ : systemMessage ,
208+ } ;
209+
182210 const response = await this . fetch ( new URL ( "messages" , this . apiBase ) , {
183211 method : "POST" ,
184- headers : {
185- "Content-Type" : "application/json" ,
186- Accept : "application/json" ,
187- "anthropic-version" : "2023-06-01" ,
188- "x-api-key" : this . apiKey as string ,
189- ...( shouldCacheSystemMessage || this . cacheBehavior ?. cacheConversation
190- ? { "anthropic-beta" : "prompt-caching-2024-07-31" }
191- : { } ) ,
192- } ,
193- body : JSON . stringify ( {
194- ...this . convertArgs ( options ) ,
195- messages : msgs ,
196- system : shouldCacheSystemMessage
197- ? [
198- {
199- type : "text" ,
200- text : this . systemMessage ,
201- cache_control : { type : "ephemeral" } ,
202- } ,
203- ]
204- : systemMessage ,
205- } ) ,
212+ headers,
213+ body : JSON . stringify ( requestBody ) ,
206214 signal,
207215 } ) ;
208216
@@ -277,14 +285,40 @@ class Anthropic extends BaseLLM {
277285 }
278286 break ;
279287 case "content_block_stop" :
280- lastToolUseId = undefined ;
281- lastToolUseName = undefined ;
288+ lastToolUseId = undefined ;
289+ lastToolUseName = undefined ;
282290 break ;
283291 default :
284292 break ;
285293 }
286294 }
287295 }
296+
297+ private setBetaHeaders (
298+ headers : any ,
299+ shouldCacheSystemMessage : boolean | undefined ,
300+ ) {
301+ const betaValues = new Set < string > ( ) ;
302+
303+ // Add from existing header if present
304+ const existingBeta = headers [ "anthropic-beta" ] ;
305+ if ( existingBeta && typeof existingBeta === "string" ) {
306+ existingBeta
307+ . split ( "," )
308+ . map ( ( v ) => v . trim ( ) )
309+ . forEach ( ( v ) => betaValues . add ( v ) ) ;
310+ }
311+
312+ // Add caching header if we should
313+ if ( shouldCacheSystemMessage || this . cacheBehavior ?. cacheConversation ) {
314+ betaValues . add ( "prompt-caching-2024-07-31" ) ;
315+ }
316+
317+ // Update the header if we have values
318+ if ( betaValues . size > 0 ) {
319+ headers [ "anthropic-beta" ] = Array . from ( betaValues ) . join ( "," ) ;
320+ }
321+ }
288322}
289323
290324export default Anthropic ;
0 commit comments