-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
90 lines (81 loc) · 2.2 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env node
import * as fs from "fs";
import * as base64 from "base-64";
import axios from "axios";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
// OpenAI API Key
const apiKey: string = process.env.OPENAI_API_KEY || "";
// Function to encode the image
function encodeImage(imageBuffer: Buffer): string {
return base64.encode(imageBuffer.toString("binary"));
}
// Set up the CLI arguments
const argv = yargs(hideBin(process.argv))
.option("file", {
alias: "f",
type: "string",
description: "Path to the image file",
})
.parseSync();
// Read the image file from the path or from the input stream
// Function to read image from file or stdin
function getImageBuffer(): Promise<Buffer> {
return new Promise((resolve, reject) => {
if (argv.file) {
// Read image from file
fs.readFile(argv.file, (err, data) => {
if (err) reject(err);
else resolve(data);
});
} else {
// Read from stdin
const chunks: Buffer[] = [];
process.stdin.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
process.stdin.on("end", () => resolve(Buffer.concat(chunks)));
process.stdin.on("error", (err) => reject(err));
}
});
}
getImageBuffer().then((imageBuffer) => {
const base64Image: string = encodeImage(imageBuffer);
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
};
const payload = {
model: "gpt-4-vision-preview",
messages: [
{
role: "user",
content: [
{
type: "text",
text: "What’s in this image?",
},
{
type: "image_url",
image_url: {
url: `data:image/jpeg;base64,${base64Image}`,
},
},
],
},
],
max_tokens: 300,
};
axios
.post("https://api.openai.com/v1/chat/completions", payload, {
headers: headers,
})
.then((response) => {
if (response.data.choices) {
console.log(response.data.choices[0].message.content);
} else {
console.log("No choices found in the response.");
}
})
.catch((error) => {
console.error(error);
});
});