Is the Dalle-2 api key generated in separate part of the OpenAI site

Hi there. This might sound like a daft question, but are dalle-2 api keys generated on the same page as the gpt models?

Why I ask is I’ve followed along with 1 of Adrian Hajdin’s lectures where we Build and Deploy a Full Stack MERN AI Image Generation App using OpenAI’s Dalle-2 api. The api I generated for my gpt app works perfectly, but after generating a seperate api for Dalle-2, my app is returning errors namely:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)
SyntaxError: Unexpected token ‘I’, "Incorrect "… is not valid JSON

I’ve had a look at my code and everything seems fine. Was thinking that maybe the api key for dalle-2 is obtained somewhere else? If the api key is obtained in the same place, then it could be my cluster on mongodb giving the issue.

1 Like

API keys are the same. Seems like there’s something wrong in your request? Can you post code?

1 Like

Hi Paul,

I’ve got quite a number of files which make up the app so far, but I’ll share the one’s I think could be causing the issue. Unfortunately Adrian does not respond directly to errors people are having with regards to the app on his youtube, github or javascript mastery website, so I’m left to figure this one out for myself. I did find that when installing vite on top of node, there were warnings of some moderate issues that were returned after installation, but that had more to do with fonts etc. and not the inner workings of the project. Here are the client side files I think could be related to the problem I’m having:

CreatePost.jsx:

import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'

import { preview } from '../assets';
import { getRandomPrompt } from '../utils';
import { FormField, Loader } from '../components';


const CreatePost = () => {
  const navigate = useNavigate();
  const [form, setForm] = useState({
    name: '',
    prompt: '',
    photo: '',
  });

  const [generatingImg, setGeneratingImg] = useState(false);
  const [loading, setLoading] = useState(false);

  const generateImage = async () => {
  if (form.prompt) {
      try {
        setGeneratingImg(true);
        const response = await fetch('http://localhost:8080/api/v1/dalle', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            prompt: form.prompt,
          }),
      })
    
      const data = await response.json();

    setForm({ ...form, photo: `data:image/jpeg;base64,${data.photo}` })
  } catch (error) {
    alert(error);
  } finally {
    setGeneratingImg(false);
  }
} else {
  alert('Please enter a prompt')
}
}

  const handleSubmit = () => {

  }

  const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value })
  }

  const handleSurpriseMe = () => {
    const randomPrompt = getRandomPrompt(form.prompt);
    setForm({ ...form, prompt: randomPrompt })
  }
  
  return (
    <section className="max-w-7xl mx-auto">
      <div>
        <h1 className="font-extrabold text-[#222328] text-[32px]">Create</h1>
        <p className="mt-2 text-[#666e75] text-[14px] max-w-[500px]">Create imaginative and visually stunning images with DALL-E AI and share them with the community</p>
      </div>

      <form className="mt-16 max-w-3xl" onSubmit={handleSubmit}>
      <div className="flex flex-col gap-5">
      <FormField
            labelName="Your name"
            type="text"
            name="name"
            placeholder="Ex., John Doe"
            value={form.name}
            handleChange={handleChange}
          />
          <FormField
            labelName="Prompt"
            type="text"
            name="prompt"
            placeholder="A man standing in front of a stargate to another dimension"
            value={form.prompt}
            handleChange={handleChange}
            isSurpriseMe
            handleSurpriseMe={handleSurpriseMe}
          />
          <div className="relative bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 w-64 p-3 h-64 flex justify-center items-center">
          { form.photo ? (
              <img
                src={form.photo}
                alt={form.prompt}
                className="w-full h-full object-contain"
              />
            ) : (
              <img
                src={preview}
                alt="preview"
                className="w-9/12 h-9/12 object-contain opacity-40"
              />
            )}

            {generatingImg && (
              <div className="absolute inset-0 z-0 flex justify-center items-center bg-[rgba(0,0,0,0.5)] rounded-lg">
                <Loader />
              </div>
            )}
          </div>
      </div>

      <div className="mt-5 flex gap-5">
          <button
            type="button"
            onClick={generateImage}
            className=" text-white bg-green-700 font-medium rounded-md text-sm w-full sm:w-auto px-5 py-2.5 text-center"
          >
            {generatingImg ? 'Generating...' : 'Generate'}
          </button>
        </div>

        <div className="mt-10">
          <p className="mt-2 text-[#666e75] text-[14px]">** Once you have created the image you want, you can share it with others in the community **</p>
          <button
            type="submit"
            className="mt-3 text-white bg-[#6469ff] font-medium rounded-md text-sm w-full sm:w-auto px-5 py-2.5 text-center"
          >
            {loading ? 'Sharing...' : 'Share with the Community'}
          </button>
        </div>
      </form>
    </section>
  )
}

