← Back to Home

How to Batch Translate with Gemini AI

Updated January 14, 2026
geminibatch translationefficiencytoken optimization

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

Error Handling

try {
  const result = await batchTranslate(headlines);
  return result;
} catch (error) {
  // Fallback: translate individually
  return Promise.all(headlines.map(h => translateOne(h)));
}