lua对接GPT4实现对话

作者 : admin 本文共1169个字,预计阅读时间需要3分钟 发布时间: 2024-06-9 共1人阅读

演示效果:

lua对接GPT4实现对话插图

 准备材料:

1、FastWeb网站开发服务:fwlua.com

2、一台服务器

该示例使用开源项目:fastweb 实现。

代码比较简单,主要是两部分,一个lua代码和一个html页面,用来用户发起请求和后台处理。

源码下载地址我放到文章尾部。

gpt.lua

利用httpclient发起一个POST请求,该请求携带了key、和对话内容,然后解析返回内容并发送给浏览器。

local dkjson = require("dkjson")
-- 配置区
local API_KEY = "你的密钥"
local ENGINE = "gpt-4o"
-- 请求访问GPT
function gpt_request(content)
    -- 创建HTTP客户端实例
    local client = httpclient.new()
    -- 设置超时时间
    client:set_timeout(3000,1000*60)
    -- 设置请求头
    client:request_header("Content-Type", "application/json")
    client:request_header("Authorization", "Bearer " .. API_KEY)
    -- 发起POST请求
    local url = "https://api.openai.com/v1/chat/completions"
    local body = {
        model = ENGINE,
        messages = {
          {
            role =  "system",
            content =  "You are a helpful assistant."
          },
          {
            role =  "user",
            content = content
          }
        }
    }
    local success = client:post(url, dkjson.encode(body))
    
    -- 检查请求是否成功
    if success then
        local body = dkjson.decode(client:response())
        local status_code = client:status()
        -- 返回GPT的发送内容
        return body.choices[1].message.content
    else
        return "请求失败"
    end
end


-- 获取请求参数
local content = dkjson.decode(request:body()).content
-- 发送给浏览器
response:send(gpt_request(content))

index.html

html部分就更简单了,只是一个表单提交和markdown的格式化显示




    
    
    Fast Web
    
    
        .button-container {
            margin-bottom: 10px;
        }
        .button-container button {
            margin-right: 10px;
        }
    


    

Fast Web GPT

回复内容:

下载地址:OpenAI-GPT – Fast Web

本站无任何商业行为
个人在线分享 » lua对接GPT4实现对话
E-->