Reputation: 23
I have a simple react app to generate images using openai api as follows.
`
import logo from './logo.svg';
import './App.css';
import { useState } from "react";
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
function App() {
const [userPrompt, setUserPrompt] = useState("")
const [imageUrl, setImageUrl] = useState("")
const generateImage = async () => {
const imageParameters = {
prompt: userPrompt,
n:1,
size: "256x256",
}
const response = await openai.createImage(imageParameters);
const urlData = response.data.data[0].url;
console.log("urlData =",urlData);
setImageUrl(urlData);
}
return (
<div className="App">
{
imageUrl
? <img src={imageUrl} className="image" alt="ai thing" />
: <img src={logo} className="image" alt="logo" />
}
<p>Generate a unique image using DALL·E</p>
<p>What do you want to see?</p>
<input
placeholder='A sunset on the Sydney Opera House'
onChange={(e) => setUserPrompt(e.target.value)}
/>
<button onClick={() => generateImage()}>Generate</button>
</div>
);
}
export default App;
`
The API KEY is inside .env file and is correct. However, when I click on generate button, it throws error on console like below:
I tried to create a react-app using DALL-E API to generate images using this guide. I am not able to receive (image) a response message after api call/request is made.
Upvotes: 2
Views: 4739
Reputation: 459
Here an ES6 NodeJs example that works and saves a PNG file. To get it to work add "type": "module", on top of your package.json. The request to the OpenAi returns you an array of urls to the png files. The "n" in the createImage is the number of the images in the array.
import { Configuration, OpenAIApi } from "openai";
import http from "https"; // or 'https' for https:// URLs
import fs from "fs";
const configuration = new Configuration({
apiKey: OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createImage({
prompt: "A cute baby sea otter",
n: 1,
size: "1024x1024",
});
const file = fs.createWriteStream("test.png");
const request = http.get(response.data.data[0].url, function (response) {
response.pipe(file);
file.on("finish", () => {
file.close();
console.log("Download Done!");
});
});
Upvotes: 1
Reputation: 1784
wrap this call to createImage() within a try/catch and print the error in your catch block
const response = await openai.createImage(imageParameters);
Upvotes: 0