#Gidster 4198 as someone mentioned here

1 messages · Page 1 of 1 (latest)

grim patio
#

that's the endpoint openAI is returning. my GET request is going to: '/' .

long cloudBOT
#

Do not post OpenAI API keys in chat

grim patio
#

oops

#

% curl -i -H "Accept: application/json" -H "Authorization: Bearer sk-xxxxxxxxx" -X GET https://api.openai.com/v1/chat/completions
HTTP/2 401
date: Mon, 29 May 2023 20:11:06 GMT
content-type: application/json; charset=utf-8
content-length: 146
vary: Origin
x-request-id: 87144255e6e2241b2ea791b0e86f51d6
strict-transport-security: max-age=15724800; includeSubDomains
cf-cache-status: DYNAMIC
server: cloudflare
cf-ray: 7cf162765cbf96ef-SJC
alt-svc: h3=":443"; ma=86400

{
"error": {
"message": "",
"type": "invalid_request_error",
"param": null,
"code": "invalid_api_key"
}
}

oak larkBOT
grim patio
#

right. the mystery is, why aren't my API keys being recognized as valid?

#

% curl -i -H "Accept: application/json" -H "Authorization: Bearer sk-Zdxxxxxxxxxxxx" -H "model:gpt-3.5" -X GET https://api.openai.com/v1/chat/completions
HTTP/2 400
date: Mon, 29 May 2023 20:21:28 GMT
content-type: application/json; charset=utf-8
content-length: 167
vary: Origin
x-request-id: d0a4140095cf07b9deb6881a08ff35a3
strict-transport-security: max-age=15724800; includeSubDomains
cf-cache-status: DYNAMIC
server: cloudflare
cf-ray: 7cf171a3cce3172a-SJC
alt-svc: h3=":443"; ma=86400

{
"error": {
"message": "you must provide a model parameter",
"type": "invalid_request_error",
"param": null,
"code": null
}
}

silver gulch
#

@grim patio ignore @oak lark , it's a bot.
(CC @soft oasis )

oak larkBOT
#

Stowpped genewating mastew~

silver gulch
#

@grim patio GET requests to api.openai.com/v1/ will always return an error, there is no API endpoint with this URI.

silver gulch
#

Your request is not complete.

grim patio
grim patio
silver gulch
#

Look at your code and the example from the documentation I shared here. See if you can spot the difference. If not, I will tell you.

grim patio
silver gulch
#

No, the model and other information should be passed in the request body and not as headers.

#

Again, check the example from the documentation.

grim patio
#

ahhh ok!

grim patio
#

here is my server.js file: ```
import express from 'express';
import * as dotenv from 'dotenv';
import cors from 'cors';
import { Configuration, OpenAIApi } from 'openai';

dotenv.config();

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

});

const openai = new OpenAIApi(configuration);

// console.log(openai)

const app = express();
app.use(cors());
app.use(express.json());

app.get('/', async (req, res) => {
res.status(200).send({
message: 'Hello from CodeX',
})
});

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

    const response = await openai.createCompletion({
        model: "gpt-3.5-turbo",
        message:[
            {
                role: "user", 
                content: '${prompt}',
            },
        ],
        
        temperature: 0, //temperature determines level of risk the AI can take in terms of giving information it already knows or searching for new information
        max_tokens: 3000, //max number of characters to generate in a complete answer
        top_p: 1,
        frequency_penalty: 0.5, //determines how repetitive AI can be in its answers
        presence_penalty: 0, //determines how much AI can talk about topics that are not in the prompt
    });

    res.status(200).send({
        bot: response.data.choices[0].text
    })
    } catch (error) {
        console.log(error);
        res.status(500).send({ error })
    }
})

app.listen(5000, () => console.log('Server is running on port http://127.0.0.1:5000'));```

silver gulch
#

Let me be more direct: the parameters used in the cURL request you shared here are wrong.

#

The OpenAI API will NOT work with those parameters because you can't inform the model in the header.

grim patio
#

