ai.lua 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. local http = require("socket.http")
  2. local ltn12 = require("ltn12")
  3. local cjson = require("cjson")
  4. local M = {}
  5. local url = "https://dashscope.aliyuncs.com/compatible-mode/v1/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. M.ask_local = function(url,content,model)
  34. -- 构造 JSON 格式的请求数据
  35. local payload = {
  36. model = model,
  37. messages = content,
  38. stream = false
  39. }
  40. local response_body = {}
  41. local res, code, response_headers, status = http.request{
  42. url = url,
  43. method = "POST",
  44. headers = {
  45. ["Content-Type"] = "application/json",
  46. },
  47. source = ltn12.source.string(cjson.encode(payload)),
  48. sink = ltn12.sink.table(response_body)
  49. }
  50. if code == 200 then
  51. local data = cjson.decode(table.concat(response_body))
  52. return true,{content = data.message.content,data=data}
  53. else
  54. return false, "请求失败,错误描述:" .. table.concat(response_body)
  55. end
  56. end
  57. return M