From e5c7a523c52154035bad43116105b2b4eed18eff Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:38:28 +0200 Subject: [PATCH] Improves Anthropic API client robustness Enhances API client with more reliable pagination and response handling: - Uses URLSearchParams for clearer parameter management - Increases pagination limit to 1000 to reduce API calls - Adds more robust content parsing for multi-block responses - Implements stricter API health check validation Ensures more predictable and resilient API interactions --- api/anthropicClient.ts | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts index 12540ff..f0ed36d 100644 --- a/api/anthropicClient.ts +++ b/api/anthropicClient.ts @@ -133,8 +133,14 @@ export class AnthropicClient { // Fetch all pages while (hasMore) { - // Build URL with pagination parameter if needed - const url = afterId ? `${this.modelsUrl}?after=${afterId}` : this.modelsUrl; + // Build URL with pagination parameters + // Use limit=1000 (Anthropic's max) to minimize round trips + const params = new URLSearchParams(); + params.set('limit', '1000'); + if (afterId) { + params.set('after', afterId); + } + const url = `${this.modelsUrl}?${params.toString()}`; const response = await requestUrl({ url, @@ -273,7 +279,12 @@ export class AnthropicClient { throw new Error('No content received from API'); } - const text = response.content[0].text; + // Parse all text blocks, not just the first one + // Anthropic API can return multiple content blocks + const text = response.content + .filter(c => c && c.type === 'text' && typeof c.text === 'string') + .map(c => c.text) + .join('\n'); const lines = text.split('\n') .map(line => line.trim()) .filter(line => line.length > 0); @@ -362,9 +373,16 @@ export class AnthropicClient { const response = await this.makeRequest(testRequest); const responseTime = Date.now() - startTime; + // Validate that the assistant actually returned "ping" + // This ensures the API is working correctly, not just returning a 2xx status + const returnedText = (response.content?.[0]?.text || '').trim().toLowerCase(); + const isValid = returnedText === 'ping'; + return { - success: true, - message: 'API key is valid and working correctly', + success: isValid, + message: isValid + ? 'API key is valid and working correctly' + : 'API responded but returned unexpected content', details: { model: response.model, responseTime,