Last active
November 19, 2024 19:33
-
-
Save zitterbewegung/8c82ae83f5034827754758d8614a0e73 to your computer and use it in GitHub Desktop.
OpenAI Deno Vision Tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import OpenAI from "npm:openai"; | |
const openai = new OpenAI(); | |
import { encode } from "https://deno.land/[email protected]/encoding/base64.ts"; | |
async function main() { | |
// Ensure a file path argument is provided | |
if (Deno.args.length === 0) { | |
console.error("Usage: deno run --allow-read script.ts <image-file-path>"); | |
Deno.exit(1); | |
} | |
const filePath = Deno.args[0]; | |
try { | |
// Read the image file as binary data | |
const fileData = await Deno.readFile(filePath); | |
// Encode the binary data into a Base64 string | |
const base64String = encode(fileData); | |
// Create a data URL string | |
const dataUrl = `data:image/jpeg;base64,${base64String}`; | |
const response = await openai.chat.completions.create({ | |
model: "gpt-4o-mini", | |
messages: [ | |
{ | |
role: "user", | |
content: [ | |
{ type: "text", text: "What’s in this image?" }, | |
{ | |
type: "image_url", | |
image_url: { | |
"url": dataUrl, | |
}, | |
}, | |
], | |
}, | |
], | |
}); | |
console.log(response.choices[0]); | |
} catch (error) { | |
console.error("Error reading file:", (error as Error).message); | |
Deno.exit(1); | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment