anthropics / anthropic-sdk-typescript

Access to Anthropic's safety-first language model APIs
https://www.npmjs.com/package/@anthropic-ai/sdk
MIT License
505 stars 49 forks source link

Claude API error despite showing that its working in Anthropic Console. #425

Closed EJ-AIpreneur closed 1 month ago

EJ-AIpreneur commented 1 month ago

I keep getting this issue when trying to call the claude API in my code. image

However, in my Anthropic console it says that the API is working and it's logging each time I press the button to call it. I have tried numerous different variations of the code, and even tried Axios, but have had no luck stopping this error.

Here is my page.tsx where it simply calls the api with a button press: `"use client"; import React, { useState } from "react"; import { Button } from "@/components/ui/button";

export default function ClaudeInteraction() { const [responseText, setResponseText] = useState("");

const handleSubmit = async () => { try { const response = await fetch("/api/claude-api", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ message: "Hello there" }), });

  if (!response.ok) {
    throw new Error("Failed to get response from Claude API");
  }

  const data = await response.json();
  setResponseText(data.text);
} catch (error) {
  console.error("Error getting response from Claude:", error);
  setResponseText("Error: Unable to get response from Claude.");
}

};

return (

{responseText &&
Response: {responseText}
}

); }`

Here is the route.ts for the api:

`import { NextApiRequest, NextApiResponse } from 'next'; import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

export async function POST(req: NextApiRequest, res: NextApiResponse) { const { message } = req.body;

try { const result = await client.messages.create({ messages: [ { role: 'user', content: "Hello there", }, ], model: 'claude-3-haiku-20240307', max_tokens: 100, }); res.status(200).json({ text: result.content }); } catch (error) { console.error('Error fetching response:', error); res.status(500).json({ error: 'Error fetching response' }); } }`

rattrayalex commented 1 month ago

The 500 error is coming from inside your backend, not from Claude. The error from the Anthropic API will appear after this log line: Error fetching response: