How to translate text with OpenAI API in Python
Setup
pip install openai OPENAI_API_KEY import os
from openai import OpenAI Examples
Integration steps
- Import OpenAI and os modules.
- Initialize the OpenAI client with the API key from os.environ.
- Construct a chat message with a prompt instructing the model to translate the given text specifying source and target languages.
- Call client.chat.completions.create with the chosen model and messages.
- Extract the translated text from response.choices[0].message.content.
Full code
import os
from openai import OpenAI
def translate_text(text: str, source_lang: str, target_lang: str) -> str:
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = (
f"Translate the following text from {source_lang} to {target_lang}:\n" + text
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content.strip()
if __name__ == "__main__":
source = "English"
target = "Spanish"
text_to_translate = "Hello, how are you?"
translation = translate_text(text_to_translate, source, target)
print(f"Original ({source}): {text_to_translate}")
print(f"Translated ({target}): {translation}") Original (English): Hello, how are you? Translated (Spanish): Hola, ¿cómo estás?
API trace
{"model": "gpt-4o", "messages": [{"role": "user", "content": "Translate the following text from English to Spanish:\nHello, how are you?"}]} {"choices": [{"message": {"content": "Hola, ¿cómo estás?"}}], "usage": {"prompt_tokens": 20, "completion_tokens": 7, "total_tokens": 27}} response.choices[0].message.contentVariants
Streaming translation ›
Use streaming to display translation output token-by-token for better user experience with longer texts.
import os
from openai import OpenAI
def translate_text_stream(text: str, source_lang: str, target_lang: str) -> None:
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = f"Translate the following text from {source_lang} to {target_lang}:\n" + text
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}],
stream=True
)
print(f"Translation ({target_lang}):", end=" ")
for chunk in stream:
delta = chunk.choices[0].delta.content or ""
print(delta, end="", flush=True)
print() # newline
if __name__ == "__main__":
translate_text_stream("Good morning, have a nice day!", "English", "French") Async translation ›
Use async calls when integrating translation in an async application or to handle multiple concurrent translations.
import os
import asyncio
from openai import OpenAI
async def translate_text_async(text: str, source_lang: str, target_lang: str) -> str:
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = f"Translate the following text from {source_lang} to {target_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():
translation = await translate_text_async("Thank you very much", "English", "Japanese")
print(f"Translated (Japanese): {translation}")
if __name__ == "__main__":
asyncio.run(main()) Use smaller model for cost efficiency ›
Use gpt-4o-mini for lower cost and faster responses when translation quality requirements are moderate.
import os
from openai import OpenAI
def translate_text_cost_efficient(text: str, source_lang: str, target_lang: str) -> str:
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = f"Translate the following text from {source_lang} to {target_lang}:\n" + text
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content.strip()
if __name__ == "__main__":
translation = translate_text_cost_efficient("Hello, how are you?", "English", "Spanish")
print(f"Translated (Spanish): {translation}") Performance
- Keep prompts concise to reduce token usage.
- Use smaller models like gpt-4o-mini for cost savings.
- Cache frequent translations to avoid repeated calls.
| Approach | Latency | Cost/call | Best for |
|---|---|---|---|
| Standard call with gpt-4o | ~800ms | ~$0.002 per 500 tokens | High-quality translations |
| Streaming with gpt-4o | ~800ms initial + streaming | ~$0.002 per 500 tokens | Better UX for long texts |
| Async call with gpt-4o | ~800ms | ~$0.002 per 500 tokens | Concurrent translation tasks |
| Cost-efficient with gpt-4o-mini | ~400ms | ~$0.0005 per 500 tokens | Budget-conscious or lower quality needs |
Quick tip
Explicitly instruct the model with source and target languages in the prompt for accurate translations.
Common mistake
Not specifying source and target languages clearly in the prompt, leading to incorrect or incomplete translations.