Integrate with Express. Help!

Hey guys, I need some help integrating the following code with Express:

import { Configuration, OpenAIApi } from 'openai';

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createImage({
  prompt: prompt("Describe the image you want"),
  n: 1,
  size: "1024x1024",
});

console.log(response.data.data[0].url)

Help will be greatly appreciated!

Could you please send a link to the Repl?

Found it on @NateDhaliwal’s profile: https://replit.com/@NateDhaliwal#index.js

1 Like

Could you describe what you want to do in more detail? Do you want to put the result in a webpage?

1 Like

Also, replace line 1 with the code below as the import command will raise an error in node.

const { Configuration, OpenAIApi } = require("openai");

Now, I got:

/home/runner/Dall-E-Express/index.js:7
const response = await openai.createImage({
                 ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules

It’s only valid in async functions, like the error said.

What should I change?

Remove await. Also, what do you mean by “Integrate into Express”?

I want the user to be able to enter the image they want (using prompt( )), and the image displayed in the HTML page.

When I remove ‘await’, I get this:
TypeError: openai.createImage is not a constructor at Object.<anonymous> (/home/runner/Dall-E-Express/index.js:7:18) at Module._compile (node:internal/modules/cjs/loader:1159:14)

You can use requests for this, or sockets (which is longer but simpler). Which one do you prefer?

1 Like

BTW, you can’t use prompt() in Node.

1 Like

Requests ig? It should be ok…

See this tutorial in Dall-E image generation. Your code is probably outdated.

1 Like

I tried it but where do I put the API key?

import openai
response = openai.Image.create(
  prompt="a white siamese cat",
  n=1,
  size="1024x1024"
)
image_url = response['data'][0]['url']

The api key must be inserted into the openai.api_key variable.

openai.api_key = 'API key'
1 Like

And make sure you put it into a secret in Replit

2 Likes

use const { question: prompt } = require('readline-sync');. Will give you the same effect

@NateDhaliwal do you still need help with this?