Skip to content

Instantly share code, notes, and snippets.

@valgaze
Last active October 15, 2023 10:50
Show Gist options
  • Select an option

  • Save valgaze/51c59e6ef5030de521f815f63e2d0967 to your computer and use it in GitHub Desktop.

Select an option

Save valgaze/51c59e6ef5030de521f815f63e2d0967 to your computer and use it in GitHub Desktop.
Voiceflow KB Upload
// Sawp in VF ACCESS_TOKEN below, have text file bongo.txt in same directory as script
// Run with node (18+ for Fetch/FormData): $ node index.js

// CONFIG
const ACCESS_TOKEN = `VF.DM.XXXXXX`;
const FILE_NAME = "bongo.txt"; // Same directory as the script

const fs = require("fs");
const path = require("path");

/**
 * Uploads a file to the Voiceflow knowledge base.
 * @param {string} fileName - The name of the file.
 * @param {Buffer} fileData - The file data as a Buffer.
 */
async function uploadFile(fileName, fileData) {
  const url = "https://api.voiceflow.com/v3alpha/knowledge-base/docs/upload";
  const queryParams = new URLSearchParams({
    maxChunkSize: "1000",
    overwrite: "true",
  });

  const headers = {
    Authorization: `Bearer ${ACCESS_TOKEN}`,
  };

  const formData = new FormData();

  const blob = new Blob([fileData], {
    type: `text/plain`, // 'application/pdf' |  'text/plain' | 'application/msword'
  });

  formData.append("file", blob, fileName);

  const response = await fetch(`${url}?${queryParams}`, {
    method: "POST",
    headers: headers,
    body: formData,
  });

  if (!response.ok) {
    const json = await response.json();
    console.log("Error:", json);
    throw new Error(`File upload failed with status ${response.status}`);
  }

  console.log("File uploaded successfully!");
}

(async () => {
  try {
    const filePath = path.resolve(__dirname, FILE_NAME);
    const fileData = await fs.promises.readFile(filePath);
    await uploadFile(FILE_NAME, fileData);
  } catch (error) {
    console.error("Error uploading file:", error);
  }
})();
@valgaze
Copy link
Author

valgaze commented Oct 3, 2023

https://developer.voiceflow.com/reference/post_v3alpha-knowledge-base-docs-upload

{
  code: 500,
  status: 'Internal Server Error',
  dateTime: '2023-10-03T14:35:08.513Z',
  timestamp: 1696343708513
} 

@geosword
Copy link

Im not sure if this is the problem you are facing. I was, until I realised that url and name should be the same. If they are not, it will spit a 500 with this response: {"code":500,"status":"Internal Server Error","dateTime":"2023-10-15T10:46:08.795Z","timestamp":1697366768795,"data":"Invalid URL"}%

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment