Getting error 400 OpenAI files endpoint Node.js - node.js

I have been trying for hours, tried CSV data, JSON data, tried it all I keep getting either a 415 error or a 400 error; if I can have any help that would be great, the documentation and the AI itself has not been at all helpful in trying to inject data to train a model
Text:
This is a text file for the OpenAI API.
It contains sample data for testing purposes.
Here is another line.
And another.
Code:
const FormData = require('form-data');
const fs = require('fs');
const API_KEY = 'MY_API_KEY';
const formData = new FormData();
formData.append('file', fs.createReadStream('./myfile.txt'), {
filename: 'myfile.txt'
});
axios.post('https://api.openai.com/v1/files', formData, {
headers: {
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
"Authorization": "Bearer " + API_KEY
}
})
.then(response => {
// Handle response
})
.catch(err => {
// Handle error
console.log(err)
});

From the documentation, you are missing the required purpose field...
Request body
file Required
...
purpose Required
The intended purpose of the uploaded documents.
Use "fine-tune" for Fine-tuning. This allows us to validate the format of the uploaded file.
const FormData = require("form-data");
const fs = require("fs");
const API_KEY = "MY_API_KEY";
const formData = new FormData();
formData.append("purpose", "search"); // 👈 adjust accordingly
formData.append("file", fs.createReadStream("./myfile.txt"), "myfile.txt");
axios
.post("https://api.openai.com/v1/files", formData, {
headers: {
...formData.getHeaders(), // this is simpler
authorization: `Bearer ${API_KEY}`,
},
})
.then((response) => {
// Handle response
})
.catch((err) => {
// Handle error
console.log(err.response?.data, err.toJSON());
});

Related

Remix Run UploadHandler Using Data for WhatsApp API Media Upload

I am attempting to use a form in Remix to add a file and then upload that file to WhatsApp using their Cloud API Media Upload endpoint. Below is my initial code within the action. The current error I am receiving is message: '(#100) The parameter messaging_product is required.. I feel like this error may be misleading based off the form data I have appended with the "messaging_product".
export async function action({ request, params }: ActionArgs) {
const uploadHandler = unstable_composeUploadHandlers(
async ({ name, contentType, data, filename }) => {
const whatsAppPhoneId = process.env.WHATSAPP_PHONE_ID;
const whatsAppToken = process.env.WHATSAPP_ACCESS_TOKEN;
const dataArray1 = [];
for await (const x of data) {
dataArray1.push(x);
}
const file1 = new File(dataArray1, filename, { type: contentType });
const graphApiUrl = `https://graph.facebook.com/v15.0/${whatsAppPhoneId}/media`;
const formData = new FormData();
formData.append("file", file1);
formData.append("messaging_product", "whatsapp");
formData.append("type", contentType);
try {
const imageMediaResponse = await fetch(graphApiUrl, {
method: "POST",
headers: {
Authorization: `Bearer ${whatsAppToken}`,
"Content-Type": "multipart/form-data",
},
body: formData,
});
const imageMedia = await imageMediaResponse.json();
return imageMedia?.id;
} catch (error) {
console.error(error);
}
const whatsAppMediaId = await uploadWhatsAppImageMedia(
whatsAppPhoneId,
whatsAppToken,
data,
filename,
contentType
);
}
);
const formData = await unstable_parseMultipartFormData(
request,
uploadHandler
);
}

Converting image URL to .png file using NodeJS

I am currently working on an application which takes in image URLs in this format:
https://replicate.delivery/pbxt/Y45OPyjFe92FLqemk1Mmsr69gzruylefj5SxKqJInMmxCyABB/out-0.png
And need to send it to an API to check if it is explicit content. The issue is that the API only accepts .png or .jpg files and not an image URL. How can I convert this image URL into a sendable file?
This is what their docs say:
const axios = require('axios').default;
const fs = require("fs");
const FormData = require("form-data");
const form = new FormData();
form.append("providers", 'amazon, google');
form.append("file", fs.createReadStream("🖼️ path/to/your/image.png"));
const options = {
method: 'POST',
url: 'https://api.edenai.run/v2/image/explicit_content',
headers: {
authorization: 'Bearer 🔑 Your_API_Key',
'Content-Type': 'multipart/form-data; boundary=' + form.getBoundary()
},
data: form
};
axios
.request(options)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
However, I do not have the path to the file and instead solely the image URL. Any help would be greatly appreciated!
You need to make an extra request to get the image first, keep it in memory (alternatively, you could save the file and then read it with fs), and then make another request, which sends the image to the checking endpoint.
With axios, you can get the image as a stream, and then just pass it along with form-data.
Try this:
// get image as a stream
const getImgOptions = {
method: 'GET',
url: 'https://replicate.delivery/pbxt/Y45OPyjFe92FLqemk1Mmsr69gzruylefj5SxKqJInMmxCyABB/out-0.png',
responseType: 'stream'
};
let img;
try {
img = await axios.request(getImgOptions);
// got the image, now send it for checking
let uploadImg;
try {
const form = new FormData();
form.append("providers", 'amazon, google');
form.append("file", img.data);
const postImgOptions = {
method: 'POST',
url: 'https://api.edenai.run/v2/image/explicit_content',
headers: {
authorization: 'Bearer 🔑 Your_API_Key',
'Content-Type': 'multipart/form-data; boundary=' + form.getBoundary()
},
data: form
};
uploadImg = await axios.request(postImgOptions);
// do something with the result
console.log('check response: ', uploadImg.data);
} catch (error) {
console.error(error);
}
} catch (error) {
console.error(error);
}

