简体   繁体   中英

OpenAI API returns an "unauthorized" error when the key is correct

I'm coding a Discord bot in Lua and I thought it would be fun to implement OpenAI's api somehow, and I've got everything right except I keep getting a 401 error. Here's a portion of my code

coroutine.wrap(function()
    local s,e = pcall(function()
        local Headers = {
            ["Authorization"] = "Bearer "..key,
            ["Content-Type"] = "application/json",
        }

        local Body = json.encode({
            model = "text-davinci-002",
            prompt = "Human: ".. table.concat(Args, " ") .. "\n\nAI:",
            temperature = 0.9,
            max_tokens = 47, --150
            top_p = 1,
            frequency_penalty = 0.0,
            presence_penalty = 0.6,
            stop = {" Human:", " AI:"}
        })
    
        res,body = coro.request("POST", link, Headers, Body, 5000)

        if res == nil then
            Message:reply("didnt return anything")
            return
        end
        
        if res.code < 200 or res.code >= 300 then
            Message:reply("Failed to send request: " .. res.reason); return --Always ends up here "Failed to send request: Unauthorized"
        end

        Message:reply("Request sent successfully!")
    end)
end)()

The "key" is the API key I got from the website . I feel like the mistake is simple and stupid but regardless I'm stuck

It's good code, though I'd do some checks on the types before you validate the codes.

Another reason behind this, is some domains may require a proxy rather than a direct connection.

coroutine.resume(coroutine.create(function()
    local headers = {
        Authorization = "Bearer " .. key,
        ["Content-Type"] = "application/json",
    }
    local body = json.encode({
        model = "text-davinci-002",
        prompt = "Human: " .. table.concat(Args, " ") .. "\n\nAI:",
        temperature = 0.9,
        max_tokens = 47, --150
        top_p = 1,
        frequency_penalty = 0.0,
        presence_penalty = 0.6,
        stop = { " Human:", " AI:" },
    })
    local success, http_result, http_body = pcall(coro.request, "POST", link, headers, body, 5e3)
    if success ~= true then
        return error(http_result, 0)
    elseif type(http_result) == "table" and type(http_result.code) == "number" and http_result.code < 200 or http_result.code >= 300 then
        return Message:reply("Failed to send request: " .. type(http_result.reason) == "string" and http_result.reason or "No reason provided.")
    end
    return Message:reply("Request sent successfully!")
end))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM