-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai_api.gd
73 lines (54 loc) · 1.61 KB
/
ai_api.gd
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
extends HTTPRequest
signal responded(text)
var api_key = "" #API KEY FROM ON GROQ
const GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
var url = GROQ_URL
var model = "llama3-70b-8192"
var temperature = 0.5
var max_tokens = 8192
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
pass # Replace with function body.
func set_api_key(_api_key):
api_key = _api_key
func make_message(text, role="user"):
return {
"role": role,
"content": text
}
func send_messages(messages):
var body = JSON.new().stringify({
"messages": messages,
"temperature": 0.6,
"frequency_penalty": 0.1,
"presence_penalty": 0.1,
"max_tokens": 4096,
"model":model,
"stream":false
})
send_request(GROQ_URL, get_headers(), body)
func send_text(text):
send_messages([make_message(text)])
##
func _on_request_complited(result, response_code, headers, body):
print("Responded")
print(result)
print(headers)
print(body.get_string_from_utf8())
if response_code == 200:
var response = JSON.parse_string(body.get_string_from_utf8())
var message = response["choices"][0]["message"]["content"]
emit_signal("responded", message)
else:
emit_signal("responded", "Error")
##
func get_headers():
var headers = ["Content-type: application/json", "Authorization: Bearer " + api_key]
return headers
func send_request(url, headers, body):
print("sending request")
request_completed.connect(_on_request_complited)
var send_request = request(url, headers, HTTPClient.METHOD_POST, body) # what do we want to connect to
if send_request != OK:
print("ERROR sending request")
pass