Creating a chat summary using openai api

20 views Asked by At

I am creating a ChatSummarizer app where the input is an excel file with chat transcripts. Each row of the excel sheet corresponds to a new chat. The Summarizer app summarizes the chat i n the adjacent column. The problem is I keep getting the following error: TypeError: Cannot read properties of undefined (reading 'create')

Here's my code:

require('dotenv').config();
const express = require('express');
const multer = require('multer');
const ExcelJS = require('exceljs');
const { Configuration, OpenAIApi } = require("openai");
const fs = require('fs');

// Initialize express app
const app = express();

// Configure multer for file uploads
const upload = multer({ dest: 'uploads/' });

// Initialize OpenAI API with configuration
const { OpenAI } = require('openai');
const openai = new OpenAI(process.env.OPENAI_API_KEY);

app.post('/upload', upload.single('file'), async (req, res) => {
  try {
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.readFile(req.file.path);
    console.log(`File uploaded to: ${req.file.path}`);

    const worksheet = workbook.getWorksheet(1);

    // Convert worksheet rows to an array for easier iteration
    let rows = [];
    worksheet.eachRow((row, rowNumber) => {
      rows.push({ row, rowNumber });
    });

    // Iterate over rows array using a for...of loop to maintain async/await context
    for (let { row, rowNumber } of rows) {
      let chatText = row.getCell(1).value;
      if (chatText) { // Ensure there's text to summarize
        try {
          const response = await openai.ChatCompletion.create({
            model: "gpt-3.5-turbo",
            prompt: `Summarize this chat: ${chatText}`,
            max_tokens: 100,
          });
          let summary = response.data.choices[0].text.trim();
          row.getCell(2).value = summary; // Assign the summary to the next column
        } catch (apiError) {
          console.error(`Error processing row ${rowNumber}:`, apiError);
        }
      }
    }

    // Save the workbook with summaries to a new file
    await workbook.xlsx.writeFile('/Users/ravikumar/ClarabridgeOutput/output.xlsx');
    res.send('File processed and summaries added.');
  } catch (error) {
    console.error(error);
    res.status(500).send('An error occurred while processing the file.');
    fs.unlinkSync(req.file.path); // Clean up uploaded file even on error
  }
});

// Choose a port for the server to listen on
const PORT = 3000;

// Start the server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
1

There are 1 answers

1
Rok Benko On

There are three problems with your code.

Problem 1: Incorrect method name

The correct method name depends on the OpenAI Node.js SDK version you're using.

If you're using the OpenAI Node.js SDK >=v4, the following is the correct method name:

openai.chat.completions.create

If you're using the OpenAI Node.js SDK <v4, the following is the correct method name:

openai.ChatCompletion.create

Problem 2: Incorrect parameter

The Chat Completions API doesn't have the prompt parameter. You should use the messages parameter instead, as follows:

messages: [{ role: "user", content: `Summarize this chat: ${chatText}` }],

Problem 3: Incorrect response extraction

The correct response extraction depends on the OpenAI Node.js SDK version you're using.

If you're using the OpenAI Node.js SDK >=v4, the following is the correct response extraction:

response.choices[0].message.content.trim();

If you're using the OpenAI Node.js SDK <v4, the following is the correct response extraction:

response.data.choices[0].message.content.trim();

An example from the documentation

I suggest you take a look at an example request from the official OpenAI documentation:

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const completion = await openai.chat.completions.create({
    messages: [{ role: "system", content: "You are a helpful assistant." }],
    model: "gpt-3.5-turbo",
  });

  console.log(completion.choices[0]);
}

main();