簡體   English   中英

OpenAI API 密鑰正確時返回“未授權”錯誤

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

我在 Lua 中編寫了一個 Discord 機器人程序,我認為以某種方式實現 OpenAI 的 api 會很有趣,除了我不斷收到 401 錯誤外,我一切正常。 這是我的代碼的一部分

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)()

“密鑰”是我從網站上獲得的 API 密鑰。 我覺得這個錯誤很簡單而且很愚蠢,但無論如何我都被卡住了

這是很好的代碼,盡管我會在您驗證代碼之前對類型進行一些檢查。

這背后的另一個原因是,某些域可能需要代理而不是直接連接。

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM