use std, okhttp, json, forms OPENAI_API_KEY=getenv("OPENAI_API_KEY", "your-api-key") CONTENT_TYPE = "application/json; charset=utf-8" chatHistory = newLabel("ChatGPT
") 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() + "
you > " + 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() + "
" + error + "") } else { answer = resp.choices[0].message.content asnwer = answer.replace("\n", "
") chatHistory.setText(chatHistory.getText() + "
ai > " + answer + "") } }, 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()