@@ -126,25 +126,34 @@ async function countTokensViaAnthropic(params: {
126126 const anthropicMessages = convertToAnthropicMessages ( messages )
127127
128128 // Use the count_tokens endpoint (beta) or make a minimal request
129- const response = await fetch ( 'https://api.anthropic.com/v1/messages/count_tokens' , {
130- method : 'POST' ,
131- headers : {
132- 'x-api-key' : env . ANTHROPIC_API_KEY ,
133- 'anthropic-version' : '2023-06-01' ,
134- 'anthropic-beta' : 'token-counting-2024-11-01' ,
135- 'content-type' : 'application/json' ,
129+ const response = await fetch (
130+ 'https://api.anthropic.com/v1/messages/count_tokens' ,
131+ {
132+ method : 'POST' ,
133+ headers : {
134+ 'x-api-key' : env . ANTHROPIC_API_KEY ,
135+ 'anthropic-version' : '2023-06-01' ,
136+ 'anthropic-beta' : 'token-counting-2024-11-01' ,
137+ 'content-type' : 'application/json' ,
138+ } ,
139+ body : JSON . stringify ( {
140+ model : model ?? 'claude-opus-4-5-20251101' ,
141+ messages : anthropicMessages ,
142+ ...( system && { system } ) ,
143+ } ) ,
136144 } ,
137- body : JSON . stringify ( {
138- model : model ?? 'claude-opus-4-5-20251101' ,
139- messages : anthropicMessages ,
140- ...( system && { system } ) ,
141- } ) ,
142- } )
145+ )
143146
144147 if ( ! response . ok ) {
145148 const errorText = await response . text ( )
146149 logger . error (
147- { status : response . status , errorText } ,
150+ {
151+ status : response . status ,
152+ errorText,
153+ messages : anthropicMessages ,
154+ system,
155+ model,
156+ } ,
148157 'Anthropic token count API error' ,
149158 )
150159 throw new Error ( `Anthropic API error: ${ response . status } - ${ errorText } ` )
@@ -211,7 +220,7 @@ function convertContentToAnthropic(
211220
212221 for ( const part of content ) {
213222 if ( part . type === 'text' ) {
214- anthropicContent . push ( { type : 'text' , text : part . text } )
223+ anthropicContent . push ( { type : 'text' , text : part . text . trim ( ) } )
215224 } else if ( part . type === 'tool-call' && role === 'assistant' ) {
216225 anthropicContent . push ( {
217226 type : 'tool_use' ,
@@ -231,7 +240,10 @@ function convertContentToAnthropic(
231240 } else if ( part . type === 'json' ) {
232241 anthropicContent . push ( {
233242 type : 'text' ,
234- text : JSON . stringify ( part . value ) ,
243+ text :
244+ typeof part . value === 'string'
245+ ? part . value . trim ( )
246+ : JSON . stringify ( part . value ) . trim ( ) ,
235247 } )
236248 }
237249 }
0 commit comments