Batch Translating with Gemini AI
Batch translation is more efficient than individual API calls for multiple texts.
Approach
Combine multiple texts into a single prompt to reduce API overhead.
Prompt Structure
const prompt = `Translate the following Japanese news headlines to English.
Return ONLY a JSON array of objects with "original" and "translated" fields.
Do not include any explanations or formatting outside the JSON.
Headlines to translate:
${headlines.map((h, i) => `${i + 1}. ${h}`).join('\n')}
Expected output format:
[
{"original": "Japanese headline 1", "translated": "English translation 1"},
{"original": "Japanese headline 2", "translated": "English translation 2"}
]
`;
Complete Implementation
async function batchTranslate(headlines: string[]): Promise<Array<{original: string, translated: string}>> {
const prompt = `Translate the following Japanese news headlines to English.
Return ONLY a JSON array with "original" and "translated" fields.
${headlines.map((h, i) => `${i + 1}. ${h}`).join('\n')}
`;
const response = await model.generateContent(prompt);
const jsonText = response.response.text();
// Parse JSON (handles markdown code blocks)
const cleaned = jsonText.replace(/```(?:json)?\s*([\s\S]*?)\s*```/, '$1');
return JSON.parse(cleaned);
}
Token Optimization
- Group related translations together
- Use numbered lists for clear mapping
- Request JSON output for easy parsing
- Limit batch size to ~50 items per request
Error Handling
try {
const result = await batchTranslate(headlines);
return result;
} catch (error) {
// Fallback: translate individually
return Promise.all(headlines.map(h => translateOne(h)));
}