I keep getting this issue when trying to call the claude API in my code.
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("");
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 });
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:
I keep getting this issue when trying to call the claude API in my code.![image](https://github.com/anthropics/anthropic-sdk-typescript/assets/143915653/d57821d7-a411-4613-b308-3168fe384557)
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" }), });
};
return (
); }`
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' }); } }`