Branchwell

Lumen & Gesso / website · lumengesso.com / app / lib / openai-vision.ts

1import 'server-only';
2
3// Reverse-engineer a textual style description from an image using
4// OpenAI's vision-capable chat model. Used by the admin "Analyze style"
5// button on custom-style commissions to turn the customer's uploaded
6// reference image into a paragraph the image-edit endpoint can read —
7// since /v1/images/edits only accepts ONE image (the pet subject), the
8// style has to travel as text on the OpenAI path.
9
10const VISION_MODEL = 'gpt-4o';
11
12const SYSTEM_INSTRUCTIONS = [
13 'You are an art critic helping another artist recreate a visual style.',
14 'You will be shown one image. Describe ITS VISUAL STYLE ONLY — do NOT describe what the subject is.',
15 'Cover, in this order, in 4–8 short sentences:',
16 ' • Medium (oil, watercolor, gouache, ink, digital, photograph, mixed media, etc.) and apparent surface (canvas, paper texture, screen grain).',
17 ' • Palette (dominant hues, saturation, warm/cool bias, contrast range).',
18 ' • Brushwork / line quality / mark-making (loose, tight, impasto, dry-brush, scratchy, smooth, etc.).',
19 ' • Lighting and atmosphere (hard, soft, directional, ambient, hazy, lit-from-within, etc.).',
20 ' • Composition tendencies if obvious (cropped tight, vignetted, central, off-center).',
21 ' • Mood the style projects (intimate, regal, playful, melancholic, monumental, etc.).',
22 'Be specific and concrete — names of techniques or movements ("ukiyo-e woodblock", "Basquiat-style neo-expressionist", "muted Edward Hopper realism") are great anchors when they fit.',
23 'Do not mention the subject. Do not reference what the image depicts. Style only.',
24 'Output the description as a single paragraph or short list — plain prose, no headers, no meta-commentary about your task.',
25].join('\n');
26
27/** Calls GPT-4o Vision against a publicly-fetchable image URL and
28 * returns a trimmed style description. Throws on any failure — the
29 * caller (analyze-style route) catches and returns a 500.
30 *
31 * Cost: ~$0.005–$0.01 per call on a typical CF Images-served upload
32 * (small image → ~1–2k input tokens; output ~150–300 tokens). */
33export async function describeImageStyle(imageUrl: string): Promise<string> {
34 const key = process.env.OPENAI_API_KEY;
35 if (!key) throw new Error('OPENAI_API_KEY not set');
36
37 const res = await fetch('https://api.openai.com/v1/chat/completions', {
38 method: 'POST',
39 headers: {
40 Authorization: `Bearer ${key}`,
41 'content-type': 'application/json',
42 },
43 body: JSON.stringify({
44 model: VISION_MODEL,
45 // Low temperature so the description stays focused + reproducible;
46 // a creative re-analyze is rarely what admin wants.
47 temperature: 0.3,
48 messages: [
49 {
50 role: 'user',
51 content: [
52 { type: 'text', text: SYSTEM_INSTRUCTIONS },
53 { type: 'image_url', image_url: { url: imageUrl } },
54 ],
55 },
56 ],
57 }),
58 });
59
60 if (!res.ok) {
61 const text = await res.text();
62 throw new Error(`OpenAI Vision ${res.status}: ${text.slice(0, 400)}`);
63 }
64 const json = (await res.json()) as {
65 choices?: { message?: { content?: string } }[];
66 };
67 const content = json?.choices?.[0]?.message?.content?.trim();
68 if (!content) throw new Error('OpenAI Vision returned no content');
69 return content;
70}