I have with the help of ChatGPT (meta, I know) created the following javascript that takes dictation as input and then sends the text to OpenAI to be rewritten.
The problem is that the action doesn’t output anything. What am I missing? (Note this is my first action that I created from blank… with the help of ChatGPT)
// Constants
const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY';
const OPENAI_API_URL = 'https://api.openai.com/v1/engines/davinci-codex/completions';
// Function to send text to OpenAI API for rewriting
async function rewriteText(text) {
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`
};
const data = {
'prompt': text,
'max_tokens': 100,
'temperature': 0.7,
'top_p': 1.0,
'frequency_penalty': 0.0,
'presence_penalty': 0.0
};
const response = await fetch(OPENAI_API_URL, {
method: 'POST',
headers: headers,
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error('Failed to rewrite text.');
}
const responseData = await response.json();
return responseData.choices[0].text.trim();
}
// Event handler for Drafts action
async function handleDraftsAction() {
// Open dictation for new draft
var s = editor.dictate();
if (s.length > 0) {
var dictation = s;
try {
// Call the OpenAI API to rewrite the dictation
const rewrittenText = await rewriteText(dictation);
// Create a new draft with the rewritten text
const newDraft = Draft.create();
newDraft.content = rewrittenText;
newDraft.update();
// Load the new draft in the editor and focus on it
editor.load(newDraft);
editor.focus();
// Display the rewritten text in the draft's content area
draft.content = rewrittenText;
console.log('Rewriting completed.');
} catch (error) {
console.log('Error:', error.message);
}
} else {
console.log('No dictation input.');
}
}
// Execute the action
handleDraftsAction();