lua对接GPT4实现对话

演示效果:

准备材料:

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

2、一台服务器

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

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

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

gpt.lua

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

Lua 复制代码
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的格式化显示

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fast Web</title>
    <script src="js/jquery-3.4.1.min.js"></script>
    <style>
        .button-container {
            margin-bottom: 10px;
        }
        .button-container button {
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <h1>Fast Web GPT</h1>
    <form id="interceptor-form">
        <label for="send">输入提问:</label>
        <input type="text" id="send" name="send" required>
        <button type="submit">提交</button>
    </form>
    <h3>回复内容:</h3>
    <div id="markdown">
        
    </div>
   <script src="/js/marked.min.js"></script>

    <script>
        $(document).ready(function(){
            $('#interceptor-form').on('submit', function(event){
                event.preventDefault();
                var send = $('#send').val();
                var data = JSON.stringify({ content: send });

                $.ajax({
                    url: "/api/gpt.lua",
                    method: 'POST',
                    contentType: 'application/json',
                    data: data,
                    success: function(response) {
                          // 使用marked.js将Markdown转换为HTML
                        var htmlContent = marked.parse(response);
                        
                          // 将生成的HTML设置到div中
                        document.getElementById('markdown').innerHTML = htmlContent;
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        alert('请求失败: ' + textStatus + ' - ' + errorThrown);
                    }
                });
            });
        });
    </script>
    
</body>
</html>

下载地址:OpenAI-GPT - Fast Web

相关推荐
_x_w14 分钟前
【10】数据结构的矩阵与广义表篇章
开发语言·数据结构·笔记·python·线性代数·链表·矩阵
kovlistudio17 分钟前
红宝书第三十六讲:持续集成(CI)配置入门指南
开发语言·前端·javascript·ci/cd·npm·node.js
c-c-developer27 分钟前
C++Primer对象移动
开发语言·c++
牵牛老人1 小时前
Qt 元对象系统探秘:从 Q_OBJECT 到反射编程的魔法之旅
开发语言·qt
叠叠乐2 小时前
Rust 中的Relaxed 内存指令重排演示:X=0 && Y=0 是怎么出现的?
开发语言·算法·rust
SoFlu软件机器人2 小时前
高并发场景下的 Java 性能优化
java·开发语言·性能优化
ll7788112 小时前
C++学习之路,从0到精通的征途:string类的模拟实现
开发语言·数据结构·c++·学习·算法·职场和发展
green5+12 小时前
卡码网55:右旋字符串
java·开发语言
壮Sir不壮2 小时前
图论之并查集——含例题
开发语言·golang·图论
辰阳星宇2 小时前
213、【图论】有向图的完全联通(Python)
开发语言·python·图论