here is my script.js file: ```
import bot from './assets/bot.svg';
import user from './assets/user.svg';

const form = document.querySelector('form');
const chat_container = document.querySelector('#chat_container');

let loadInterval;

function loader(element) {
element.textContent = ''

loadInterval = setInterval(() => {
element.textContent += '.';

if (element.textContent === '....') {
  element.textContent = '';
}

},300)
}

function typeText(element, text) {
let index = 0

let interval = setInterval(() => {
if (index < text.length) {
element.innerHTML += text.charAt(index)
index++
} else {
clearInterval(interval)
}
}, 20)
}

silver gulch
#

Regarding your javascript code, what is the error you are receiving?

grim patio
#
function generateUniqueId() {
  const timestamp = Date.now();
  const randomNumber = Math.random();
  const hexadecimalString = randomNumber.toString(16);

  return `id-${timestamp}-${hexadecimalString}`
}

function chatStripe (isAi, value, uniqueId) {
  return (
    `
      <div class="wrapper ${isAi && 'ai'}">
        <div class="chat">
          <div class="profile">
            <img
              src= ${isAi ? bot : user}
              alt="${isAi ? 'bot' : 'user'}"
            />
            </div>
            <div class="message" id=${uniqueId}>${value}</div>
          </div>
        </div>
      
    `
  )
}

const handleSubmit = async (e) => {
  e.preventDefault();

  const data = new FormData(form);

  //user's chatstripe
  chat_container.innerHTML += chatStripe(false, data.get('prompt'));

  form.reset();

  //bot's chatstripe
  const uniqueId = generateUniqueId();
  chat_container.innerHTML += chatStripe(true, " ", uniqueId);

  chat_container.scrollTop = chat_container.scrollHeight;

  const messageDiv = document.getElementById(uniqueId);

  loader(messageDiv)

  const response = await fetch('http://127.0.0.1:5000/ ', {
        method: 'POST',
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer sk-1Xxxxxxxxxxxxxxx",
            "Organization": "org-xxxxxxxx",
            "Access-Control-Allow-Origin":"*" 
        },
        body: JSON.stringify({
            prompt: data.get('prompt')
        })
    })


    clearInterval(loadInterval)
    messageDiv.innerHTML = " "

    if (response.ok) {
      const data = await response.json();
      const parsedData = data.bot.trim()

      typeText(messageDiv, parsedData) 
    } else {
        const err = await response.text()

        messageDiv.innerHTML = "Something went wrong"
        alert(err)
      }
    }
  
form.addEventListener('submit', handleSubmit);
form.addEventListener('keyup', (e) => {
  if (e.keyCode === 13) {
    handleSubmit(e);
  }
})```
silver gulch
#

Hold on mate, what is the error you are receiving from your js code?

grim patio
#

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

silver gulch
#

No line where it is failing?

grim patio
#

that's the only error. it seems to me the error is coming from the source, not from my code. my app was working initially, then it wasn't. same with two other applications using the openAI api.

grim patio
#
Server is running on port http://127.0.0.1:5000
Error: Request failed with status code 401
    at createError (/Users/gideoncrawley/Projects/openAI_codex/server/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/Users/gideoncrawley/Projects/openAI_codex/server/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/Users/gideoncrawley/Projects/openAI_codex/server/node_modules/axios/lib/adapters/http.js:322:11)
    at IncomingMessage.emit (node:events:539:35)
    at endReadableNT (node:internal/streams/readable:1342:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      'User-Agent': 'OpenAI/NodeJS/3.2.1',
      Authorization: 'Bearer undefined',
      'Content-Length': 164
    },
    method: 'post',
    data: '{"model":"gpt-3.5-turbo","message":[{"role":"user","content":"${prompt}"}],"temperature":0,"max_tokens":3000,"top_p":1,"frequency_penalty":0.5,"presence_penalty":0}',
    url: 'https://api.openai.com/v1/completions'
  },```
#

'Authorization: 'Bearer undefined'. the problem is that my api keys are not being honored. what i don't know is why.

silver gulch
#

Authorization: 'Bearer undefined',
I don't know your app but it seems you have an issue here

grim patio
#

i do indeed.

#

but it's not just this app. it's everything and anything i've built using the openai api! this app i'm showing you was working, exactly as is, and then it wasn't.

#

same for the others.

silver gulch
#

You have:

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

Is it possible that you forgot to set an environment variable with your OpenAPI key before you started the apps?

grim patio
#

nope. it's in the .env file

hardy python
#

Let's backtrack a bit. Why don't you go to the API reference page and manually construct a complete CURL request on your own, following their example, and run that? Every example I've seen you paste so far has had part of it missing, but you keep changing which part.

#

curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "text-davinci-003", "prompt": "Say this is a test", "max_tokens": 7, "temperature": 0 }'