11import { Anthropic } from "@anthropic-ai/sdk"
22import { Stream as AnthropicStream } from "@anthropic-ai/sdk/streaming"
33import { withRetry } from "../retry"
4- import { anthropicDefaultModelId , AnthropicModelId , anthropicModels , ApiHandlerOptions , ModelInfo } from "@shared/api"
4+ import { anthropicDefaultModelId , AnthropicModelId , anthropicModels , CLAUDE_SONNET_4_1M_SUFFIX , ModelInfo } from "@shared/api"
55import { ApiHandler } from "../index"
66import { ApiStream } from "../transform/stream"
77
8+ interface AnthropicHandlerOptions {
9+ apiKey ?: string
10+ anthropicBaseUrl ?: string
11+ apiModelId ?: string
12+ thinkingBudgetTokens ?: number
13+ maxRetries ?: number
14+ }
15+
816export class AnthropicHandler implements ApiHandler {
9- private options : ApiHandlerOptions
17+ private options : AnthropicHandlerOptions
1018 private client : Anthropic
1119
12- constructor ( options : ApiHandlerOptions ) {
20+ constructor ( options : AnthropicHandlerOptions ) {
1321 this . options = options
1422 this . client = new Anthropic ( {
1523 apiKey : this . options . apiKey ,
@@ -22,7 +30,10 @@ export class AnthropicHandler implements ApiHandler {
2230 async * createMessage ( systemPrompt : string , messages : Anthropic . Messages . MessageParam [ ] ) : ApiStream {
2331 const model = this . getModel ( )
2432 let stream : AnthropicStream < Anthropic . RawMessageStreamEvent >
25- const modelId = model . id
33+ const modelId = model . id . endsWith ( CLAUDE_SONNET_4_1M_SUFFIX )
34+ ? model . id . slice ( 0 , - CLAUDE_SONNET_4_1M_SUFFIX . length )
35+ : model . id
36+ const enable1mContextWindow = model . id . endsWith ( CLAUDE_SONNET_4_1M_SUFFIX )
2637
2738 const budget_tokens = this . options . thinkingBudgetTokens || 0
2839 const reasoningOn = ( modelId . includes ( "3-7" ) || modelId . includes ( "4-" ) ) && budget_tokens !== 0 ? true : false
@@ -95,24 +106,15 @@ export class AnthropicHandler implements ApiHandler {
95106 stream : true ,
96107 } ,
97108 ( ( ) => {
98- // prompt caching: https://x.com/alexalbert__/status/1823751995901272068
99- // https://github.com/anthropics/anthropic-sdk-typescript?tab=readme-ov-file#default-headers
100- // https://github.com/anthropics/anthropic-sdk-typescript/commit/c920b77fc67bd839bfeb6716ceab9d7c9bbe7393
101- switch ( modelId ) {
102- case "claude-sonnet-4-20250514" :
103- case "claude-opus-4-20250514" :
104- case "claude-3-7-sonnet-20250219" :
105- case "claude-3-5-sonnet-20241022" :
106- case "claude-3-5-haiku-20241022" :
107- case "claude-3-opus-20240229" :
108- case "claude-3-haiku-20240307" :
109- return {
110- headers : {
111- "anthropic-beta" : "prompt-caching-2024-07-31" ,
112- } ,
113- }
114- default :
115- return undefined
109+ // 1m context window beta header
110+ if ( enable1mContextWindow ) {
111+ return {
112+ headers : {
113+ "anthropic-beta" : "context-1m-2025-08-07" ,
114+ } ,
115+ }
116+ } else {
117+ return undefined
116118 }
117119 } ) ( ) ,
118120 )
0 commit comments