| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- local http = require("socket.http")
- local ltn12 = require("ltn12")
- local cjson = require("cjson")
- local M = {}
- local url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
- M.ask = function(key,content,model,is_json)
- -- 构造 JSON 格式的请求数据
- local payload = {
- model = model,
- messages = content,
- }
- if is_json ~= nil and is_json == true then
- payload["response_format"] = {type = "json_object"}
- end
- local response_body = {}
- local res, code, response_headers, status = http.request{
- url = url,
- method = "POST",
- headers = {
- ["Authorization"] = "Bearer " .. key,
- ["Content-Type"] = "application/json",
- },
- source = ltn12.source.string(cjson.encode(payload)),
- sink = ltn12.sink.table(response_body)
- }
- if code == 200 then
- local data = cjson.decode(table.concat(response_body))
- return true,{content = data.choices[1].message.content,data=data}
- else
- return false, "请求失败,错误描述:" .. table.concat(response_body)
- end
- end
- M.ask_local = function(url,content,model)
- -- 构造 JSON 格式的请求数据
- local payload = {
- model = model,
- messages = content,
- stream = false
- }
- local response_body = {}
- local res, code, response_headers, status = http.request{
- url = url,
- method = "POST",
- headers = {
- ["Content-Type"] = "application/json",
- },
- source = ltn12.source.string(cjson.encode(payload)),
- sink = ltn12.sink.table(response_body)
- }
- if code == 200 then
- local data = cjson.decode(table.concat(response_body))
- return true,{content = data.message.content,data=data}
- else
- return false, "请求失败,错误描述:" .. table.concat(response_body)
- end
- end
- return M
|