@jhb.software/payload-alt-text-plugin 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +225 -36
- package/dist/components/BulkGenerateAltTextsButton.js +3 -16
- package/dist/components/BulkGenerateAltTextsButton.js.map +1 -1
- package/dist/components/summarizeBulkGenerate.d.ts +26 -0
- package/dist/components/summarizeBulkGenerate.js +56 -0
- package/dist/components/summarizeBulkGenerate.js.map +1 -0
- package/dist/endpoints/bulkGenerateAltTexts.d.ts +18 -1
- package/dist/endpoints/bulkGenerateAltTexts.js +39 -16
- package/dist/endpoints/bulkGenerateAltTexts.js.map +1 -1
- package/dist/endpoints/generateAltText.js +17 -9
- package/dist/endpoints/generateAltText.js.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/plugin.js +20 -4
- package/dist/plugin.js.map +1 -1
- package/dist/resolvers/anthropic.d.ts +64 -0
- package/dist/resolvers/anthropic.js +140 -0
- package/dist/resolvers/anthropic.js.map +1 -0
- package/dist/resolvers/createVisionResolver.d.ts +148 -0
- package/dist/resolvers/createVisionResolver.js +300 -0
- package/dist/resolvers/createVisionResolver.js.map +1 -0
- package/dist/resolvers/mistral.d.ts +15 -1
- package/dist/resolvers/mistral.js +85 -250
- package/dist/resolvers/mistral.js.map +1 -1
- package/dist/resolvers/openAI.d.ts +22 -3
- package/dist/resolvers/openAI.js +57 -138
- package/dist/resolvers/openAI.js.map +1 -1
- package/dist/translations/de.js +12 -4
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +12 -4
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/translation-schema.json +24 -8
- package/dist/types/AltTextPluginConfig.d.ts +71 -12
- package/dist/types/AltTextPluginConfig.js.map +1 -1
- package/dist/utilities/altTextHealth.d.ts +3 -1
- package/dist/utilities/altTextHealth.js +103 -12
- package/dist/utilities/altTextHealth.js.map +1 -1
- package/dist/utilities/resolveLocales.d.ts +15 -0
- package/dist/utilities/resolveLocales.js +38 -0
- package/dist/utilities/resolveLocales.js.map +1 -0
- package/dist/utilities/stableStringify.d.ts +9 -0
- package/dist/utilities/stableStringify.js +19 -0
- package/dist/utilities/stableStringify.js.map +1 -0
- package/package.json +4 -5
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { createVisionResolver, VisionProviderError } from './createVisionResolver.js';
|
|
2
|
+
/**
|
|
3
|
+
* Image formats the Messages API accepts.
|
|
4
|
+
*
|
|
5
|
+
* Narrower than what an upload collection may hold — SVG and AVIF are missing,
|
|
6
|
+
* so the endpoint rejects those documents and their generate button stays
|
|
7
|
+
* disabled instead of failing at the provider.
|
|
8
|
+
*
|
|
9
|
+
* @see https://platform.claude.com/docs/en/build-with-claude/vision
|
|
10
|
+
*/ const SUPPORTED_MIME_TYPES = [
|
|
11
|
+
'image/jpeg',
|
|
12
|
+
'image/png',
|
|
13
|
+
'image/gif',
|
|
14
|
+
'image/webp'
|
|
15
|
+
];
|
|
16
|
+
/**
|
|
17
|
+
* Claude's 10 MB ceiling is measured on the base64 payload, which inflates the
|
|
18
|
+
* raw bytes by roughly 4/3 — so the guard has to sit at ~7.5 MB of raw image to
|
|
19
|
+
* mean 10 MB on the wire. Checking the raw length against 10 MB would wave
|
|
20
|
+
* through a 9 MB photo that arrives as ~12 MB and is rejected by the provider,
|
|
21
|
+
* costing the download and replacing a readable message with a raw 400.
|
|
22
|
+
*/ const MAX_IMAGE_BYTES = Math.floor(10 * 1024 * 1024 * 3 / 4);
|
|
23
|
+
/**
|
|
24
|
+
* Room for one alt text and its keywords per locale, plus the thinking tokens
|
|
25
|
+
* Claude spends before answering. A budget sized for the answer alone would be
|
|
26
|
+
* exhausted while reasoning, and the response would be cut off mid-JSON.
|
|
27
|
+
*/ const MAX_TOKENS_PER_LOCALE = 2000;
|
|
28
|
+
/**
|
|
29
|
+
* Creates a Claude-based resolver for alt text generation.
|
|
30
|
+
*
|
|
31
|
+
* The image is downloaded and sent as bytes. Claude can fetch an image URL
|
|
32
|
+
* itself, but that path is not dependable for a CMS: it requires the file to be
|
|
33
|
+
* reachable from the public internet. Sending the bytes removes that whole class
|
|
34
|
+
* of failure for the price of one extra download. The `media_type` a base64 image block carries
|
|
35
|
+
* comes from the download, which reads it off what the thumbnail URL served.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* import { anthropicResolver } from '@jhb.software/payload-alt-text-plugin'
|
|
40
|
+
*
|
|
41
|
+
* anthropicResolver({
|
|
42
|
+
* apiKey: process.env.ANTHROPIC_API_KEY,
|
|
43
|
+
* model: 'claude-opus-5', // optional, this is the default
|
|
44
|
+
* })
|
|
45
|
+
* ```
|
|
46
|
+
*/ export const anthropicResolver = ({ apiKey, baseUrl = 'https://api.anthropic.com', effort, instructions, model = 'claude-opus-5', timeoutMs = 30_000 })=>createVisionResolver({
|
|
47
|
+
apiKey,
|
|
48
|
+
generate: async ({ filename, image, instructions: resolvedInstructions, maxTokens, responseSchema, signal })=>{
|
|
49
|
+
if (!image) {
|
|
50
|
+
throw new Error('The image was not downloaded');
|
|
51
|
+
}
|
|
52
|
+
const response = await fetch(`${baseUrl}/v1/messages`, {
|
|
53
|
+
body: JSON.stringify({
|
|
54
|
+
max_tokens: maxTokens,
|
|
55
|
+
messages: [
|
|
56
|
+
{
|
|
57
|
+
content: [
|
|
58
|
+
// Claude works best when the image comes before the text.
|
|
59
|
+
{
|
|
60
|
+
type: 'image',
|
|
61
|
+
source: {
|
|
62
|
+
type: 'base64',
|
|
63
|
+
data: image.base64,
|
|
64
|
+
media_type: image.mediaType
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
...filename ? [
|
|
68
|
+
{
|
|
69
|
+
type: 'text',
|
|
70
|
+
text: filename
|
|
71
|
+
}
|
|
72
|
+
] : []
|
|
73
|
+
],
|
|
74
|
+
role: 'user'
|
|
75
|
+
}
|
|
76
|
+
],
|
|
77
|
+
model,
|
|
78
|
+
// `format` constrains the response to the schema the plugin needs;
|
|
79
|
+
// `effort` caps how long Claude thinks before producing it. Only sent
|
|
80
|
+
// when configured: some models reject the field outright.
|
|
81
|
+
output_config: {
|
|
82
|
+
...effort ? {
|
|
83
|
+
effort
|
|
84
|
+
} : {},
|
|
85
|
+
format: {
|
|
86
|
+
type: 'json_schema',
|
|
87
|
+
schema: responseSchema
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
// The instructions are an operator instruction, not a turn in the
|
|
91
|
+
// conversation, so they travel as the top-level system prompt.
|
|
92
|
+
system: resolvedInstructions
|
|
93
|
+
}),
|
|
94
|
+
headers: {
|
|
95
|
+
'anthropic-version': '2023-06-01',
|
|
96
|
+
'content-type': 'application/json',
|
|
97
|
+
'x-api-key': apiKey
|
|
98
|
+
},
|
|
99
|
+
method: 'POST',
|
|
100
|
+
signal
|
|
101
|
+
});
|
|
102
|
+
if (!response.ok) {
|
|
103
|
+
// Bounded: unbounded provider text would land in the log as-is.
|
|
104
|
+
const body = (await response.text().catch(()=>'')).slice(0, 500);
|
|
105
|
+
throw new VisionProviderError({
|
|
106
|
+
body,
|
|
107
|
+
label: 'Anthropic',
|
|
108
|
+
status: response.status
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const message = await response.json();
|
|
112
|
+
// A refusal and a truncated answer both arrive as a 200 with unusable
|
|
113
|
+
// content, so they are named rather than surfacing as a JSON parse error.
|
|
114
|
+
if (message.stop_reason === 'refusal') {
|
|
115
|
+
throw new Error('Claude declined to describe this image');
|
|
116
|
+
}
|
|
117
|
+
if (message.stop_reason === 'max_tokens') {
|
|
118
|
+
throw new Error(`Claude ran out of tokens before finishing the alt text (max_tokens: ${maxTokens})`);
|
|
119
|
+
}
|
|
120
|
+
const text = message.content?.find((block)=>block.type === 'text')?.text;
|
|
121
|
+
if (typeof text !== 'string') {
|
|
122
|
+
throw new Error('No result from Anthropic');
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
return JSON.parse(text);
|
|
126
|
+
} catch {
|
|
127
|
+
throw new Error('Claude returned a response that was not valid JSON');
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
inlineImage: true,
|
|
131
|
+
instructions,
|
|
132
|
+
key: 'anthropic',
|
|
133
|
+
label: 'Anthropic',
|
|
134
|
+
maxImageBytes: MAX_IMAGE_BYTES,
|
|
135
|
+
maxTokensPerLocale: MAX_TOKENS_PER_LOCALE,
|
|
136
|
+
supportedMimeTypes: SUPPORTED_MIME_TYPES,
|
|
137
|
+
timeoutMs
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
//# sourceMappingURL=anthropic.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/resolvers/anthropic.ts"],"sourcesContent":["import type { VisionInstructions } from './createVisionResolver.js'\nimport type { AltTextResolver } from './types.js'\n\nimport { createVisionResolver, VisionProviderError } from './createVisionResolver.js'\n\nexport type AnthropicResolverConfig = {\n /** Anthropic API key for authentication */\n apiKey: string\n /**\n * Base URL of the Anthropic API.\n * @default 'https://api.anthropic.com'\n */\n baseUrl?: string\n /**\n * Caps how long Claude thinks before answering. Lower effort still thinks on a\n * difficult image, just less than a higher setting would.\n *\n * Describing an image is not a reasoning-heavy task, so `'low'` keeps the\n * spend down on the models that accept it. Omitted, the field is not sent and\n * Claude uses its default (`'high'`) — which also keeps models without effort\n * support, such as `claude-haiku-4-5`, usable.\n */\n effort?: 'high' | 'low' | 'max' | 'medium' | 'xhigh'\n /**\n * Builds the instructions from the default ones, e.g. to append a house style\n * rule. Sent as the system prompt, separately from the image.\n *\n * @default ({ defaultInstructions }) => defaultInstructions\n */\n instructions?: VisionInstructions\n /**\n * The Claude model to use for alt text generation.\n *\n * Must be able to read images. `claude-sonnet-5` is the cheaper choice for a\n * large media library; `claude-haiku-4-5` works too, but only without\n * `effort`.\n *\n * @default 'claude-opus-5'\n */\n model?: string\n /**\n * Abort after this many milliseconds. Covers downloading the image and the\n * message call together.\n * @default 30000\n */\n timeoutMs?: number\n}\n\n/**\n * Image formats the Messages API accepts.\n *\n * Narrower than what an upload collection may hold — SVG and AVIF are missing,\n * so the endpoint rejects those documents and their generate button stays\n * disabled instead of failing at the provider.\n *\n * @see https://platform.claude.com/docs/en/build-with-claude/vision\n */\nconst SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']\n\n/**\n * Claude's 10 MB ceiling is measured on the base64 payload, which inflates the\n * raw bytes by roughly 4/3 — so the guard has to sit at ~7.5 MB of raw image to\n * mean 10 MB on the wire. Checking the raw length against 10 MB would wave\n * through a 9 MB photo that arrives as ~12 MB and is rejected by the provider,\n * costing the download and replacing a readable message with a raw 400.\n */\nconst MAX_IMAGE_BYTES = Math.floor((10 * 1024 * 1024 * 3) / 4)\n\n/**\n * Room for one alt text and its keywords per locale, plus the thinking tokens\n * Claude spends before answering. A budget sized for the answer alone would be\n * exhausted while reasoning, and the response would be cut off mid-JSON.\n */\nconst MAX_TOKENS_PER_LOCALE = 2000\n\ntype AnthropicMessage = {\n content?: { text?: string; type: string }[]\n stop_reason?: string\n}\n\n/**\n * Creates a Claude-based resolver for alt text generation.\n *\n * The image is downloaded and sent as bytes. Claude can fetch an image URL\n * itself, but that path is not dependable for a CMS: it requires the file to be\n * reachable from the public internet. Sending the bytes removes that whole class\n * of failure for the price of one extra download. The `media_type` a base64 image block carries\n * comes from the download, which reads it off what the thumbnail URL served.\n *\n * @example\n * ```typescript\n * import { anthropicResolver } from '@jhb.software/payload-alt-text-plugin'\n *\n * anthropicResolver({\n * apiKey: process.env.ANTHROPIC_API_KEY,\n * model: 'claude-opus-5', // optional, this is the default\n * })\n * ```\n */\nexport const anthropicResolver = ({\n apiKey,\n baseUrl = 'https://api.anthropic.com',\n effort,\n instructions,\n model = 'claude-opus-5',\n timeoutMs = 30_000,\n}: AnthropicResolverConfig): AltTextResolver =>\n createVisionResolver({\n apiKey,\n generate: async ({\n filename,\n image,\n instructions: resolvedInstructions,\n maxTokens,\n responseSchema,\n signal,\n }) => {\n if (!image) {\n throw new Error('The image was not downloaded')\n }\n\n const response = await fetch(`${baseUrl}/v1/messages`, {\n body: JSON.stringify({\n max_tokens: maxTokens,\n messages: [\n {\n content: [\n // Claude works best when the image comes before the text.\n {\n type: 'image',\n source: { type: 'base64', data: image.base64, media_type: image.mediaType },\n },\n ...(filename ? [{ type: 'text', text: filename }] : []),\n ],\n role: 'user',\n },\n ],\n model,\n // `format` constrains the response to the schema the plugin needs;\n // `effort` caps how long Claude thinks before producing it. Only sent\n // when configured: some models reject the field outright.\n output_config: {\n ...(effort ? { effort } : {}),\n format: { type: 'json_schema', schema: responseSchema },\n },\n // The instructions are an operator instruction, not a turn in the\n // conversation, so they travel as the top-level system prompt.\n system: resolvedInstructions,\n }),\n headers: {\n 'anthropic-version': '2023-06-01',\n 'content-type': 'application/json',\n 'x-api-key': apiKey,\n },\n method: 'POST',\n signal,\n })\n\n if (!response.ok) {\n // Bounded: unbounded provider text would land in the log as-is.\n const body = (await response.text().catch(() => '')).slice(0, 500)\n\n throw new VisionProviderError({ body, label: 'Anthropic', status: response.status })\n }\n\n const message = (await response.json()) as AnthropicMessage\n\n // A refusal and a truncated answer both arrive as a 200 with unusable\n // content, so they are named rather than surfacing as a JSON parse error.\n if (message.stop_reason === 'refusal') {\n throw new Error('Claude declined to describe this image')\n }\n\n if (message.stop_reason === 'max_tokens') {\n throw new Error(\n `Claude ran out of tokens before finishing the alt text (max_tokens: ${maxTokens})`,\n )\n }\n\n const text = message.content?.find((block) => block.type === 'text')?.text\n\n if (typeof text !== 'string') {\n throw new Error('No result from Anthropic')\n }\n\n try {\n return JSON.parse(text)\n } catch {\n throw new Error('Claude returned a response that was not valid JSON')\n }\n },\n inlineImage: true,\n instructions,\n key: 'anthropic',\n label: 'Anthropic',\n maxImageBytes: MAX_IMAGE_BYTES,\n maxTokensPerLocale: MAX_TOKENS_PER_LOCALE,\n supportedMimeTypes: SUPPORTED_MIME_TYPES,\n timeoutMs,\n })\n"],"names":["createVisionResolver","VisionProviderError","SUPPORTED_MIME_TYPES","MAX_IMAGE_BYTES","Math","floor","MAX_TOKENS_PER_LOCALE","anthropicResolver","apiKey","baseUrl","effort","instructions","model","timeoutMs","generate","filename","image","resolvedInstructions","maxTokens","responseSchema","signal","Error","response","fetch","body","JSON","stringify","max_tokens","messages","content","type","source","data","base64","media_type","mediaType","text","role","output_config","format","schema","system","headers","method","ok","catch","slice","label","status","message","json","stop_reason","find","block","parse","inlineImage","key","maxImageBytes","maxTokensPerLocale","supportedMimeTypes"],"mappings":"AAGA,SAASA,oBAAoB,EAAEC,mBAAmB,QAAQ,4BAA2B;AA6CrF;;;;;;;;CAQC,GACD,MAAMC,uBAAuB;IAAC;IAAc;IAAa;IAAa;CAAa;AAEnF;;;;;;CAMC,GACD,MAAMC,kBAAkBC,KAAKC,KAAK,CAAC,AAAC,KAAK,OAAO,OAAO,IAAK;AAE5D;;;;CAIC,GACD,MAAMC,wBAAwB;AAO9B;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,MAAM,EACNC,UAAU,2BAA2B,EACrCC,MAAM,EACNC,YAAY,EACZC,QAAQ,eAAe,EACvBC,YAAY,MAAM,EACM,GACxBb,qBAAqB;QACnBQ;QACAM,UAAU,OAAO,EACfC,QAAQ,EACRC,KAAK,EACLL,cAAcM,oBAAoB,EAClCC,SAAS,EACTC,cAAc,EACdC,MAAM,EACP;YACC,IAAI,CAACJ,OAAO;gBACV,MAAM,IAAIK,MAAM;YAClB;YAEA,MAAMC,WAAW,MAAMC,MAAM,GAAGd,QAAQ,YAAY,CAAC,EAAE;gBACrDe,MAAMC,KAAKC,SAAS,CAAC;oBACnBC,YAAYT;oBACZU,UAAU;wBACR;4BACEC,SAAS;gCACP,0DAA0D;gCAC1D;oCACEC,MAAM;oCACNC,QAAQ;wCAAED,MAAM;wCAAUE,MAAMhB,MAAMiB,MAAM;wCAAEC,YAAYlB,MAAMmB,SAAS;oCAAC;gCAC5E;mCACIpB,WAAW;oCAAC;wCAAEe,MAAM;wCAAQM,MAAMrB;oCAAS;iCAAE,GAAG,EAAE;6BACvD;4BACDsB,MAAM;wBACR;qBACD;oBACDzB;oBACA,mEAAmE;oBACnE,sEAAsE;oBACtE,0DAA0D;oBAC1D0B,eAAe;wBACb,GAAI5B,SAAS;4BAAEA;wBAAO,IAAI,CAAC,CAAC;wBAC5B6B,QAAQ;4BAAET,MAAM;4BAAeU,QAAQrB;wBAAe;oBACxD;oBACA,kEAAkE;oBAClE,+DAA+D;oBAC/DsB,QAAQxB;gBACV;gBACAyB,SAAS;oBACP,qBAAqB;oBACrB,gBAAgB;oBAChB,aAAalC;gBACf;gBACAmC,QAAQ;gBACRvB;YACF;YAEA,IAAI,CAACE,SAASsB,EAAE,EAAE;gBAChB,gEAAgE;gBAChE,MAAMpB,OAAO,AAAC,CAAA,MAAMF,SAASc,IAAI,GAAGS,KAAK,CAAC,IAAM,GAAE,EAAGC,KAAK,CAAC,GAAG;gBAE9D,MAAM,IAAI7C,oBAAoB;oBAAEuB;oBAAMuB,OAAO;oBAAaC,QAAQ1B,SAAS0B,MAAM;gBAAC;YACpF;YAEA,MAAMC,UAAW,MAAM3B,SAAS4B,IAAI;YAEpC,sEAAsE;YACtE,0EAA0E;YAC1E,IAAID,QAAQE,WAAW,KAAK,WAAW;gBACrC,MAAM,IAAI9B,MAAM;YAClB;YAEA,IAAI4B,QAAQE,WAAW,KAAK,cAAc;gBACxC,MAAM,IAAI9B,MACR,CAAC,oEAAoE,EAAEH,UAAU,CAAC,CAAC;YAEvF;YAEA,MAAMkB,OAAOa,QAAQpB,OAAO,EAAEuB,KAAK,CAACC,QAAUA,MAAMvB,IAAI,KAAK,SAASM;YAEtE,IAAI,OAAOA,SAAS,UAAU;gBAC5B,MAAM,IAAIf,MAAM;YAClB;YAEA,IAAI;gBACF,OAAOI,KAAK6B,KAAK,CAAClB;YACpB,EAAE,OAAM;gBACN,MAAM,IAAIf,MAAM;YAClB;QACF;QACAkC,aAAa;QACb5C;QACA6C,KAAK;QACLT,OAAO;QACPU,eAAetD;QACfuD,oBAAoBpD;QACpBqD,oBAAoBzD;QACpBW;IACF,GAAE"}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import type { AltTextResolver } from './types.js';
|
|
4
|
+
export type VisionInstructionsArgs = {
|
|
5
|
+
/** The instructions the resolver would send on its own, stating the rules the plugin depends on */
|
|
6
|
+
defaultInstructions: string;
|
|
7
|
+
/** The uploaded file's name, when the endpoint could supply one */
|
|
8
|
+
filename?: string;
|
|
9
|
+
/** The locales the response must cover, as configured in Payload */
|
|
10
|
+
locales: string[];
|
|
11
|
+
};
|
|
12
|
+
export type VisionInstructions = (args: VisionInstructionsArgs) => Promise<string> | string;
|
|
13
|
+
/** The thumbnail's bytes, handed to providers that declared `inlineImage`. */
|
|
14
|
+
export type VisionImage = {
|
|
15
|
+
/** Base64-encoded bytes, without a data URI prefix */
|
|
16
|
+
base64: string;
|
|
17
|
+
/** `data:<mediaType>;base64,<base64>`, for providers that take a data URI */
|
|
18
|
+
dataUri: string;
|
|
19
|
+
/** The format actually served at the thumbnail URL, not the document's stored one */
|
|
20
|
+
mediaType: string;
|
|
21
|
+
};
|
|
22
|
+
export type VisionGenerateArgs = {
|
|
23
|
+
/** The uploaded file's name, when the endpoint could supply one */
|
|
24
|
+
filename?: string;
|
|
25
|
+
/** The downloaded thumbnail — present only when the resolver declared `inlineImage` */
|
|
26
|
+
image?: VisionImage;
|
|
27
|
+
/**
|
|
28
|
+
* The format the collection declares `getImageThumbnail` delivers, or
|
|
29
|
+
* undefined when nothing was declared. Resolvers that inline the bytes should
|
|
30
|
+
* use `image.mediaType`, which is what the URL actually served, with this
|
|
31
|
+
* declaration already standing in when the host named no usable type.
|
|
32
|
+
*/
|
|
33
|
+
imageThumbnailMimeType?: string;
|
|
34
|
+
/** URL of the image thumbnail, for providers that fetch it themselves */
|
|
35
|
+
imageThumbnailUrl: string;
|
|
36
|
+
/** The instructions to send, e.g. as the system prompt */
|
|
37
|
+
instructions: string;
|
|
38
|
+
/** The locales the response must cover */
|
|
39
|
+
locales: string[];
|
|
40
|
+
/** Token budget for the response, scaled by the number of requested locales */
|
|
41
|
+
maxTokens: number;
|
|
42
|
+
req: PayloadRequest;
|
|
43
|
+
/** Draft-7 JSON Schema of the object the provider must return */
|
|
44
|
+
responseSchema: Record<string, unknown>;
|
|
45
|
+
/**
|
|
46
|
+
* Aborts once `timeoutMs` has elapsed, already covering the image download.
|
|
47
|
+
* Undefined when the resolver declares no `timeoutMs`, leaving the deadline to
|
|
48
|
+
* the provider client.
|
|
49
|
+
*/
|
|
50
|
+
signal?: AbortSignal;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* A non-ok HTTP response from a provider.
|
|
54
|
+
*
|
|
55
|
+
* Carries the status so the factory can tell a rate limit or an outage — worth
|
|
56
|
+
* another attempt — from a malformed request, which would fail identically every
|
|
57
|
+
* time.
|
|
58
|
+
*
|
|
59
|
+
* The response body is kept off `message` deliberately. That message is shown in
|
|
60
|
+
* the admin panel to anyone allowed to generate an alt text, while the body is
|
|
61
|
+
* text the provider chose: OpenAI echoes a masked form of the rejected API key
|
|
62
|
+
* into a 401, and providers routinely name organization ids, project ids and
|
|
63
|
+
* internal endpoints. It goes to the server log, where the person debugging the
|
|
64
|
+
* configuration is, and not to an editor's screen.
|
|
65
|
+
*/
|
|
66
|
+
export declare class VisionProviderError extends Error {
|
|
67
|
+
/** The provider's response body, for the log only — never for `message`. */
|
|
68
|
+
readonly body?: string;
|
|
69
|
+
readonly status: number;
|
|
70
|
+
constructor({ body, label, status }: {
|
|
71
|
+
body?: string;
|
|
72
|
+
label: string;
|
|
73
|
+
status: number;
|
|
74
|
+
});
|
|
75
|
+
/** Rate limits and server-side failures are transient; a 4xx is not. */
|
|
76
|
+
get isTransient(): boolean;
|
|
77
|
+
}
|
|
78
|
+
export type VisionResolverConfig = {
|
|
79
|
+
/**
|
|
80
|
+
* Checked before any work happens, so a plugin wired as
|
|
81
|
+
* `enabled: !!process.env.X_API_KEY` fails with a readable message instead of
|
|
82
|
+
* a provider error — or, worse, a paid-for image download.
|
|
83
|
+
*/
|
|
84
|
+
apiKey: string;
|
|
85
|
+
/**
|
|
86
|
+
* Sends one request to the provider and resolves with its parsed JSON
|
|
87
|
+
* response. Rejecting fails the generation, so provider errors need no
|
|
88
|
+
* special handling beyond throwing a readable message.
|
|
89
|
+
*/
|
|
90
|
+
generate: (args: VisionGenerateArgs) => Promise<unknown>;
|
|
91
|
+
/**
|
|
92
|
+
* Download the thumbnail and hand `generate` the bytes rather than the URL.
|
|
93
|
+
*
|
|
94
|
+
* Needed by every provider whose own fetcher requires a publicly reachable
|
|
95
|
+
* file.
|
|
96
|
+
*/
|
|
97
|
+
inlineImage?: boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Builds the instructions from the default ones, e.g. to append a house style
|
|
100
|
+
* rule. Called once per generation. The image and the required response shape
|
|
101
|
+
* are not part of the instructions and cannot be altered here.
|
|
102
|
+
*
|
|
103
|
+
* @default ({ defaultInstructions }) => defaultInstructions
|
|
104
|
+
*/
|
|
105
|
+
instructions?: VisionInstructions;
|
|
106
|
+
/** Identifies the resolver, e.g. in log entries */
|
|
107
|
+
key: string;
|
|
108
|
+
/** Provider name used in error messages shown in the admin UI */
|
|
109
|
+
label: string;
|
|
110
|
+
/**
|
|
111
|
+
* Rejects an inlined image above this size before it is sent.
|
|
112
|
+
* @default 20971520 (20 MB)
|
|
113
|
+
*/
|
|
114
|
+
maxImageBytes?: number;
|
|
115
|
+
/**
|
|
116
|
+
* Token budget granted per requested locale. A ceiling, not a reservation, so
|
|
117
|
+
* headroom is free; the default keeps the pre-factory bulk budget of 300 for
|
|
118
|
+
* every locale count rather than only for two or more.
|
|
119
|
+
* @default 300
|
|
120
|
+
*/
|
|
121
|
+
maxTokensPerLocale?: number;
|
|
122
|
+
/** @see AltTextResolver.supportedMimeTypes */
|
|
123
|
+
supportedMimeTypes?: string[];
|
|
124
|
+
/**
|
|
125
|
+
* Abort after this many milliseconds, covering the image download and the
|
|
126
|
+
* provider call together. Omit it to impose no deadline of the factory's own —
|
|
127
|
+
* appropriate when the provider's own client already has one.
|
|
128
|
+
*/
|
|
129
|
+
timeoutMs?: number;
|
|
130
|
+
};
|
|
131
|
+
/** One schema entry per requested locale, so the model must answer for all of them. */
|
|
132
|
+
export declare const schemaForLocales: (locales: string[]) => z.ZodObject<{
|
|
133
|
+
[x: string]: z.ZodObject<{
|
|
134
|
+
altText: z.ZodString;
|
|
135
|
+
keywords: z.ZodArray<z.ZodString>;
|
|
136
|
+
}, z.core.$strip>;
|
|
137
|
+
}, z.core.$strip>;
|
|
138
|
+
/**
|
|
139
|
+
* Creates a resolver for a vision (LLM) provider, leaving only the provider call
|
|
140
|
+
* to `generate`: the prompt, the required response schema, the optional image
|
|
141
|
+
* download and the strict reading of the response are handled here.
|
|
142
|
+
*
|
|
143
|
+
* All locales go into a single call rather than one call each: the image is
|
|
144
|
+
* uploaded and analyzed once — the expensive part — and every language ends up
|
|
145
|
+
* describing the same reading of it. `resolve` is that same call with one
|
|
146
|
+
* locale.
|
|
147
|
+
*/
|
|
148
|
+
export declare const createVisionResolver: ({ apiKey, generate, inlineImage, instructions, key, label, maxImageBytes, maxTokensPerLocale, supportedMimeTypes, timeoutMs, }: VisionResolverConfig) => AltTextResolver;
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/**
|
|
3
|
+
* A non-ok HTTP response from a provider.
|
|
4
|
+
*
|
|
5
|
+
* Carries the status so the factory can tell a rate limit or an outage — worth
|
|
6
|
+
* another attempt — from a malformed request, which would fail identically every
|
|
7
|
+
* time.
|
|
8
|
+
*
|
|
9
|
+
* The response body is kept off `message` deliberately. That message is shown in
|
|
10
|
+
* the admin panel to anyone allowed to generate an alt text, while the body is
|
|
11
|
+
* text the provider chose: OpenAI echoes a masked form of the rejected API key
|
|
12
|
+
* into a 401, and providers routinely name organization ids, project ids and
|
|
13
|
+
* internal endpoints. It goes to the server log, where the person debugging the
|
|
14
|
+
* configuration is, and not to an editor's screen.
|
|
15
|
+
*/ export class VisionProviderError extends Error {
|
|
16
|
+
/** The provider's response body, for the log only — never for `message`. */ body;
|
|
17
|
+
status;
|
|
18
|
+
constructor({ body, label, status }){
|
|
19
|
+
super(`${label} responded with status ${status}`);
|
|
20
|
+
this.body = body;
|
|
21
|
+
this.name = 'VisionProviderError';
|
|
22
|
+
this.status = status;
|
|
23
|
+
}
|
|
24
|
+
/** Rate limits and server-side failures are transient; a 4xx is not. */ get isTransient() {
|
|
25
|
+
return this.status === 429 || this.status >= 500;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** Attempts after the first, for a provider error that may pass on a retry. */ const MAX_RETRIES = 2;
|
|
29
|
+
/** Backs off between attempts, bounded by the resolver's own deadline. */ const retryDelayMs = (attempt)=>250 * 2 ** (attempt - 1);
|
|
30
|
+
const altTextSchema = z.object({
|
|
31
|
+
altText: z.string().describe('A concise, descriptive alt text for the image'),
|
|
32
|
+
keywords: z.array(z.string()).describe('Keywords that describe the content of the image')
|
|
33
|
+
});
|
|
34
|
+
/** One schema entry per requested locale, so the model must answer for all of them. */ export const schemaForLocales = (locales)=>z.object(Object.fromEntries(locales.map((locale)=>[
|
|
35
|
+
locale,
|
|
36
|
+
altTextSchema
|
|
37
|
+
])));
|
|
38
|
+
/**
|
|
39
|
+
* Rules dictated by the plugin rather than by the provider: one entry per
|
|
40
|
+
* configured locale, describing what is visible rather than guessing at it.
|
|
41
|
+
*/ const buildDefaultInstructions = ({ locales })=>[
|
|
42
|
+
`You are an expert at analyzing images and creating descriptive image alt text.`,
|
|
43
|
+
`Please analyze the given image and provide the following in ${locales.join(', ')}:`,
|
|
44
|
+
`- A concise, localized descriptive alt text (1-2 sentences) as "altText". Focus on the subject, action, and setting. Avoid phrases like 'Image of', 'A picture of', or 'Photo showing'. Be specific and include relevant details like location or context if visible. Make no assumptions.`,
|
|
45
|
+
`- A localized list of keywords that describe the content (e.g., ["Camel", "Palm trees", "Desert"]) as "keywords"`,
|
|
46
|
+
`If a context is provided, use it to enhance the alt text.`,
|
|
47
|
+
`Format your response as a JSON object with ${locales.map((locale)=>`"${locale}"`).join(', ')} keys, each containing "altText" and "keywords".`
|
|
48
|
+
].join('\n\n');
|
|
49
|
+
/**
|
|
50
|
+
* Downloads the image and returns its bytes.
|
|
51
|
+
*
|
|
52
|
+
* The document's mime type is checked by the endpoint before the resolver runs,
|
|
53
|
+
* but `getImageThumbnail` may point at a derivative in a different format, so
|
|
54
|
+
* what was actually served is what counts. Only when the host names no usable
|
|
55
|
+
* type at all — no header, or a generic `application/octet-stream` as private
|
|
56
|
+
* buckets and signed URLs often send — does the collection's declared
|
|
57
|
+
* `imageThumbnailMimeType` stand in for it.
|
|
58
|
+
*/ async function fetchImage({ declaredMediaType, label, maxImageBytes, signal, supportedMimeTypes, url }) {
|
|
59
|
+
let response;
|
|
60
|
+
try {
|
|
61
|
+
response = await fetch(url, {
|
|
62
|
+
signal
|
|
63
|
+
});
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return {
|
|
66
|
+
error: `Could not download the image from ${url}: ${error instanceof Error ? error.message : 'unknown error'}`
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
if (!response.ok) {
|
|
70
|
+
return {
|
|
71
|
+
error: `Could not download the image from ${url}: status ${response.status}`
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const served = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
|
|
75
|
+
const mediaType = served && served !== 'application/octet-stream' ? served : declaredMediaType?.toLowerCase();
|
|
76
|
+
if (!mediaType) {
|
|
77
|
+
return {
|
|
78
|
+
error: `The image at ${url} was served as ${served ? `"${served}"` : 'no content type at all'}, which does not name an image format. Declare imageThumbnailMimeType for the collection so ${label} knows what it is reading.`
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
if (supportedMimeTypes && !supportedMimeTypes.includes(mediaType)) {
|
|
82
|
+
return {
|
|
83
|
+
error: `The image at ${url} was served as "${mediaType}", which ${label} cannot read. Supported types: ${supportedMimeTypes.join(', ')}.`
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
const tooLarge = (byteLength)=>`The image at ${url} is ${Math.round(byteLength / 1024 / 1024)} MB, above ${label}'s ${Math.round(maxImageBytes / 1024 / 1024)} MB limit. Point getImageThumbnail at a smaller image size.`;
|
|
87
|
+
// Measuring by reading is work the header already answers, and the file is on
|
|
88
|
+
// its way to being rejected: `getImageThumbnail` may point at the original
|
|
89
|
+
// upload, which can be far above the provider's limit.
|
|
90
|
+
const declaredLength = Number(response.headers.get('content-length'));
|
|
91
|
+
if (Number.isInteger(declaredLength) && declaredLength > maxImageBytes) {
|
|
92
|
+
return {
|
|
93
|
+
error: tooLarge(declaredLength)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
97
|
+
if (bytes.byteLength === 0) {
|
|
98
|
+
return {
|
|
99
|
+
error: `The image at ${url} was empty.`
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
if (bytes.byteLength > maxImageBytes) {
|
|
103
|
+
return {
|
|
104
|
+
error: tooLarge(bytes.byteLength)
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const base64 = bytes.toString('base64');
|
|
108
|
+
return {
|
|
109
|
+
image: {
|
|
110
|
+
base64,
|
|
111
|
+
dataUri: `data:${mediaType};base64,${base64}`,
|
|
112
|
+
mediaType
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Runs the provider call, retrying a transient failure.
|
|
118
|
+
*
|
|
119
|
+
* Every bundled resolver reaches its provider over `fetch`, which retries
|
|
120
|
+
* nothing by itself. Without this, a bulk generation that trips a rate limit
|
|
121
|
+
* gives up on the first 429 and leaves those images without an alt text. The
|
|
122
|
+
* resolver's `timeoutMs` covers the attempts together, so a deadline still
|
|
123
|
+
* bounds the whole call.
|
|
124
|
+
*/ async function generateWithRetry({ args, generate }) {
|
|
125
|
+
for(let attempt = 0;; attempt++){
|
|
126
|
+
try {
|
|
127
|
+
return await generate(args);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
const isRetryable = error instanceof VisionProviderError && error.isTransient;
|
|
130
|
+
if (!isRetryable || attempt >= MAX_RETRIES || args.signal?.aborted) {
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
await new Promise((resolve)=>setTimeout(resolve, retryDelayMs(attempt + 1)));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Reads the model's response.
|
|
139
|
+
*
|
|
140
|
+
* Deliberately strict about a blank `altText`: the field is required on the
|
|
141
|
+
* collection, so an empty string would satisfy that requirement while telling a
|
|
142
|
+
* screen reader nothing — and nobody looks at an alt text again once it is set.
|
|
143
|
+
*/ function parseResults(content, locales) {
|
|
144
|
+
const parsed = schemaForLocales(locales).safeParse(content);
|
|
145
|
+
if (!parsed.success) {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
const results = {};
|
|
149
|
+
for (const locale of locales){
|
|
150
|
+
const entry = parsed.data[locale];
|
|
151
|
+
if (entry.altText.trim().length === 0) {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
results[locale] = {
|
|
155
|
+
altText: entry.altText.trim(),
|
|
156
|
+
keywords: entry.keywords
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
return results;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Creates a resolver for a vision (LLM) provider, leaving only the provider call
|
|
163
|
+
* to `generate`: the prompt, the required response schema, the optional image
|
|
164
|
+
* download and the strict reading of the response are handled here.
|
|
165
|
+
*
|
|
166
|
+
* All locales go into a single call rather than one call each: the image is
|
|
167
|
+
* uploaded and analyzed once — the expensive part — and every language ends up
|
|
168
|
+
* describing the same reading of it. `resolve` is that same call with one
|
|
169
|
+
* locale.
|
|
170
|
+
*/ export const createVisionResolver = ({ apiKey, generate, inlineImage = false, instructions = ({ defaultInstructions })=>defaultInstructions, key, label, maxImageBytes = 20 * 1024 * 1024, maxTokensPerLocale = 300, supportedMimeTypes, timeoutMs })=>{
|
|
171
|
+
const run = async ({ filename, imageThumbnailMimeType, imageThumbnailUrl, locales, req })=>{
|
|
172
|
+
if (!apiKey) {
|
|
173
|
+
return {
|
|
174
|
+
error: `No ${label} API key configured`,
|
|
175
|
+
success: false
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
if (locales.length === 0) {
|
|
179
|
+
return {
|
|
180
|
+
error: 'No locale requested',
|
|
181
|
+
success: false
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const signal = timeoutMs === undefined ? undefined : AbortSignal.timeout(timeoutMs);
|
|
185
|
+
let image;
|
|
186
|
+
if (inlineImage) {
|
|
187
|
+
const downloaded = await fetchImage({
|
|
188
|
+
declaredMediaType: imageThumbnailMimeType,
|
|
189
|
+
label,
|
|
190
|
+
maxImageBytes,
|
|
191
|
+
signal,
|
|
192
|
+
supportedMimeTypes,
|
|
193
|
+
url: imageThumbnailUrl
|
|
194
|
+
});
|
|
195
|
+
if ('error' in downloaded) {
|
|
196
|
+
return {
|
|
197
|
+
error: downloaded.error,
|
|
198
|
+
success: false
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
image = downloaded.image;
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
const defaultInstructions = buildDefaultInstructions({
|
|
205
|
+
locales
|
|
206
|
+
});
|
|
207
|
+
const content = await generateWithRetry({
|
|
208
|
+
args: {
|
|
209
|
+
filename,
|
|
210
|
+
image,
|
|
211
|
+
imageThumbnailMimeType,
|
|
212
|
+
imageThumbnailUrl,
|
|
213
|
+
instructions: await instructions({
|
|
214
|
+
defaultInstructions,
|
|
215
|
+
filename,
|
|
216
|
+
locales
|
|
217
|
+
}),
|
|
218
|
+
locales,
|
|
219
|
+
maxTokens: maxTokensPerLocale * locales.length,
|
|
220
|
+
req,
|
|
221
|
+
responseSchema: z.toJSONSchema(schemaForLocales(locales), {
|
|
222
|
+
target: 'draft-7'
|
|
223
|
+
}),
|
|
224
|
+
signal
|
|
225
|
+
},
|
|
226
|
+
generate
|
|
227
|
+
});
|
|
228
|
+
const results = parseResults(content, locales);
|
|
229
|
+
if (!results) {
|
|
230
|
+
return {
|
|
231
|
+
error: `${label} did not return a usable alt text for every requested locale (${locales.join(', ')})`,
|
|
232
|
+
success: false
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
results,
|
|
237
|
+
success: true
|
|
238
|
+
};
|
|
239
|
+
} catch (error) {
|
|
240
|
+
req.payload.logger.error({
|
|
241
|
+
err: error,
|
|
242
|
+
msg: 'Error generating alt text',
|
|
243
|
+
// Logged separately: it is deliberately absent from the error message
|
|
244
|
+
// the admin panel shows, and is what a misconfiguration is diagnosed from.
|
|
245
|
+
providerResponse: error instanceof VisionProviderError ? error.body : undefined,
|
|
246
|
+
resolver: key
|
|
247
|
+
});
|
|
248
|
+
return {
|
|
249
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
250
|
+
success: false
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
return {
|
|
255
|
+
key,
|
|
256
|
+
resolve: async ({ filename, imageThumbnailMimeType, imageThumbnailUrl, locale, req })=>{
|
|
257
|
+
const result = await run({
|
|
258
|
+
filename,
|
|
259
|
+
imageThumbnailMimeType,
|
|
260
|
+
imageThumbnailUrl,
|
|
261
|
+
locales: [
|
|
262
|
+
locale
|
|
263
|
+
],
|
|
264
|
+
req
|
|
265
|
+
});
|
|
266
|
+
if (!result.success) {
|
|
267
|
+
return {
|
|
268
|
+
error: result.error,
|
|
269
|
+
success: false
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
result: result.results[locale],
|
|
274
|
+
success: true
|
|
275
|
+
};
|
|
276
|
+
},
|
|
277
|
+
resolveBulk: async ({ filename, imageThumbnailMimeType, imageThumbnailUrl, locales, req })=>{
|
|
278
|
+
const result = await run({
|
|
279
|
+
filename,
|
|
280
|
+
imageThumbnailMimeType,
|
|
281
|
+
imageThumbnailUrl,
|
|
282
|
+
locales,
|
|
283
|
+
req
|
|
284
|
+
});
|
|
285
|
+
if (!result.success) {
|
|
286
|
+
return {
|
|
287
|
+
error: result.error,
|
|
288
|
+
success: false
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
return {
|
|
292
|
+
results: result.results,
|
|
293
|
+
success: true
|
|
294
|
+
};
|
|
295
|
+
},
|
|
296
|
+
supportedMimeTypes
|
|
297
|
+
};
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
//# sourceMappingURL=createVisionResolver.js.map
|