Take dictation as input and let ChatGPT rewrite it (not working)

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();

So ChatGPT is great and reproducing other people’s code it has surfaced from across the Internet from a while back, but it really doesn’t generally do well when it comes to writing code for things like Drafts or making use of things that have come along more recently.

The JavaScript it has provided is incompatible with Drafts. The fetch would instead use the http class in Drafts, and in any case, there is a (fairly new) class for interacting direct with OpenAI API - OpenAI.

The reason it isn’t outputting anything is because it is using the wrong classes and constructs (e.g., read about async and Drafts here).

You would be better off just using or adapting one of the many existing ChatGPT examples for Drafts. Do a search on this forum, in the Drafts directory, and look at the examples on the OpenAI page in the documentation.

1 Like

Did you find a way to do this?