How to build real-time translation app
Quick answer
Use the
OpenAI Python SDK to send user input to a chat model like gpt-4o with a prompt instructing it to translate text in real time. Stream the response for immediate partial translations and update the UI accordingly.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official openai Python SDK and set your API key as an environment variable.
- Run
pip install openaito install the SDK. - Set your API key in your shell:
export OPENAI_API_KEY='your_api_key'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key"(Windows).
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 shows a simple synchronous Python script that sends text to gpt-4o with a system prompt to translate from English to Spanish. It streams the response tokens for real-time output.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
messages = [
{"role": "system", "content": "You are a helpful translator that translates English to Spanish in real time."},
{"role": "user", "content": "Translate this sentence: Hello, how are you today?"}
]
stream = client.chat.completions.create(
model="gpt-4o",
messages=messages,
stream=True
)
print("Translation:", end=" ")
for chunk in stream:
delta = chunk.choices[0].delta.content or ""
print(delta, end="", flush=True)
print() output
Translation: Hola, ¿cómo estás hoy?
Common variations
You can adapt this example to:
- Use asynchronous calls with
asyncandawaitfor better concurrency. - Change the target language by modifying the system prompt.
- Use other models like
gpt-4o-minifor lower latency or cost. - Integrate with a GUI or web framework to display translations live.
import os
import asyncio
from openai import OpenAI
async def translate_text(text: str, target_language: str = "Spanish"):
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
messages = [
{"role": "system", "content": f"You are a helpful translator that translates English to {target_language} in real time."},
{"role": "user", "content": f"Translate this sentence: {text}"}
]
stream = await client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
stream=True
)
print(f"Translation to {target_language}:", end=" ")
async for chunk in stream:
delta = chunk.choices[0].delta.content or ""
print(delta, end="", flush=True)
print()
if __name__ == "__main__":
asyncio.run(translate_text("Good morning, have a nice day!", "French")) output
Translation to French: Bonjour, passez une bonne journée!
Troubleshooting
- If you get authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - If streaming does not work, ensure your network allows HTTP/2 connections and you are using the latest
openaiSDK. - For slow responses, try smaller models like
gpt-4o-minior reducemax_tokens.
Key Takeaways
- Use the OpenAI Python SDK with
gpt-4oorgpt-4o-minifor real-time translation. - Stream responses to display partial translations immediately for a live user experience.
- Customize the system prompt to target any language or translation style.
- Async calls improve concurrency and responsiveness in real-time apps.
- Always secure your API key via environment variables to avoid leaks.