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

相关推荐
睡美人的小仙女1273 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
rayufo3 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk3 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
缺点内向4 小时前
C#编程实战:如何为Word文档添加背景色或背景图片
开发语言·c#·自动化·word·.net
一起养小猫4 小时前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
zhougl9964 小时前
Java 所有关键字及规范分类
java·开发语言
java1234_小锋5 小时前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言
2501_944525545 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
qq_417129255 小时前
C++中的桥接模式变体
开发语言·c++·算法
开源技术5 小时前
如何将本地LLM模型与Ollama和Python集成
开发语言·python