UNPKG

wuchale

Version:

Protobuf-like i18n from plain code

43 lines (42 loc) 1.43 kB
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent'; const headers = { 'Content-Type': 'application/json' }; function prepareData(content, instruction, think) { return { system_instruction: { parts: [{ text: instruction }] }, contents: [{ parts: [{ text: content }] }], generationConfig: think ? undefined : { thinkingConfig: { thinkingBudget: 0 } } }; } export function gemini({ apiKey = 'env', batchSize = 50, think = false, parallel = 4 } = {}) { if (apiKey === 'env') { apiKey = process.env.GEMINI_API_KEY ?? ''; } if (!apiKey) { return null; } return { name: 'Gemini', batchSize, parallel, translate: async (content, instruction) => { const data = prepareData(content, instruction, think); const res = await fetch(url, { method: 'POST', headers: { ...headers, 'x-goog-api-key': apiKey }, body: JSON.stringify(data) }); const json = await res.json(); if (json.error) { throw new Error(`error: ${json.error.code} ${json.error.message}`); } return json.candidates?.[0]?.content.parts[0].text ?? ''; }, }; } export const defaultGemini = gemini();