API call URL error

Hello! I am currently in the process of setting up the api calls and routing for one of my projects, but am running into an error.
When i run the following code:

Code

app.post(‘/api/calculate’, authenticateToken, async (req, res) => {
try {

const hfResponse = await fetch('https://api-inference.huggingface.co/models/gpt2', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.HUGGINGFACE_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify("Hello World!")
});

if (!hfResponse.ok) {
  const errorText = await hfResponse.text();
  console.error(`HF API error: ${hfResponse.status} ${errorText}`);
  return res.status(hfResponse.status).json({ error: errorText });
}

const result = await hfResponse.json();
const text = Array.isArray(result) ? result[0]?.generated_text : result.generated_text;

res.json({ recommendations: text });

} catch (err) {
console.error(‘Fetch failed:’, err);
res.status(500).json({ error: ‘Failed to get AI response’ });
}
});

It gives me the following error:
HF API error: 404 Not Found

I have checked and my API token seems to be working and gpt2 should be available to my free account. The API token exists in a seperate .env file that is in the same folder as the code was run in.

Is it an error with my URL? I’ve tried some other variations but everything has returned the same result. Please help me troubleshoot. Thank you so much!

1 Like

There are two problems. One is that the URL for the request is probably wrong. The other is that it may not have been deployed, so I don’t know if it can be used…

I think it can be used with the deployed model…

// https://api-inference.huggingface.co/models/gpt2
https://router.huggingface.co/hf-inference/models/openai-community/gpt2/v1/chat/completions

One of deployed models: