ai.lua 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. local http = require("socket.http")
  2. local ltn12 = require("ltn12")
  3. local cjson = require("cjson")
  4. local M = {}
  5. local url = "https://api.deepseek.com/chat/completions"
  6. M.ask = function(key,content,model,is_json)
  7. -- 构造 JSON 格式的请求数据
  8. local payload = {
  9. model = model,
  10. messages = content
  11. }
  12. if is_json ~= nil and is_json == true then
  13. payload["response_format"] = {type = "json_object"}
  14. end
  15. local response_body = {}
  16. local res, code, response_headers, status = http.request{
  17. url = url,
  18. method = "POST",
  19. headers = {
  20. ["Authorization"] = "Bearer " .. key,
  21. ["Content-Type"] = "application/json",
  22. },
  23. source = ltn12.source.string(cjson.encode(payload)),
  24. sink = ltn12.sink.table(response_body)
  25. }
  26. if code == 200 then
  27. local data = cjson.decode(table.concat(response_body))
  28. return true,{content = data.choices[1].message.content,data=data}
  29. else
  30. return false, "请求失败,错误描述:" .. table.concat(response_body)
  31. end
  32. end
  33. return M