I’ve been trying to implement a basic prompt into a 2D side-scroller I’m playing around with. I’m doing this through Repl.it and haven’t had issues with deploys before, but not sure why it’s having an issue generating the prompt. I’ve messed around with the url testing with local:3000 and then the deployed server link, both of which do make the call, but fail to actually generate the text on the front end.
The key seems to work fine, and the payload is received in the network tab, but failing soon after with a ‘failed to fetch’ for the generate-text. Any advice would be greatly appreciated!
import OpenAI from 'openai';
import dotenv from 'dotenv';
import cors from 'cors';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
app.use(cors());
app.use(express.json());
app.options('/generate-dialogue', cors()); // Enable pre-flight requests for CORS
app.post('/generate-dialogue', async (req, res) => {
const { prompt } = req.body;
const openai = new OpenAI({
apiKey: OPENAI_API_KEY,
});
try {
const response = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: prompt }
],
max_tokens: 50
});
res.json(response);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Something went wrong');
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
```async function updateDialogue() {
console.log('updateDialogue called');
try {
const response = await fetch('https://EsteraJablonski.Test-Game.repl.co/generate-dialogue', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: 'Generate a random phrase or fact about love: ',
max_tokens: 50
})
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log('API Response:', data);
if (data.choices && data.choices.length > 0) {
console.log('Setting text:', data.choices[0].text.trim());
dialogueText.setText(data.choices[0].text.trim());
}
} catch (error) {
console.error('Error:', error);
}
}