pythonintermediate
Real-Time Translation Pipeline with OpenAI
Build a language detection and translation pipeline using GPT for multi-language support.
pythonPress โ/Ctrl + Shift + C to copy
from openai import OpenAI
from typing import Optional
client = OpenAI()
def detect_and_translate(text: str, target_lang: str = 'English') -> dict:
detect_resp = client.chat.completions.create(
model='gpt-4o-mini',
response_format={'type': 'json_object'},
messages=[{
'role': 'user',
'content': f'Detect the language of this text and return JSON {{"language": "..."}}: {text!r}'
}],
)
import json
source_lang = json.loads(detect_resp.choices[0].message.content)['language']
if source_lang.lower() == target_lang.lower():
return {'source': source_lang, 'target': target_lang, 'translation': text, 'same_language': True}
trans_resp = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role':'system','content':f'Translate to {target_lang}. Return only the translation.'},{'role':'user','content':text}],
)
return {'source': source_lang, 'target': target_lang, 'translation': trans_resp.choices[0].message.content}
for sample in ['Bonjour le monde!', 'ๆฅๆฌ่ชใฎใในใ', 'Hello World']:
result = detect_and_translate(sample)
print(f'{sample!r} ({result["source"]}) -> {result["translation"]}')Use Cases
- multilingual apps
- auto-translation
- language detection
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
#openai#streaming
typescriptbeginner
Generate Text Embeddings with OpenAI
Create vector embeddings for semantic search and similarity matching using text-embedding-3-small.
Best for: semantic search
#openai#embeddings
typescriptadvanced
RAG Pipeline (Retrieve + Augment + Generate)
Minimal RAG implementation: embed a query, retrieve top-k chunks, inject into prompt.
Best for: document Q&A
#rag#embeddings
typescriptintermediate
OpenAI Tool Calling (Function Calling)
Define tools for GPT to call, parse the response, execute the function, and return results.
Best for: AI agents
#openai#tool-calling