export default CreatePost

App.jsx:

import React from 'react'
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';

import { logo } from './assets';
import { Home, CreatePost } from './pages';

const App = () => {
  return (
    <BrowserRouter>
      <header className="w-full flex justify-between items-center bg-white sm:px-8 px-4 py-4 border-b border-b-[#e6ebf4]">
    <Link to="/">
      <img src={logo} alt="logo" className="w-28 object-contain" />
    </Link>

    <Link to="/create-post" className="font-inter font-medium bg-[#6469ff] text-white px-4 py-2 rounded-md">Create</Link>

    </header>
    <main className="sm:p-8 px-4 py-8 w-full bg-[#f9fafe] min-h-[calc(100vh-73px)]">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/create-post" element={<CreatePost />} />
      </Routes>
    </main>
    
    
    
    </BrowserRouter>
  )
}

export default App

The following is from the server side:

connect.js:

import mongoose from 'mongoose';

const connectDB = (url) => {
    mongoose.set('strictQuery', true);

    mongoose.connect(url)
    .then(() => console.log('MongoDB connected'))
    .catch((err) => console.log(err));
}

export default connectDB;

dalleRoutes.js:

import express from 'express';
import * as dotenv from 'dotenv';
import { Configuration, OpenAIApi } from 'openai';

dotenv.config();

const router = express.Router();

const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY,
  });

  const openai = new OpenAIApi(configuration);

  router.route('/').get((req, res) => {
    res.send('Hello from DALL-E!');
  });

  router.route('/').post(async (req, res) => {
    try {
      const { prompt } = req.body;

      const aiResponse = await openai.createImage({
        prompt,
        n: 1,
        size: '1024x1024',
        response_format: 'b64_json',
      });

      const image = aiResponse.data.data[0].b64_json;
    
      res.status(200).json({ photo: image });
    } catch (error) {
        console.log(error);
         res.status(500).send(error?.response.data.error.message)
  }

      })

  export default router;

index.js:

import express from 'express';
import * as dotenv from 'dotenv';
import cors from 'cors';

import connectDB from './mongodb/connect.js';
import postRoutes from './routes/postRoutes.js';
import dalleRoutes from './routes/dalleRoutes.js';

dotenv.config();

const app = express();
app.use(cors());
app.use(express.json({ limit: '50mb' }));

app.use('/api/v1/post', postRoutes);
app.use('/api/v1/dalle', dalleRoutes);

app.get('/', async (req, res) => {
    res.send('Hello from DALL.E!');
    })

const startServer = async () => {
  try {
    connectDB(process.env.MONGODB_URL);
    app.listen(8080, () => console.log('Server has started on port:8080'))
  } catch (error) {
    console.log(error);
  }
  }
  
startServer();

The above code and files are where I think the error could be if any. I also have reason to believe it could be my database cluster on mongodb. I wonder if I should delete the current cluster, create a new one and try to connect to that one. Currently the return I’m getting is that I’m connecting with my mongo cluster with no issue. Hopefully you can make sense of what is going on. Let me know if you need other files.

Thanks in advance.