🎯 Mục tiêu bài học
LLMs xuất sắc trong translation và multilingual tasks. Bài này cover các kỹ thuật từ basic translation đến complex localization pipelines.
Sau bài này, bạn sẽ:
✅ Build translation pipelines với context-awareness ✅ Implement language detection và auto-translate ✅ Tạo localization pipeline cho các thị trường khác nhau ✅ Đánh giá chất lượng bản dịch với accuracy, fluency, terminology
🔍 Translation Architecture
Checkpoint
Bạn đã hiểu kiến trúc tổng quát của translation pipeline chưa?
💻 Basic Translation
1from langchain_openai import ChatOpenAI2from langchain_core.prompts import ChatPromptTemplate3from langchain_core.output_parsers import StrOutputParser45llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.3)67translate_chain = (8 ChatPromptTemplate.from_messages([9 ("system", """Ban la dich gia chuyen nghiep.10 Dich tu {source_lang} sang {target_lang}.11 Giu nguyen y nghia, tone, va format.12 Khong giai thich, chi tra ve ban dich."""),13 ("human", "{text}")14 ])15 | llm16 | StrOutputParser()17)1819result = translate_chain.invoke({20 "source_lang": "Vietnamese",21 "target_lang": "English",22 "text": "Hoc AI khong kho neu ban co lo trinh phu hop va kien tri."23})24print(result)Checkpoint
Bạn đã thử implement basic translation với LangChain chưa?
📐 Context-aware Translation
1from pydantic import BaseModel, Field2from typing import List34class TranslationOutput(BaseModel):5 translation: str6 alternatives: List[str] = Field(description="2-3 cach dich khac")7 notes: List[str] = Field(description="Ghi chu ve context, idiomatic expressions")89context_translate = (10 ChatPromptTemplate.from_messages([11 ("system", """Dich voi context awareness.12 Domain: {domain}13 Tone: {tone}14 Cung cap: ban dich chinh, alternatives, va notes."""),15 ("human", "Dich tu {source} sang {target}:\n{text}")16 ])17 | llm.with_structured_output(TranslationOutput)18)1920result = context_translate.invoke({21 "domain": "technology",22 "tone": "professional",23 "source": "Vietnamese",24 "target": "English",25 "text": "Chay mo hinh AI tren may cuc bo giup giam chi phi cloud."26})2728print(f"Translation: {result.translation}")29for alt in result.alternatives:30 print(f" Alt: {alt}")Checkpoint
Bạn đã hiểu cách implement context-aware translation chưa?
⚡ Batch Translation Pipeline
1import asyncio23async def translate_batch(texts, source, target):4 tasks = [{"text": t, "source_lang": source, "target_lang": target} for t in texts]5 results = await translate_chain.abatch(tasks, config={"max_concurrency": 10})6 return results78texts_vi = [9 "Xin chao, toi la AI assistant.",10 "Hom nay thoi tiet dep qua!",11 "Ban da an com chua?",12]1314translated = asyncio.run(translate_batch(texts_vi, "Vietnamese", "English"))15for original, translated_text in zip(texts_vi, translated):16 print(f"VI: {original}")17 print(f"EN: {translated_text}\n")Checkpoint
Bạn đã hiểu cách batch translate nhiều texts cùng lúc chưa?
🛠️ Language Detection
1class LanguageInfo(BaseModel):2 language: str3 confidence: float4 script: str5 is_formal: bool67detect_chain = (8 ChatPromptTemplate.from_messages([9 ("system", "Detect language of the text. Return language name, confidence, script type, formality."),10 ("human", "{text}")11 ])12 | llm.with_structured_output(LanguageInfo)13)1415# Auto-detect and translate16def auto_translate(text, target="English"):17 lang = detect_chain.invoke({"text": text})18 if lang.language.lower() == target.lower():19 return text20 return translate_chain.invoke({21 "text": text,22 "source_lang": lang.language,23 "target_lang": target24 })Checkpoint
Bạn đã hiểu cách implement language detection và auto-translate chưa?
🌐 Localization Pipeline
1class LocalizedContent(BaseModel):2 text: str3 cultural_notes: List[str]4 adapted_references: List[str]56localize_chain = (7 ChatPromptTemplate.from_messages([8 ("system", """Localize content cho thi truong {market}.9 Khong chi dich ma con:10 - Adapt cultural references11 - Adjust tone cho local audience12 - Convert units, formats13 - Note van hoa dac biet"""),14 ("human", "{content}")15 ])16 | llm.with_structured_output(LocalizedContent)17)1819# Localize marketing content20result = localize_chain.invoke({21 "market": "Vietnam",22 "content": "Our Black Friday sale starts at $99! Save big this Thanksgiving weekend."23})Checkpoint
Bạn đã hiểu sự khác biệt giữa localization và translation đơn thuần chưa?
💻 Multi-language Content Generation
1from langchain_core.runnables import RunnableParallel23# Generate content in multiple languages simultaneously4multi_lang = RunnableParallel(5 english=ChatPromptTemplate.from_messages([6 ("system", "Write in English."),7 ("human", "Write product description: {product}")8 ]) | llm | StrOutputParser(),9 10 vietnamese=ChatPromptTemplate.from_messages([11 ("system", "Viet bang tieng Viet."),12 ("human", "Viet mo ta san pham: {product}")13 ]) | llm | StrOutputParser(),14 15 japanese=ChatPromptTemplate.from_messages([16 ("system", "Write in Japanese."),17 ("human", "Write product description: {product}")18 ]) | llm | StrOutputParser()19)2021results = multi_lang.invoke({"product": "AI-powered smart home assistant"})Checkpoint
Bạn đã hiểu cách tạo nội dung đa ngôn ngữ đồng thời với RunnableParallel chưa?
📐 Translation Quality Evaluation
1class QualityScore(BaseModel):2 accuracy: int = Field(ge=1, le=10)3 fluency: int = Field(ge=1, le=10)4 terminology: int = Field(ge=1, le=10)5 overall: int = Field(ge=1, le=10)6 issues: List[str]78quality_chain = (9 ChatPromptTemplate.from_messages([10 ("system", """Danh gia chat luong ban dich.11 So sanh original va translation.12 Score 1-10 cho: accuracy, fluency, terminology, overall."""),13 ("human", "Original: {original}\nTranslation: {translation}")14 ])15 | llm.with_structured_output(QualityScore)16)Checkpoint
Bạn đã hiểu cách đánh giá chất lượng bản dịch chưa?
🎯 Tổng kết
- Build auto-detect + translate pipeline
- Tạo batch translator cho list of texts
- Implement localization cho Vietnam market
- Build translation quality checker
Challenge: Translate technical documentation giữ nguyên code blocks
Câu hỏi tự kiểm tra
- LLMs có những ưu điểm gì so với translation APIs truyền thống khi dịch văn bản?
- Localization khác gì so với translation đơn thuần?
- Làm thế nào để đánh giá chất lượng bản dịch với các tiêu chí accuracy, fluency và terminology?
- RunnableParallel được ứng dụng như thế nào để tạo nội dung đa ngôn ngữ đồng thời?
🎉 Tuyệt vời! Bạn đã hoàn thành bài học Translation và Multilingual Processing!
Tiếp theo: Hãy học cách phân loại văn bản tự động với Text Classification!
