Error : Could not load data:image/png;base64,undefined: undefined

Problem

I think I have not properly migrated to OpenAI v4,
I could use some help make it work.

the errors I’m getting are:

  • POST http://localhost:8080/api/v1/dalle 500 (Internal Server Error)
  • Error: Could not load data:image/png;base64,undefined: undefined
    at chunk-NSXAVJG4.js?v=007676ee:17070:39
    at HTMLImageElement.onImageError (chunk-7Z2GYTU5.js?v=007676ee:26069:20)

Code

// this is created using v4 of OpenAI API

import express from "express";
import * as dotenv from "dotenv";
import OpenAI from "openai";

dotenv.config();

const router = express.Router();

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

router.route("/").get((req, res) => {
  res.status(200).json({ message: "Hello from DALL-E routes" });
});

// posting image to front-end app
router.route("/").post(async (req, res) => {
  try {
    const { prompt } = req.body;
    const aiResponse = await openai.images.generate({
      model: "dall-e-3",
      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.error(error);
    res.status(500).json({ message: "Something went wrong" });
  }
});

export default router;

It sounds like you might be discussing a node.js SDK “version” of OpenAI’s, but then you talk about a URL, which is not employed by calls to the library.

The correct URL for images is https://api.openai.com/v1/images/generations, so somebody or somebody’s AI has led you astray. You can consult the API reference to read how to make calls to generate images.

POST https://api.openai.com/v1/images/generations 401 (Unauthorized)

##file: server/routes/dalle.routes.js

import express from "express";
import OpenAI from "openai";
import * as dotenv from "dotenv";

dotenv.config();

const router = express.Router();

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

router.route("/").get((req, res) => {
  res.status(200).json({ message: "Hello from DALL-E routes" });
});

// Posting image to front-end app
router.route("/").post(async (req, res) => {
  try {
    const { prompt } = req.body;
    const aiResponse = await openai.images.generate({
      model: "dall-e-3",
      prompt,
      n: 1,
      size: "1024x1024",
      response_format: "b64_json",
    });
    const image = aiResponse.data[0].url;
    res.status(200).json({ photo: image });
  } catch (error) {
    console.error("Error generating image: ", error.message);
    res.status(500).json({ message: "Something went wrong" });
  }
});

export default router;

##file: client/src/pages/customizer.jsx

  // function for AI Picker for generating image
  const handleSubmit = async (type) => {
    if (!prompt) return alert("Please enter a prompt");

    try {
      setGeneratingImg(true);
      
      const response = await fetch('https://api.openai.com/v1/images/generations', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          prompt,
        })
      })

      const data = await response.json();
      if (data.photo) {
        handleDecals(type, `data:image/png;base64,${data.photo}`);
      } else {
        throw new Error("Image data not found in response");
      }
    } catch (error) {
      alert(error.message);
    } finally {
      setGeneratingImg(false);
      setActiveEditorTab("");
    }
  };

I have created ApiKey using user and project format.

also in documentation here is this line:
Authorization: Bearer OPENAI_API_KEY

&

import OpenAI from “openai”;

const openai = new OpenAI({
organization: “org-K75kgQRFNvP4c1IqfgMqS1rG”,
project: “$PROJECT_ID”,
});

how can I use them

[Link to repo](https://github.com/Shaheer5/threejs-shirt)

A “user” API key is the classic standard API key that has no limitations on use when it is used on your default organization or one of which you are a member by invitation. It should be called “superuser” api key or “do anything” key, not one you would give to a user.

Projects was introduced a few months ago, a poor name for “scoped keys with limits”. You cannot force an organization member to use them, so inviting people to your organization is still a big problem.

You can generate API keys in projects you create, which can be limited to endpoints, and projects limited by models and usage amounts. That is a good idea for new use, to shut off anything not used to limit the exposure if a key were to be leaked or abused.

If you generate a project key, you should not need to employ an organization ID nor project ID in API calls. The API key is your authentication method, and should be loaded from an environment variable, not hard-coded or in config files.

To demonstrate you have it working, you can make API calls to one of the simpler endpoints, like models, to list the models you have access to, and then can orient yourself to parsing JSON you’ll get back or which SDKs return.

I have created new account of openai and created apikey using that account, and its neither expired nor reached the credit limit, but why I am still getting 401 unauthorized error at front-end and the error below at the node back-end

code: 'billing_hard_limit_reached',
    message: 'Billing hard limit has been reached',
    param: null,
    type: 'invalid_request_error'

“Hard limit” is the monthly limit setting that you place on a project or your whole account.

If you set it to $5, and you’ve consumed $5 this month, you are denied.

The organization monthly budget setting is near the bottom of this page:

https://platform.openai.com/settings/organization/limits

You will need to navigate to limits of your projects yourself and see what you have set.


A truly new account must be funded with prepayment of credits, waiting a bit for them to take effect, and you should generate your first API key under “user API keys” to see if you will be required to do phone verification.