首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当密钥正确时,OpenAI API返回一个“未经授权”的错误。

当密钥正确时,OpenAI API返回一个“未经授权”的错误。
EN

Stack Overflow用户
提问于 2022-09-27 19:13:29
回答 1查看 149关注 0票数 0

我在Lua中编写了一个不和谐的机器人,我认为以某种方式实现OpenAI的api会很有趣,除了我一直有401错误之外,我已经做好了所有的事情。这是我的代码的一部分

代码语言:javascript
复制
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密钥。我觉得这个错误是简单而愚蠢的,但不管我被困在哪里

EN

回答 1

Stack Overflow用户

发布于 2022-09-27 22:38:18

这是很好的代码,不过在您验证代码之前,我会对这些类型做一些检查。

这背后的另一个原因是,某些域可能需要代理而不是直接连接。

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73872748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档