NodeJS PDF Upload and Analysis

How can I do the following using the NodeJS SDK.
I want to take a PDF file and upload it to the API.
I want the API then to provide me an output.

I have the following code which was suggested by chatGPT:

async function getOrCreateInvoiceAssistant() {
  const assistants = await openai.listAssistants();
  let assistant = assistants.find((a: any) => === GPT_ASSISTANT_NAME);

  if (!assistant) {
    assistant = await openai.createAssistant({
      model: OPENAI_MODEL,
      description: 'You are a PDF retrieval assistant. Your response is always in JSON format.',
      instructions: invoiceExpensePrompt(),
      tools: [{ type: 'file_search' }],

  return assistant;

export async function getDataFromExpenseInvoicePdf(documentId: string) {
  try {
    // Download the PDF document
    const fileBuffer = await downloadDocument(documentId);

    // Convert the buffer to a readable stream
    const stream = fileBuffer;

    // Upload the PDF file to OpenAI API
    const uploadedFile = await openai.files.create({
      file: stream,
      purpose: 'assistants',

    // Create a chat completion with the uploaded file and prompt
    const response = await{
      model: OPENAI_MODEL,
      messages: [{ role: 'user', content: invoiceExpensePrompt(), attachments: { file_id: } }],

    // Extract and parse the JSON from the Assistant's response
    let resTxt = response.choices[0].message.content;
    if (resTxt.startsWith('```json')) {
      resTxt = resTxt.slice(6);
    if (resTxt.endsWith('```')) {
      resTxt = resTxt.slice(0, -3);
    resTxt = resTxt.slice(resTxt.indexOf('{'), resTxt.lastIndexOf('}') + 1).trim();

    const data = JSON.parse(resTxt);

    // Optionally delete the file to preserve space
    await openai.deleteFile(;

    return data;
  } catch (error) {
    console.error('Failed to generate content from PDF document', error);
    throw error;

I just want to upload a PDF, have it analyzed using the prompt and then return it.