-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
gpt_query.lua
75 lines (61 loc) · 2.16 KB
/
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
local api_key = nil
local CONFIGURATION = nil
-- Attempt to load the api_key module. IN A LATER VERSION, THIS WILL BE REMOVED
local success, result = pcall(function() return require("api_key") end)
if success then
api_key = result.key
else
print("api_key.lua not found, skipping...")
end
-- Attempt to load the configuration module
success, result = pcall(function() return require("configuration") end)
if success then
CONFIGURATION = result
else
print("configuration.lua not found, skipping...")
end
-- Define your queryChatGPT function
local https = require("ssl.https")
local http = require("socket.http")
local ltn12 = require("ltn12")
local json = require("json")
local function queryChatGPT(message_history)
-- Use api_key from CONFIGURATION or fallback to the api_key module
local api_key_value = CONFIGURATION and CONFIGURATION.api_key or api_key
local api_url = CONFIGURATION and CONFIGURATION.base_url or "https://api.openai.com/v1/chat/completions"
local model = CONFIGURATION and CONFIGURATION.model or "gpt-4o-mini"
-- Determine whether to use http or https
local request_library = api_url:match("^https://") and https or http
-- Start building the request body
local requestBodyTable = {
model = model,
messages = message_history,
}
-- Add additional parameters if they exist
if CONFIGURATION and CONFIGURATION.additional_parameters then
for key, value in pairs(CONFIGURATION.additional_parameters) do
requestBodyTable[key] = value
end
end
-- Encode the request body as JSON
local requestBody = json.encode(requestBodyTable)
local headers = {
["Content-Type"] = "application/json",
["Authorization"] = "Bearer " .. api_key_value,
}
local responseBody = {}
-- Make the HTTP/HTTPS request
local res, code, responseHeaders = request_library.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