mirror of
https://github.com/aNNiMON/Own-Programming-Language-Tutorial.git
synced 2024-09-20 00:34:20 +03:00
Add ChatGPT example
This commit is contained in:
parent
899a466c9a
commit
f7ca2f16b9
59
examples/forms/chatgpt.own
Normal file
59
examples/forms/chatgpt.own
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
use std, okhttp, json, forms
|
||||||
|
|
||||||
|
OPENAI_API_KEY=getenv("OPENAI_API_KEY", "your-api-key")
|
||||||
|
CONTENT_TYPE = "application/json; charset=utf-8"
|
||||||
|
|
||||||
|
chatHistory = newLabel("<html>ChatGPT<br>")
|
||||||
|
messageField = newTextField()
|
||||||
|
sendButton = newButton("Send")
|
||||||
|
|
||||||
|
messageField.onAction(::onSend)
|
||||||
|
sendButton.onClick(::onSend)
|
||||||
|
def onSend() {
|
||||||
|
text = messageField.getText()
|
||||||
|
if (length(text) == 0) return 0
|
||||||
|
messageField.setText("")
|
||||||
|
chatHistory.setText(chatHistory.getText() + "<br><b>you</b> > " + text)
|
||||||
|
|
||||||
|
thread(def(content) {
|
||||||
|
r = okhttp.request()
|
||||||
|
.header("Authorization", "Bearer " + OPENAI_API_KEY)
|
||||||
|
.url("https://api.openai.com/v1/chat/completions")
|
||||||
|
.post(RequestBody.string(CONTENT_TYPE, jsonencode({
|
||||||
|
"model": "gpt-3.5-turbo",
|
||||||
|
"messages": [{"role": "user", "content": content}]
|
||||||
|
})))
|
||||||
|
.newCall(okhttp.client)
|
||||||
|
.execute()
|
||||||
|
.body()
|
||||||
|
.string()
|
||||||
|
|
||||||
|
println r
|
||||||
|
resp = jsondecode(r)
|
||||||
|
if arrayKeyExists("error", resp) {
|
||||||
|
error = "Error #" + resp.error.code + ": " + resp.error.message
|
||||||
|
chatHistory.setText(chatHistory.getText() + "<br><font color=red>" + error + "</font>")
|
||||||
|
} else {
|
||||||
|
answer = resp.choices[0].message.content
|
||||||
|
asnwer = answer.replace("\n", "<br>")
|
||||||
|
chatHistory.setText(chatHistory.getText() + "<br><font color=blue><b>ai</b> > " + answer + "</font>")
|
||||||
|
}
|
||||||
|
}, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
messagePanel = newPanel()
|
||||||
|
messagePanel.setLayout(boxLayout(messagePanel, BoxLayout.LINE_AXIS))
|
||||||
|
messagePanel.add(messageField)
|
||||||
|
messagePanel.add(sendButton)
|
||||||
|
|
||||||
|
mainPanel = newPanel(borderLayout(10, 10))
|
||||||
|
mainPanel.setPreferredSize(400, 250)
|
||||||
|
mainPanel.add(chatHistory, BorderLayout.CENTER)
|
||||||
|
mainPanel.add(messagePanel, BorderLayout.SOUTH)
|
||||||
|
|
||||||
|
window = newWindow("ChatGPT")
|
||||||
|
window.setMinimumSize(200, 220)
|
||||||
|
window.setLocationByPlatform()
|
||||||
|
window.add(mainPanel)
|
||||||
|
window.pack()
|
||||||
|
window.setVisible()
|
Loading…
Reference in New Issue
Block a user