UNPKG

nuxt-alt-generator

Version:

Nuxt module that generates alt text for images using AI

60 lines (57 loc) 1.95 kB
import { getOpenAI } from "./openai.js"; import { createError, defineCachedFunction, useRuntimeConfig } from "#imports"; const getSystemPropmt = (context) => ` You will be given an image and a language. You will return the alt text for it taking into account best SEO and accessibility practices in the given language. ${context && "While generating the alt text, take into account the context of the website for including the relevant key-words.'" + context + "'"} Only return the alt text, do not add any other text. `; const getAcceptLanguageHeader = (event) => { const acceptLanguageHeader = event.node.req.headers["accept-language"]?.split(",")[0]; return acceptLanguageHeader || "en"; }; export const generateAltTextFromImage = defineCachedFunction( async ({ src }, event) => { const runtimeConfig = useRuntimeConfig(event).altGenerator; if (!runtimeConfig.enabled) { return `Example generated alt text for ${src}`; } const instance = getOpenAI(event); const response = await instance.responses.create({ // @todo: add support for other models model: "gpt-4.1-nano", temperature: 0.1, store: true, input: [ { role: "user", content: getSystemPropmt(runtimeConfig.ai.context) }, { role: "user", content: [ { type: "input_image", image_url: src, // @todo add support for local images? detail: "low" }, { type: "input_text", text: `Language code: ${getAcceptLanguageHeader(event)}` } ] } ] }); if (response.error) { throw createError(response.error); } return response.output_text; }, { maxAge: 1e3 * 60 * 60 * 24, // 1 day getKey: ({ src }, event) => `generated-alt:${src}:${getAcceptLanguageHeader(event)}` } );