Skip to content

Instantly share code, notes, and snippets.

@aNNiMON
Last active September 18, 2024 20:17
Show Gist options
  • Save aNNiMON/f45b534f9ad63e3ae4058129adf52e97 to your computer and use it in GitHub Desktop.
Save aNNiMON/f45b534f9ad63e3ae4058129adf52e97 to your computer and use it in GitHub Desktop.
OpenAI API
include "own-modules/openai/OpenAI.own"
OPENAI_API_KEY = getenv("OPENAI_API_KEY", "")
if OPENAI_API_KEY.isEmpty() {
println "OPENAI_API_KEY is required"
exit(1)
}
openai = new OpenAI(OPENAI_API_KEY)
extract(isOk, response) = openai.chatCompletionsBasic(
openai.CHAT_MODEL_GPT4O_MINI, "Hello from OwnLang!")
if (isOk) {
echo("Response: ", response)
exit(0)
} else {
echo("Error: ", response)
exit(1)
}
use std, okhttp, json
class OpenAI {
CHAT_MODEL_GPT35_TURBO = "gpt-3.5-turbo"
CHAT_MODEL_GPT4O_MINI = "gpt-4o-mini"
CHAT_MODEL_GPT4O = "gpt-4o"
API_URL = "https://api.openai.com"
CONTENT_TYPE = "application/json; charset=utf-8"
def OpenAI(apiKey) {
this.apiKey = apiKey
}
def buildUserMessage(text) = {"role": "user", "content": text}
def buildAssistantMessage(text) = {"role": "assistant", "content": text}
def buildSystemMessage(text) = {"role": "system", "content": text}
def buildMessageForRole(role, text) = {"role": role, "content": text}
def chatCompletionsBasic(model, userPrompt, assistantPrompt = "", systemPrompt = "") {
if userPrompt.isEmpty() return [0, "Error: empty user prompt"]
messages = []
if !assistantPrompt.isEmpty() {
messages += this.buildAssistantMessage(assistantPrompt)
}
if !systemPrompt.isEmpty() {
messages += this.buildSystemMessage(systemPrompt)
}
messages += this.buildUserMessage(userPrompt)
return this.chatCompletions(model, messages)
}
def chatCompletions(model, messages, maxTokens = 4096) {
if model.isEmpty() return [0, "empty model"]
r = okhttp.request()
.header("Authorization", "Bearer " + this.apiKey)
.url(this.API_URL + "/v1/chat/completions")
.post(RequestBody.string(this.CONTENT_TYPE, jsonencode({
"model": model,
"messages": messages,
"max_tokens": maxTokens
})))
.newCall(okhttp.client)
.execute()
.body()
.string()
resp = jsondecode(r)
if arrayKeyExists("error", resp) {
return [0, "Error #" + resp.error.code + ": " + resp.error.message]
} else {
return [1, resp.choices[0].message.content]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment