forked from drewbaumann/AskGPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpt_query.lua
38 lines (30 loc) · 933 Bytes
/
gpt_query.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
local API_KEY = require("api_key")
local https = require("ssl.https")
local ltn12 = require("ltn12")
local json = require("json")
local function queryChatGPT(message_history)
local api_key = API_KEY.key
local api_url = "https://api.openai.com/v1/chat/completions"
local headers = {
["Content-Type"] = "application/json",
["Authorization"] = "Bearer " .. api_key,
}
local requestBody = json.encode({
model = "gpt-3.5-turbo",
messages = message_history,
})
local responseBody = {}
local res, code, responseHeaders = https.request {
url = api_url,
method = "POST",
headers = headers,
source = ltn12.source.string(requestBody),
sink = ltn12.sink.table(responseBody),
}
if code ~= 200 then
error("Error querying ChatGPT API: " .. code)
end
local response = json.decode(table.concat(responseBody))
return response.choices[1].message.content
end
return queryChatGPT