2

I'm trying to get the OpenAI API working in Excel using Office Script (TypeScript), but I seem to be running into some trouble. When I run the script, it doesn't give any output. Any suggestions?

In the Excel workbook, I have the following tabs:

Prompt Result 1 2 API

In Prompt!B2 I type the prompt. In API!B1 I insert the API key I was expecting a result in Prompt!B4 / Result!A1:D1000

async function main(workbook: ExcelScript.Workbook) {

  // Set the OpenAI API key - Add this in the Excel file or replace this part with your key
  const apiKey = workbook.getWorksheet("API").getRange("B1").getValue();
  const endpoint: string = "https://api.openai.com/v1/completions";

  // get worksheet info
  const sheet = workbook.getWorksheet("Prompt");
  // the ask
  const mytext = sheet.getRange("B2").getValue();

  // useful if if we get more than one row back
  const result = workbook.getWorksheet("Result");
  result.getRange("A1:D1000").clear();
  sheet.getRange("B3").setValue(" ")

  // Set the model engine and prompt
  const model: string = "text-davinci-002";
  const prompt: (string | boolean | number) = mytext;

  // Set the HTTP headers
  const headers: Headers = new Headers();
  headers.append("Content-Type", "application/json");
  headers.append("Authorization", `Bearer ${apiKey}`);

  // Set the HTTP body
  const body: (string | boolean | number) = JSON.stringify({
    model: model,
    prompt: prompt,
    max_tokens: 1024,
    n: 1,
    temperature: 0.5,
  });

  // Send the HTTP request
  const response: Response = await fetch(endpoint, {
    method: "POST",
    headers: headers,
    body: body,
  });

  // Parse the response as JSON
  const json: { choices: { text: (string | boolean | number) }[] } = await response.json();

  // Get the answer - i.e. output
  const text: (string | boolean | number) = json.choices[0].text;

  // Output the generated text
  // console.log(text);

  const output = sheet.getRange("B4");

  output.setValue(text);

  const cell = sheet.getRange("B4");

  // Split the cell contents by new line

  const arr = cell.getValue().toString().split("\n");

  const newcell = result.getRange("A1");

  var offset = 0;
  // console.log (arr)

  for (let i = 0; i < arr.length; i++) {
    // Write the value to the next cell

    if (arr[i].length > 0) {
      newcell.getOffsetRange(offset, 0).setValue(arr[i]);

      offset++;
    }
  }

  // console.log(offset)
  if (offset > 1) {
    sheet.getRange("B3").setValue("Check 'Result' sheet to get answers separated by multiple rows")

  }
}
  • `output.setValue(text);` looks right when I looked at the docs: https://learn.microsoft.com/en-us/javascript/api/office-scripts/excelscript/excelscript.range?view=office-scripts#excelscript-excelscript-range-setvalues-member(1). Does the `console.log(text)` give you any output? – Robert Rendell Mar 21 '23 at 08:38
  • I’ve always found Fetch to be bloody dodgy in Office Scripts. Simple as that. Not sure why. – Skin Mar 21 '23 at 09:15
  • It seems my problem was not in the script. The problem was on the API config. Thanks for the tips. – Biggestspider Mar 23 '23 at 09:03
  • @Skin - in most cases, CORS would be the culprit, which is unfortunately always a challenge when running JavaScript in the browser... – Yutao Huang Apr 13 '23 at 04:15

0 Answers0