fwlua 发表于 2024-6-15 20:06:42

FastWeb实现GPT4o对话

代码比较简单,主要是两部分,一个lua代码和一个html页面,用来用户发起请求和后台处理。
利用httpclient发起一个POST请求,该请求携带了key、和对话内容,然后解析返回内容并发送给浏览器。

gpt.lua
local cjson = require("cjson")
local response = require("fastweb.response")
local request = require("fastweb.request")
local socket = require("socket")
local https = require("ssl.https")
local ltn12 = require("ltn12")

-- 配置区
local API_KEY = "你的密钥"
local ENGINE = "gpt-4"

-- 请求访问GPT
local function gpt_request(content)
    -- 创建HTTP请求的body
    local body = {
      model = ENGINE,
      messages = {
            {
                role = "system",
                content = "You are a helpful assistant."
            },
            {
                role = "user",
                content = content
            }
      }
    }
    local body_json = cjson.encode(body)

    -- 创建HTTP请求
    local url = "https://api.openai.com/v1/chat/completions"
    local response_body = {}
    local headers = {
      ["Content-Type"] = "application/json",
      ["Authorization"] = "Bearer " .. API_KEY,
      ["Content-Length"] = tostring(#body_json)
    }

    local success, status_code, headers, status_text = https.request{
      url = url,
      method = "POST",
      headers = headers,
      source = ltn12.source.string(body_json),
      sink = ltn12.sink.table(response_body),
      protocol = "tlsv1_2"
    }

    -- 检查请求是否成功
    if success and status_code == 200 then
      local response_str = table.concat(response_body)
      local response_table = cjson.decode(response_str)
      -- 返回GPT的回复内容
      return response_table.choices.message.content
    else
      return "请求失败"
    end
end

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


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

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



页: [1]
查看完整版本: FastWeb实现GPT4o对话