anthropics / anthropics/claude-quickstarts
API Error Connection
- Dominant language
- TypeScript
- Stars
- 17.6k
- Forks
- 3k
- Avg merge
- 5h 13m
- Merged PRs (30d)
- 3
Description
hi,
why i get an error
[DEBUG] Error in chat request {
"error": {
"name": "Error",
"message": "Connection error.",
"stack": "Error: Connection error.\n at Anthropic.makeRequest (webpack-internal:///(rsc)/./node_modules/@anthropic-ai/sdk/core.mjs:338:19)\n at async POST (webpack-internal:///(rsc)/./src/app/api/chat/route.ts:50:26)\n at async G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\compiled\\next-server\\app-route.runtime.dev.js:6:63809\n at async eU.execute (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\compiled\\next-server\\app-route.runtime.dev.js:6:53964)\n at async eU.handle (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\compiled\\next-server\\app-route.runtime.dev.js:6:65062)\n at async doRender (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\base-server.js:1333:42)\n at async cacheEntry.responseCache.get.routeKind (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\base-server.js:1555:28)\n at async DevServer.renderToResponseWithComponentsImpl (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\base-server.js:1463:28)\n at async DevServer.renderPageComponent (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\base-server.js:1856:24)\n at async DevServer.renderToResponseImpl (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\base-server.js:1894:32)\n at async DevServer.pipeImpl (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\base-server.js:911:25)\n at async Nre-anthropic\\node_modules\\next\\dist\\server\\base-server.js:911:25)\n at async NextNodeServer.handleCatchallRenderRequest (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\next-server.js:271:17)\n at async DevServer.handleRequestImpl (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\base-server.js:es\\next\\dist\\server\\next-server.js:271:17)\n at async DevServer.handleRequestImpl (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\base-server.js:807:17)\n at async G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\servepl (G:\r\\dev\\next-dev-server.js:331:20\n at async Span.traceAsyncFn (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\trace\\trace.js:151:20)\n at async DevServer.handleRequest (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\dev\\next-dev-server.js:328:24)\n at async invokeRender (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\lib\\router-server.js:163:21)\n at async handleRequest (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\lib\\router-server.js:342:24)\n at async requestHandlerImpl (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\lib\\router-server.js:366:13)\n at async Server.requestListener (G:\\images-diff-score-anthropic\\node_modules\\next\\dist\\server\\lib\\start-server.js:140:13)",
"cause": {}
}
}
for my code typescript for image analysis:
route.tsx
import { NextResponse } from 'next/server';
import Anthropic from '@anthropic-ai/sdk';
import axios from 'axios';
// Debug logging function
const debugLog = (message: string, data?: any) => {
console.log(`[DEBUG] ${message}`, data ? JSON.stringify(data, null, 2) : '');
};
async function getBase64Image(url: string): Promise {
try {
// Remove any leading/trailing whitespace from URL
const cleanUrl = url.trim();
debugLog('Fetching image from cleaned URL', { cleanUrl });
const response = await axios.get(cleanUrl, {
responseType: 'arraybuffer',
timeout: 10000, // 10 second timeout
maxContentLength: 10 * 1024 * 1024 // 10MB max
});
return Buffer.from(response.data, 'binary').toString('base64');
} catch (error) {
debugLog('Error fetching image:', error);
throw new Error('Failed to fetch image: ' + (error instanceof Error ? error.message : String(error)));
}
}
if (!process.env.ANTHROPIC_API_KEY) {
throw new Error('Missing ANTHROPIC_API_KEY environment variable');
}
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
export async function POST(request: Request) {
try {
const body = await request.json();
const { imageUrl } = body;
if (!imageUrl) {
return NextResponse.json(
{ error: 'Image URL is required' },
{ status: 400 }
);
}
debugLog('Fetching image from URL', { imageUrl });
const imageData = await getBase64Image(imageUrl);
debugLog('Making request to Anthropic API');
const message = await anthropic.messages.create({
model: "claude-3-5-sonnet-20240620",
max_tokens: 1024,
temperature: 0.7,
system: "You are an expert image analyzer. Always respond in JSON format with 'description' and 'tags' fields.",
messages: [
{
role: "user",
content: [
{
type: "text",
text: "Analyze this image in detail, focusing on the main subject, colors, composition, and any notable features."
},
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: imageData
}
}
]
}
]
});
debugLog('Received response from Anthropic API');
if (!message.content[0] || !message.content[0].text) {
throw new Error('Unexpected API response format');
}
const responseText = message.content[0].text;
try {
const result = JSON.parse(responseText);
return NextResponse.json(result);
} catch (error) {
debugLog('Failed to parse JSON response, using raw text', { responseText });
return NextResponse.json({
description: responseText,
tags: []
});
}
} catch (error: any) {
debugLog('Error processing image', {
error: {
name: error.name,
message: error.message,
status: error.status,
type: error.type,
stack: error.stack
}
});
// Handle specific error types
if (error.name === 'APIError') {
return NextResponse.json(
{
error: 'API Error',
details: error.message,
status: error.status
},
{ status: error.status || 500 }
);
}
if (error.name === 'APIConnectionError') {
return NextResponse.json(
{
error: 'Connection error. Please check your network connection and try again.',
details: error.message
},
{ status: 503 }
);
}
if (error.name === 'AuthenticationError') {
return NextResponse.json(
{
error: 'Authentication failed. Please check your API key.',
details: error.message
},
{ status: 401 }
);
}
return NextResponse.json(
{
error: 'Failed to process image',
details: error.message
},
{ status: error.status || 500 }
);
}
}
and rendered page.tsx
'use client';
import { useState } from 'react';
import axios from 'axios';
export default function TestPage() {
const [imageUrl, setImageUrl] = useState('');
const [result, setResult] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError(null);
setResult(null);
try {
const response = await axios.post('/api/test-image', { imageUrl });
setResult(response.data);
} catch (error: any) {
setError(error.response?.data?.error || 'Failed to analyze image');
} finally {
setLoading(false);
}
};
return (
Image Analysis Test
setImageUrl(e.target.value)}
placeholder="Enter image URL"
className="flex-1 px-4 py-2 border rounded-lg"
/>
{loading ? 'Analyzing...' : 'Analyze'}
{error && (
{error}
)}
{result && (
Image
Analysis Result
{result.description}
{result.tags && (
Tags:
{result.tags.map((tag: string, index: number) => (
{tag}
))}
)}
)}
{loading && (
)}
);
}
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.