How to beginner · 3 min read

How to translate multiple languages in batch

Quick answer
Use the OpenAI Python SDK to send batch translation requests by iterating over multiple texts and target languages. Create a prompt for each input specifying the source and target languages, then call client.chat.completions.create with model="gpt-4o" to get translations efficiently.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the official openai Python package and set your API key as an environment variable.

  • Install the SDK: pip install openai
  • Set your API key in your shell environment: export OPENAI_API_KEY='your_api_key' (Linux/macOS) or setx OPENAI_API_KEY "your_api_key" (Windows)
bash
pip install openai
output
Collecting openai
  Downloading openai-1.x.x-py3-none-any.whl (xx kB)
Installing collected packages: openai
Successfully installed openai-1.x.x

Step by step

This example translates a batch of English sentences into multiple target languages using gpt-4o. It loops over inputs and languages, sends prompts to the API, and collects translations.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

texts = [
    "Hello, how are you?",
    "What is the weather like today?",
    "Thank you for your help."
]

target_languages = ["Spanish", "French", "German"]

translations = {}

for text in texts:
    translations[text] = {}
    for lang in target_languages:
        prompt = (
            f"Translate the following English text to {lang}:\n" +
            f"{text}"
        )
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": prompt}]
        )
        translated_text = response.choices[0].message.content.strip()
        translations[text][lang] = translated_text

for original, langs in translations.items():
    print(f"Original: {original}")
    for lang, translation in langs.items():
        print(f"  {lang}: {translation}")
    print()
output
Original: Hello, how are you?
  Spanish: Hola, ¿cómo estás?
  French: Bonjour, comment ça va ?
  German: Hallo, wie geht es dir?

Original: What is the weather like today?
  Spanish: ¿Cómo está el clima hoy?
  French: Quel temps fait-il aujourd'hui ?
  German: Wie ist das Wetter heute?

Original: Thank you for your help.
  Spanish: Gracias por tu ayuda.
  French: Merci pour votre aide.
  German: Merci pour votre aide.

Common variations

You can batch translate asynchronously using async Python with the OpenAI SDK, or use streaming for large texts. You can also switch models like gpt-4o-mini for cost savings or claude-3-5-sonnet-20241022 for Anthropic's Claude.

python
import asyncio
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

texts = ["Hello, how are you?", "What is the weather like today?"]
target_languages = ["Spanish", "French"]

async def translate(text, lang):
    prompt = f"Translate the following English text to {lang}:\n{text}"
    response = await client.chat.completions.acreate(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content.strip()

async def main():
    translations = {}
    for text in texts:
        translations[text] = {}
        tasks = [translate(text, lang) for lang in target_languages]
        results = await asyncio.gather(*tasks)
        for lang, translation in zip(target_languages, results):
            translations[text][lang] = translation
    for original, langs in translations.items():
        print(f"Original: {original}")
        for lang, translation in langs.items():
            print(f"  {lang}: {translation}")
        print()

asyncio.run(main())
output
Original: Hello, how are you?
  Spanish: Hola, ¿cómo estás?
  French: Bonjour, comment ça va ?

Original: What is the weather like today?
  Spanish: ¿Cómo está el clima hoy?
  French: Quel temps fait-il aujourd'hui ?

Troubleshooting

  • If you get 401 Unauthorized, verify your OPENAI_API_KEY environment variable is set correctly.
  • If translations are incomplete, increase max_tokens in the request.
  • For rate limits, add delays or batch fewer requests per second.

Key Takeaways

  • Use the OpenAI Python SDK with client.chat.completions.create to translate texts in batch by looping over inputs and target languages.
  • Async calls with acreate enable concurrent batch translation for faster throughput.
  • Adjust max_tokens and model choice to balance cost and translation quality.
  • Always set your API key securely via environment variables to avoid authentication errors.
Verified 2026-04 · gpt-4o, gpt-4o-mini, claude-3-5-sonnet-20241022
Verify ↗