Skip to content

Commit

Permalink
fix: further escaping issues (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisgrieser committed Aug 26, 2024
1 parent 492eefb commit 1058d69
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions scripts/openai-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,55 @@ const app = Application.currentApplication();
app.includeStandardAdditions = true;
//──────────────────────────────────────────────────────────────────────────────

/** @param {string} filepath @param {string} text */
function writeToFile(filepath, text) {
const str = $.NSString.alloc.initWithUTF8String(text);
str.writeToFileAtomicallyEncodingError(filepath, true, $.NSUTF8StringEncoding, null);
}

function ensureCacheFolderExists() {
const finder = Application("Finder");
const cacheDir = $.getenv("alfred_workflow_cache");
if (!finder.exists(Path(cacheDir))) {
const cacheDirBasename = $.getenv("alfred_workflow_bundleid");
const cacheDirParent = cacheDir.slice(0, -cacheDirBasename.length);
finder.make({
new: "folder",
at: Path(cacheDirParent),
withProperties: { name: cacheDirBasename },
});
}
}

//──────────────────────────────────────────────────────────────────────────────

/** @type {AlfredRun} */
// biome-ignore lint/correctness/noUnusedVariables: Alfred run
function run(argv) {
const selection = argv[0]?.trim();
if (!selection) return "ERROR: No selection.";
ensureCacheFolderExists();
const dataCache = $.getenv("alfred_workflow_cache") + "/request-data.json";

const apiKey =
$.NSProcessInfo.processInfo.environment.objectForKey("alfred_apikey").js ||
app.doShellScript('source "$HOME/.zshenv"; echo "$OPENAI_API_KEY"');
const prompt = $.getenv("static_prompt") + selection;
const temp = Number.parseInt($.getenv("temperature")) / 10;
const prompt = $.getenv("static_prompt") + " " + selection;
const temperature = Number.parseInt($.getenv("temperature")) / 10;

const data = {
model: $.getenv("openai_model"),
messages: [{ role: "user", content: prompt }],
temperature: temp,
temperature: temperature,
};
// write to file as send request via `--data-binary` to avoid more escaping issues
writeToFile(dataCache, JSON.stringify(data));

const response = app.doShellScript(
`curl --max-time 15 https://api.openai.com/v1/chat/completions \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer ${apiKey}' \
-d '${JSON.stringify(data)}' `,
--data-binary @'${dataCache}' `,
);
if (!response) return "ERROR: No response from OpenAI API.";
const obj = JSON.parse(response);
Expand Down

0 comments on commit 1058d69

Please sign in to comment.