-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathimage-support.mjs
More file actions
188 lines (163 loc) · 5.24 KB
/
image-support.mjs
File metadata and controls
188 lines (163 loc) · 5.24 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/**
* Image Support Example
*
* This example demonstrates how to use multimodal (image) inputs with the
* Codex CLI provider. Images are passed to Codex CLI via the --image flag.
*
* Supported image formats:
* - Base64 data URL (data:image/png;base64,...)
* - Base64 string (without data URL prefix)
* - Buffer / Uint8Array / ArrayBuffer
*
* NOT supported:
* - HTTP/HTTPS URLs (images must be provided as binary data)
*
* Usage:
* node examples/exec/image-support.mjs # Uses bundled bull.webp
* node examples/exec/image-support.mjs /path/to/image.png # Uses custom image
*/
import { readFileSync } from 'node:fs';
import { extname, basename, join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { generateText, streamText } from 'ai';
import { codexExec } from 'ai-sdk-provider-codex-cli';
// Supported image extensions and their MIME types
const SUPPORTED_EXTENSIONS = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
};
/**
* Convert an image file to a base64 data URL
*/
function toDataUrl(filePath) {
const ext = extname(filePath).toLowerCase();
const mediaType = SUPPORTED_EXTENSIONS[ext];
if (!mediaType) {
throw new Error(
`Unsupported image extension "${ext}". Supported: ${Object.keys(SUPPORTED_EXTENSIONS).join(', ')}`,
);
}
const contents = readFileSync(filePath);
const base64 = contents.toString('base64');
return `data:${mediaType};base64,${base64}`;
}
/**
* Get media type from file path
*/
function getMediaType(filePath) {
const ext = extname(filePath).toLowerCase();
return SUPPORTED_EXTENSIONS[ext] || 'image/png';
}
// Create model instance - gpt-5.5 supports vision/multimodal inputs
const model = codexExec('gpt-5.5', {
allowNpx: true,
skipGitRepoCheck: true,
approvalMode: 'on-failure',
sandboxMode: 'workspace-write',
color: 'never',
});
async function main() {
// Use bundled bull.webp as default if no path provided
const __dirname = dirname(fileURLToPath(import.meta.url));
const defaultImagePath = join(__dirname, '../assets/bull.webp');
const filePath = process.argv[2] || defaultImagePath;
const fileName = basename(filePath);
console.log('='.repeat(60));
console.log('Image Support Example - Codex CLI Provider');
console.log('='.repeat(60));
if (!process.argv[2]) {
console.log(`\nUsing default image: ${fileName}`);
console.log('Tip: Pass a custom image path as argument:');
console.log(' node examples/exec/image-support.mjs /path/to/image.png\n');
} else {
console.log(`\nUsing custom image: ${fileName}\n`);
}
// ===== Example 1: Using generateText with data URL =====
console.log('-'.repeat(60));
console.log('Example 1: generateText with data URL');
console.log('-'.repeat(60));
const dataUrl = toDataUrl(filePath);
console.log(`Image loaded: ${fileName} (${(dataUrl.length / 1024).toFixed(1)} KB base64)\n`);
console.log('Asking model to describe the image...\n');
const { text } = await generateText({
model,
messages: [
{
role: 'user',
content: [
{
type: 'text',
text: `Describe what you see in this image "${fileName}" in 2-3 sentences.`,
},
{ type: 'image', image: dataUrl },
],
},
],
});
console.log('Response:', text);
// ===== Example 2: Using streamText with Buffer =====
console.log('\n' + '-'.repeat(60));
console.log('Example 2: streamText with Buffer');
console.log('-'.repeat(60));
const imageBuffer = readFileSync(filePath);
const mediaType = getMediaType(filePath);
console.log(`\nAsking model about the mood of the image (streaming)...\n`);
process.stdout.write('Response: ');
const { textStream } = await streamText({
model,
messages: [
{
role: 'user',
content: [
{
type: 'text',
text: 'What mood or emotion does this image convey? Answer in one sentence.',
},
{
type: 'image',
image: imageBuffer,
mimeType: mediaType,
},
],
},
],
});
for await (const chunk of textStream) {
process.stdout.write(chunk);
}
process.stdout.write('\n');
// ===== Example 3: Multiple images =====
console.log('\n' + '-'.repeat(60));
console.log('Example 3: Demonstrating multiple images support');
console.log('-'.repeat(60));
console.log('\nNote: You can pass multiple images in a single message.');
console.log('Each image becomes a separate --image flag to Codex CLI.\n');
console.log('Code example:');
console.log(`
const { text } = await generateText({
model,
messages: [{
role: 'user',
content: [
{ type: 'text', text: 'Compare these two images' },
{ type: 'image', image: image1Buffer, mimeType: 'image/png' },
{ type: 'image', image: image2Buffer, mimeType: 'image/jpeg' },
],
}],
});
`);
console.log('='.repeat(60));
console.log('Examples completed successfully!');
console.log('='.repeat(60));
}
main().catch((error) => {
console.error('\nError:', error.message);
if (error.cause) {
console.error('Cause:', error.cause);
}
process.exitCode = 1;
});