Skip to content

Commit f7ca2f1

Browse files
committed
Add ChatGPT example
1 parent 899a466 commit f7ca2f1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

examples/forms/chatgpt.own

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
use std, okhttp, json, forms
2+
3+
OPENAI_API_KEY=getenv("OPENAI_API_KEY", "your-api-key")
4+
CONTENT_TYPE = "application/json; charset=utf-8"
5+
6+
chatHistory = newLabel("<html>ChatGPT<br>")
7+
messageField = newTextField()
8+
sendButton = newButton("Send")
9+
10+
messageField.onAction(::onSend)
11+
sendButton.onClick(::onSend)
12+
def onSend() {
13+
text = messageField.getText()
14+
if (length(text) == 0) return 0
15+
messageField.setText("")
16+
chatHistory.setText(chatHistory.getText() + "<br><b>you</b> > " + text)
17+
18+
thread(def(content) {
19+
r = okhttp.request()
20+
.header("Authorization", "Bearer " + OPENAI_API_KEY)
21+
.url("https://api.openai.com/v1/chat/completions")
22+
.post(RequestBody.string(CONTENT_TYPE, jsonencode({
23+
"model": "gpt-3.5-turbo",
24+
"messages": [{"role": "user", "content": content}]
25+
})))
26+
.newCall(okhttp.client)
27+
.execute()
28+
.body()
29+
.string()
30+
31+
println r
32+
resp = jsondecode(r)
33+
if arrayKeyExists("error", resp) {
34+
error = "Error #" + resp.error.code + ": " + resp.error.message
35+
chatHistory.setText(chatHistory.getText() + "<br><font color=red>" + error + "</font>")
36+
} else {
37+
answer = resp.choices[0].message.content
38+
asnwer = answer.replace("\n", "<br>")
39+
chatHistory.setText(chatHistory.getText() + "<br><font color=blue><b>ai</b> > " + answer + "</font>")
40+
}
41+
}, text)
42+
}
43+
44+
messagePanel = newPanel()
45+
messagePanel.setLayout(boxLayout(messagePanel, BoxLayout.LINE_AXIS))
46+
messagePanel.add(messageField)
47+
messagePanel.add(sendButton)
48+
49+
mainPanel = newPanel(borderLayout(10, 10))
50+
mainPanel.setPreferredSize(400, 250)
51+
mainPanel.add(chatHistory, BorderLayout.CENTER)
52+
mainPanel.add(messagePanel, BorderLayout.SOUTH)
53+
54+
window = newWindow("ChatGPT")
55+
window.setMinimumSize(200, 220)
56+
window.setLocationByPlatform()
57+
window.add(mainPanel)
58+
window.pack()
59+
window.setVisible()

0 commit comments

Comments
 (0)