Skip to content

Instantly share code, notes, and snippets.

@foeken
Created November 28, 2022 15:24
Show Gist options
  • Save foeken/077bdcc5f6ae373c6f224557c99e94b8 to your computer and use it in GitHub Desktop.
Save foeken/077bdcc5f6ae373c6f224557c99e94b8 to your computer and use it in GitHub Desktop.
ScriptKit OpenAI script for Tana
// Name: OpenAI Replace
// Description: Replace using Open AI's API
// Shortcut: cmd ctrl s
import "@johnlindquist/kit"
let { Configuration, OpenAIApi } = await npm("openai")
let configuration = new Configuration({
apiKey: await env("OPENAI_API_KEY"),
})
let openai = new OpenAIApi(configuration)
let complete = async (prompt, maxTokens, temperature) => {
setTimeout(() => {
setLoading(true)
}, 250)
console.log(maxTokens)
console.log(temperature)
console.log(prompt)
let response = await openai.createCompletion({
model: "text-davinci-002",
prompt: `${prompt}`,
temperature: temperature,
max_tokens: maxTokens,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
setLoading(false)
return response?.data?.choices[0]?.text?.trim()
}
let prompt = await getSelectedText()
let regexMatch = null
let temperature = 0.7
let temperatureRegex = /\n Temperature: ([+-]?([0-9]*[.])?[0-9]+)/
regexMatch = temperatureRegex.exec(prompt)
if (regexMatch) {
temperature = parseFloat(regexMatch[1])
prompt = prompt.replace(temperatureRegex, "")
}
let maxTokens = 512
let maxTokensRegex = /\n Max Tokens: ([+-]?([0-9]*[.])?[0-9]+)/
regexMatch = maxTokensRegex.exec(prompt)
if (regexMatch) {
maxTokens = parseInt(regexMatch[1])
prompt = prompt.replace(maxTokensRegex, "")
}
let result = ""
while (true) {
if (result != "") {
prompt = await editor(prompt)
}
div("Give me a second ...", "text-center text-4xl p-10 font-semibold")
result = await complete(prompt, maxTokens, temperature)
let retryOrContinue = await arg(
{
placeholder: "",
hint: "[R]etry another prompt, [E]dit the reply, or continue (enter)",
ignoreBlur: true,
}, div(md(result), 'm-4')
)
if (retryOrContinue === "E") {
result = await editor(result)
break
}
if (retryOrContinue === "") break
}
setSelectedText("%%tana%%\n" + result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment