Selecting OpenAI answer text from HTTPResponse

First post here. I am trying to create an action that uses the OpenAI chatgpt4 API to summarize an email imported from Drafts Maildrop, and appends the response to the bottom of the message.

I have successfully gotten it to the point where the entire HTTPResponse object gets added to the bottom of the draft. But I don’t want the whole response object as a string - I just want the answer text.

This is the script I wrote

const draftText = editor.getText()

// create OpenAI object
let ai = new OpenAI()

// make API request
let response = ai.request({
	"path": "/chat/completions",
	"method": "POST",
	"parameters": "draftText",
	"data": {
		"model": "gpt-4",
		"messages": [
			{
				"role": "system",
				"content": "[my instructions for summarizing the message here]"
			},
			{"role": "user",
			"content": draftText
			},
		]
	}
})

// report status
console.log(`CODE: ${response.statusCode}

ERR: ${response.error}

${response.responseText}
`)

let content = `${draftText}

===

${response.responseText}

===
`

editor.setSelectedText(content)

Here is the response I get:

{
  "id": "chatcmpl-[removed from post]",
  "object": "chat.completion",
  "created": 1693372536,
  "model": "gpt-4-0613",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "[the chatGPT answer I want to isolate is here]"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 5567,
    "completion_tokens": 277,
    "total_tokens": 5844
  }
}


===

Can anyone help me figure out how to handle this HTTPResponse object?

Untested, but try replacing ${response.responseText} with the line below and see if that works for your example.

${response.responseData.choices[0].message.content}

If you are just wanting to append below the email, you can use the quickChatResponse method

Here is an example based on your post.

// Get the current text from the Drafts editor.
const draftText = editor.getText();

// Create an OpenAI object.
let ai = new OpenAI();

// Define the chat prompt for summarization.
const chatPrompt = `Summarize the following message:\n\n===\n${draftText}\n===\n\n===\n`;

// Use the quickChatResponse method to get a quick summary.
let answer = ai.quickChatResponse(chatPrompt);

// Check if the answer is defined before proceeding.
if (typeof answer !== 'undefined') {
    // Prepare the content to be inserted in the Drafts editor.
    const contentToInsert = `\n\n===\n${answer}\n===\n`;

    // Insert the generated content at the cursor position.
    editor.setSelectedText(contentToInsert);
} else {
    console.log("Received undefined answer from quickChatResponse.");
}

If you are wanting to call it directly, the full example would look something like this:

const draftText = editor.getText();

// Create an OpenAI object. This object is used to interact with the OpenAI API.
let ai = new OpenAI();

// Make an API request to OpenAI's chat completions endpoint.
let response = ai.request({
    // The API endpoint path for chat completions.
    "path": "/chat/completions",
    
    // The HTTP method for the request.
    "method": "POST",
    
    // Parameters to send with the request. In this case, "draftText" seems to be specified as a parameter, although its actual use is not clear.
    "parameters": "draftText",
    
    // The payload data for the request.
    "data": {
        // Specify the model to use (GPT-4 in this case).
        "model": "gpt-4",
        
        // The sequence of messages to send to the model.
        "messages": [
            // The first message is from the "system" to give instructions to the model.
            {
                "role": "system",
                "content": "[my instructions for summarizing the message here]"
            },
            
            // The second message is from the "user" and contains the text to be processed.
            {
                "role": "user",
                "content": draftText
            }
        ]
    }
});

// Log the status code and any errors to the console for debugging.
console.log(`CODE: ${response.statusCode}\nERR: ${response.error}`);

// Parse the raw JSON response text to get it into object form.
let parsedResponse = JSON.parse(response.responseText);

// Extract the message content from the first choice in the response.
let messageContent = parsedResponse.choices[0].message.content;

// Prepare the content that will replace the selected text in the Drafts editor.
// It consists of the original draft text, followed by the model's response, separated by '==='.
let content = `\n\n===\n${messageContent}\n===\n`;

// Replace the selected text (appends when no text is selected) in the Drafts editor with the prepared content.
editor.setSelectedText(content);
1 Like

Thank you! That worked perfectly. I will use the quickChatResponse method for this, but I appreciate you giving the solution for the direct call as well.