Sending form data server side

I am sending a formdata to an endpoint that requires the following data:
token_key,
customer_id,
folder_id,
document_id,
file
but I get an error when sending it, the steps I do are the following:
html file
submitBtn.addEventListener("click", function (e) {
if (is_signed) {
var dataUrl = canvas.toDataURL();
var image = dataURItoBlob(dataUrl);
var file = new File([image], 'firma.png', {
type: 'image/png'
});
var folder_id = location.search.slice(1).split("&")[0].split("=")[1]
var document_id = location.search.slice(1).split("&")[1].split("=")[1]
const formdata = new FormData();
formdata.append('document_id', parseInt(document_id));
formdata.append('folder_id', parseInt(folder_id));
formdata.append('file', file)
axios.post('/send-signature', formdata, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}, false)
Js file
router.post("/send-signature", (req, res) => {
const url_expa_signature = `${process.env.BASE_URL_EXPA}/upload-documents`
const document_id = req.body.document_id
const folder_id = req.body.folder_id
const file = req.files.file
const token_key = process.env.TOKEN_KEY
const customer_id = process.env.CUSTOMER_ID
const formdata = new FormData();
formdata.append('token_key', token_key);
formdata.append('customer_id', customer_id);
formdata.append('folder_id', folder_id);
formdata.append('document_id', document_id);
formdata.append('file', file);
axios({
method: 'post',
url: url_expa_signature,
data: formdata,
})
})
and the following error is
TypeError: source.on is not a function
any suggestion?
It was a problem with the endpoint that i consume, i solve it calling to suport and they fix the bug.

how to send image via discord webhook using node-fetch?

const fetch = require('node-fetch');
const fs = require('fs')
var data = fs.readFileSync('2.png', 'utf8')
var URL = "apikey";
fetch(URL, {
"method":"POST",
"headers": {"Content-Type": "application/json"},
"body": data
})
.then(res=> console.log(res))
.catch(err => console.error(err));
how can I send images via discord webhook? I have tried the above and it does not work. and there are no proper examples on discord docs.
You are sending a file then your Content-Type should be multipart/form-data.
Change code to
const fetch = require('node-fetch');
const formData = require('form-data');
const fs = require('fs')
const form = new formData();
form.append('file1', fs.createReadStream('./2.png')); // give absolute path if possible
var URL = "XYZ URL";
fetch(URL, {
'method': 'POST',
'body': form,
headers: form.getHeaders()
})
.then(res=> console.log(res))
.catch(err => console.error(err));
See yellow notice in this page of discord's documentations

How to download a file from a server, and and post it again in another one (Node.js)

In my node application, I want to get a file from one server, and then upload it into another server. I have the following code:
const axios = require("axios");
const FormData = require("form-data");
const { createWriteStream, createReadStream } = require("fs");
const response = await axios({
url: "https://first-server/image.png",
method: "GET",
responseType: "stream",
});
await new Promise((res) => {
response.data.pipe(
createWriteStream("someFile.png").on("finish", () => {
res();
})
);
});
const form = new FormData();
form.append("file", createReadStream("./someFile.png"));
const postHeaders = {
headers: {
Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("https://second-server.com/api", form, postHeaders)
.then((response) => {
console.log(JSON.stringify(response.data));
})
This code works, but I think it's not the right way to do this, since it writes the retrieved file into the local disc before posting it again into the second server. I need to be able to upload the file without writing it into the local disc. Is there any way?
Just replace form.append("file", createReadStream("./someFile.png")); with
form.append("file", response.data);
Both response.data and createReadStream("./someFile.png") are readable stream.
Note: You can directly transfer returned stream data without any need to create temporary file.
const axios = require("axios");
const FormData = require("form-data");
axios({
url: "http://localhost:3000/temp.png",
method: "GET",
responseType: "stream",
}).then(response => {
response.data.on("data", function(data) {
const form = new FormData();
form.append("file", data);
const postHeaders = {
headers: {
// Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("http://localhost:8000/api", form, postHeaders)
.then((response) => {
// console.log(JSON.stringify(response.data));
})
.catch(function(error){
console.log(error)
});
});
})
.catch(function(error){
console.log(error)
});

Resources