· last year · Jul 08, 2024, 04:25 AM
1-- Define the URL and API key
2local url = "https://api.openai.com/v1/completions"
3local apiKey = "YOUR_API_KEY"
4
5-- Define a function to call the GPT API with tools/functions
6local function callGPTWithTools(prompt, tools, max_tokens)
7 local headers = {
8 ["Content-Type"] = "application/json",
9 ["Authorization"] = "Bearer " .. apiKey
10 }
11
12 local body = textutils.serializeJSON({
13 model = "text-davinci-003",
14 prompt = prompt,
15 max_tokens = max_tokens or 150,
16 functions = tools
17 })
18
19 -- Make the HTTP POST request
20 local response = http.post(url, body, headers)
21
22 -- Check for a successful response
23 if response then
24 local responseBody = response.readAll()
25 response.close()
26
27 -- Parse the JSON response
28 local responseTable = textutils.unserializeJSON(responseBody)
29
30 if responseTable and responseTable.choices and responseTable.choices[1] then
31 return responseTable.choices[1].text
32 else
33 return "Error: Invalid response from GPT API."
34 end
35 else
36 return "Error: Unable to connect to GPT API."
37 end
38end
39
40-- Function to prompt user and call GPT API with tools/functions
41local function main()
42 print("Enter your prompt:")
43 local prompt = read()
44
45 print("Enter max tokens (default 150):")
46 local max_tokens = tonumber(read()) or 150
47
48 -- Define your tools/functions here
49 local tools = {
50 {
51 name = "exampleFunction",
52 description = "An example function to demonstrate API usage",
53 parameters = {
54 type = "object",
55 properties = {
56 exampleParameter = {
57 type = "string",
58 description = "An example parameter for the function"
59 }
60 },
61 required = {"exampleParameter"}
62 }
63 }
64 }
65
66 local result = callGPTWithTools(prompt, tools, max_tokens)
67 print("GPT-3 Response:")
68 print(result)
69end
70
71-- Run the main function
72main()