"""
Pattern 237: Translation Agent
Purpose: Multi-language translation with context preservation, quality checking, and dialect support.
Implements automatic language detection, translation memory, and terminology management.
"""
from typing import Dict, Any, List, Optional, Set
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from collections import defaultdict
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
class TranslationQuality(Enum):
"""Translation quality levels."""
DRAFT = "draft" # Quick, basic translation
STANDARD = "standard" # Good quality
PROFESSIONAL = "professional" # High quality
CERTIFIED = "certified" # Legal/official level
class TranslationStyle(Enum):
"""Translation style preferences."""
FORMAL = "formal"
INFORMAL = "informal"
TECHNICAL = "technical"
CREATIVE = "creative"
LITERAL = "literal"
@dataclass
class TranslationMemoryEntry:
"""Entry in translation memory."""
source_text: str
target_text: str
source_lang: str
target_lang: str
quality: TranslationQuality
created_at: datetime = field(default_factory=datetime.now)
@dataclass
class Translation:
"""A translation result."""
source_text: str
translated_text: str
source_lang: str
target_lang: str
quality: TranslationQuality
style: TranslationStyle
confidence: float = 0.0
detected_lang: Optional[str] = None
alternatives: List[str] = field(default_factory=list)
preserved_terms: Dict[str, str] = field(default_factory=dict)
class TranslationAgent:
"""
Translation Agent - Multi-language translation with quality control.
Features:
- Automatic language detection
- Multi-language support
- Translation memory for consistency
- Terminology management
- Quality levels
- Style preferences
- Context preservation
- Alternative translations
"""
def __init__(self, name: str):
self.name = name
self.llm = ChatOpenAI(model="gpt-4", temperature=0.3)
# Translation resources
self.translation_memory: List[TranslationMemoryEntry] = []
self.terminology: Dict[str, Dict[str, str]] = defaultdict(dict) # term -> {lang: translation}
self.supported_languages: Set[str] = {
"English", "Spanish", "French", "German", "Italian", "Portuguese",
"Chinese", "Japanese", "Korean", "Arabic", "Russian", "Hindi"
}
# Statistics
self.statistics: Dict[str, Any] = {
"total_translations": 0,
"languages_used": defaultdict(int),
"quality_distribution": {q.value: 0 for q in TranslationQuality},
"memory_hits": 0
}
def translate(self,
text: str,
target_lang: str,
source_lang: Optional[str] = None,
quality: TranslationQuality = TranslationQuality.STANDARD,
style: TranslationStyle = TranslationStyle.FORMAL) -> Translation:
"""Translate text to target language."""
# Detect source language if not provided
if source_lang is None:
source_lang = self._detect_language(text)
# Check translation memory
memory_match = self._check_translation_memory(text, source_lang, target_lang)
if memory_match:
self.statistics["memory_hits"] += 1
return memory_match
# Apply terminology
terms_to_preserve = self._extract_terms(text, source_lang, target_lang)
# Perform translation
translated_text = self._perform_translation(
text, source_lang, target_lang, quality, style, terms_to_preserve
)
# Generate alternatives
alternatives = self._generate_alternatives(text, source_lang, target_lang, 2)
# Calculate confidence
confidence = self._calculate_confidence(text, translated_text, quality)
# Create translation object
translation = Translation(
source_text=text,
translated_text=translated_text,
source_lang=source_lang,
target_lang=target_lang,
quality=quality,
style=style,
confidence=confidence,
detected_lang=source_lang,
alternatives=alternatives,
preserved_terms=terms_to_preserve
)
# Add to translation memory
self._add_to_memory(translation)
# Update statistics
self.statistics["total_translations"] += 1
self.statistics["languages_used"][f"{source_lang}->{target_lang}"] += 1
self.statistics["quality_distribution"][quality.value] += 1
return translation
def _detect_language(self, text: str) -> str:
"""Detect source language of text."""
prompt = ChatPromptTemplate.from_messages([
("system", "Detect the language of the given text. "
"Return only the language name (e.g., 'English', 'Spanish', 'French')."),
("human", f"Text: {text[:200]}\n\nLanguage:")
])
chain = prompt | self.llm
response = chain.invoke({})
detected = str(response.content).strip()
return detected if detected in self.supported_languages else "English"
def _perform_translation(self,
text: str,
source_lang: str,
target_lang: str,
quality: TranslationQuality,
style: TranslationStyle,
preserve_terms: Dict[str, str]) -> str:
"""Perform the actual translation."""
quality_instructions = {
TranslationQuality.DRAFT: "Provide a quick, basic translation focusing on meaning.",
TranslationQuality.STANDARD: "Provide an accurate translation with natural flow.",
TranslationQuality.PROFESSIONAL: "Provide a high-quality, polished translation with attention to nuance.",
TranslationQuality.CERTIFIED: "Provide a precise, formal translation suitable for official documents."
}
style_instructions = {
TranslationStyle.FORMAL: "Use formal language and professional tone.",
TranslationStyle.INFORMAL: "Use casual, conversational language.",
TranslationStyle.TECHNICAL: "Maintain technical terminology and precision.",
TranslationStyle.CREATIVE: "Adapt idioms and expressions creatively.",
TranslationStyle.LITERAL: "Translate as literally as possible while maintaining sense."
}
terms_note = ""
if preserve_terms:
terms_list = ", ".join([f"'{k}' as '{v}'" for k, v in preserve_terms.items()])
terms_note = f"\n\nPreserve these terms: {terms_list}"
prompt = ChatPromptTemplate.from_messages([
("system", f"You are an expert translator from {source_lang} to {target_lang}. "
f"{quality_instructions.get(quality, '')} "
f"{style_instructions.get(style, '')} "
f"Maintain the original meaning, tone, and context.{terms_note}"),
("human", f"Translate to {target_lang}:\n\n{text}")
])
chain = prompt | self.llm
response = chain.invoke({})
return str(response.content).strip()
def _generate_alternatives(self,
text: str,
source_lang: str,
target_lang: str,
count: int) -> List[str]:
"""Generate alternative translations."""
prompt = ChatPromptTemplate.from_messages([
("system", f"Provide {count} alternative translations from {source_lang} to {target_lang}. "
f"Each alternative should capture different nuances or phrasings. "
f"Return only the translations, one per line."),
("human", f"Text: {text}")
])
chain = prompt | self.llm
response = chain.invoke({})
alternatives = [line.strip() for line in str(response.content).split('\n') if line.strip()]
return alternatives[:count]
def _extract_terms(self, text: str, source_lang: str, target_lang: str) -> Dict[str, str]:
"""Extract and translate terminology."""
preserved = {}
# Check terminology database
for term, translations in self.terminology.items():
if term.lower() in text.lower() and target_lang in translations:
preserved[term] = translations[target_lang]
return preserved
def _check_translation_memory(self,
text: str,
source_lang: str,
target_lang: str) -> Optional[Translation]:
"""Check if translation exists in memory."""
for entry in self.translation_memory:
if (entry.source_text == text and
entry.source_lang == source_lang and
entry.target_lang == target_lang):
return Translation(
source_text=entry.source_text,
translated_text=entry.target_text,
source_lang=entry.source_lang,
target_lang=entry.target_lang,
quality=entry.quality,
style=TranslationStyle.FORMAL,
confidence=1.0,
detected_lang=source_lang
)
return None
def _add_to_memory(self, translation: Translation):
"""Add translation to memory."""
entry = TranslationMemoryEntry(
source_text=translation.source_text,
target_text=translation.translated_text,
source_lang=translation.source_lang,
target_lang=translation.target_lang,
quality=translation.quality
)
self.translation_memory.append(entry)
# Limit memory size
if len(self.translation_memory) > 1000:
self.translation_memory = self.translation_memory[-1000:]
def _calculate_confidence(self, source: str, translation: str, quality: TranslationQuality) -> float:
"""Calculate translation confidence score."""
# Simple heuristic (in production, use back-translation or BLEU score)
base_confidence = {
TranslationQuality.DRAFT: 0.6,
TranslationQuality.STANDARD: 0.8,
TranslationQuality.PROFESSIONAL: 0.9,
TranslationQuality.CERTIFIED: 0.95
}
confidence = base_confidence.get(quality, 0.8)
# Adjust based on length similarity
len_ratio = len(translation) / len(source) if len(source) > 0 else 1.0
if 0.5 <= len_ratio List[Translation]:
"""Translate multiple texts."""
return [self.translate(text, target_lang, source_lang) for text in texts]
def get_statistics(self) -> Dict[str, Any]:
"""Get translation statistics."""
return {
"name": self.name,
"supported_languages": len(self.supported_languages),
"memory_size": len(self.translation_memory),
"terminology_entries": len(self.terminology),
**self.statistics
}
class TranslationPattern:
"""
Translation Pattern - Manage translation agents.
Coordinates multiple translation agents for different purposes.
"""
def __init__(self):
self.agents: Dict[str, TranslationAgent] = {}
def create_agent(self, name: str) -> TranslationAgent:
"""Create a new translation agent."""
agent = TranslationAgent(name)
self.agents[name] = agent
print(f" Created translation agent: {name}")
return agent
def run(self,
agent_name: str,
text: str,
target_lang: str,
source_lang: Optional[str] = None,
quality: TranslationQuality = TranslationQuality.STANDARD) -> Dict[str, Any]:
"""Perform translation using specified agent."""
if agent_name not in self.agents:
return {"error": f"Agent {agent_name} not found"}
agent = self.agents[agent_name]
translation = agent.translate(text, target_lang, source_lang, quality)
print(f"\n=== Translation by {agent_name} ===")
print(f"Source ({translation.source_lang}): {translation.source_text[:100]}...")
print(f"Target ({translation.target_lang}): {translation.translated_text}")
print(f"Quality: {translation.quality.value} | Confidence: {translation.confidence:.1%}")
if translation.alternatives:
print("\nAlternatives:")
for i, alt in enumerate(translation.alternatives, 1):
print(f" {i}. {alt}")
if translation.preserved_terms:
print(f"\nPreserved Terms: {', '.join(translation.preserved_terms.keys())}")
return {
"agent": agent_name,
"source_lang": translation.source_lang,
"target_lang": translation.target_lang,
"confidence": translation.confidence,
"statistics": agent.get_statistics()
}
# Example usage
if __name__ == "__main__":
print("=== Translation Agent Pattern Demo ===\n")
# Create pattern
pattern = TranslationPattern()
# Create agents
print("1. Setting up translation agents...")
universal_translator = pattern.create_agent("UniversalTranslator")
technical_translator = pattern.create_agent("TechnicalTranslator")
# Add terminology
print("\n2. Adding terminology...")
universal_translator.add_terminology("machine learning", {
"Spanish": "aprendizaje automático",
"French": "apprentissage automatique",
"German": "maschinelles Lernen"
})
# Perform translations
print("\n3. Performing translations...")
text1 = "Artificial intelligence is transforming the way we live and work."
result1 = pattern.run("UniversalTranslator", text1, "Spanish", quality=TranslationQuality.PROFESSIONAL)
print("\n" + "="*60 + "\n")
text2 = "Machine learning algorithms analyze data to make predictions."
result2 = pattern.run("UniversalTranslator", text2, "French", source_lang="English")
print("\n" + "="*60 + "\n")
text3 = "The quick brown fox jumps over the lazy dog."
result3 = pattern.run("UniversalTranslator", text3, "German", quality=TranslationQuality.STANDARD)
# Print statistics
print("\n" + "="*60)
print("\n4. Translation Statistics:")
stats = result3["statistics"]
for key, value in stats.items():
print(f" {key}: {value}")
print("\n✓ Multi-language translation with quality control complete!")
Agentic Architecture Pattern: Translation Agent
Pattern 237: 237 Translation Agent – Line-by-Line Explanation
Overview
Pattern 237: Translation Agent
Purpose: Multi-language translation with context preservation, quality checking, and dialect support. Implements automatic language detection, translation memory, and terminology management.
Code Structure Analysis
File Information
- Pattern Number: 237
- Pattern Name: 237 Translation Agent
- File Path:
patterns\domain_specific\237_translation_agent.py - Total Lines: 412
Detailed Code Explanation
Module Docstring
"""
Pattern 237: Translation Agent
Purpose: Multi-language translation with context preservation, quality checking, and dialect support.
Implements automatic language detection, translation memory, and terminology management.
"""
Explanation: This module docstring describes the purpose and key features of the 237 Translation Agent pattern.
Imports Section
from typing import Dict, Any, List, Optional, Set
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from collections import defaultdict
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI # First 20 imports shown
Explanation: The module imports necessary dependencies:
– from typing import Dict, Any, List, Optional, Set: Type hints for better code documentation
– from dataclasses import dataclass, field: Data class decorators for clean data structures
– from datetime import datetime: Date and time utilities
– from enum import Enum: Enumeration support for fixed sets of values
– from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration
– from langchain_openai import ChatOpenAI: LangChain framework integration
Enumerations
TranslationQuality (Line 17)
class TranslationQuality(Enum):
DRAFT
STANDARD
PROFESSIONAL
CERTIFIED
Purpose: Translation quality levels.
Values:
– DRAFT: Represents draft
– STANDARD: Represents standard
– PROFESSIONAL: Represents professional
– CERTIFIED: Represents certified
TranslationStyle (Line 25)
class TranslationStyle(Enum):
FORMAL
INFORMAL
TECHNICAL
CREATIVE
LITERAL
Purpose: Translation style preferences.
Values:
– FORMAL: Represents formal
– INFORMAL: Represents informal
– TECHNICAL: Represents technical
– CREATIVE: Represents creative
– LITERAL: Represents literal
Classes
TranslationQuality (Line 17)
Description: Translation quality levels.
TranslationStyle (Line 25)
Description: Translation style preferences.
TranslationMemoryEntry (Line 35)
Description: Entry in translation memory.
Translation (Line 46)
Description: A translation result.
TranslationAgent (Line 60)
Description: Translation Agent – Multi-language translation with quality control.
Features: – Automatic language detection – Multi-language support – Translation memory for consistency – Terminology management – Quality levels – Style preferences – Context preservation – Alternative translations
Methods:
__init__ (Line 75)
def __init__(self, name):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
– name: Identifier or label
translate (Line 95)
def translate(self, text, target_lang, source_lang, quality, style):
"""Translate text to target language."""
Purpose: Translate text to target language.
Parameters:
– self: Instance reference
– text: Parameter for text
– target_lang: Parameter for target_lang
– source_lang: Parameter for source_lang
– quality: Parameter for quality
– style: Parameter for style
_detect_language (Line 151)
def _detect_language(self, text):
"""Detect source language of text."""
Purpose: Detect source language of text.
Parameters:
– self: Instance reference
– text: Parameter for text
_perform_translation (Line 165)
def _perform_translation(self, text, source_lang, target_lang, quality, style, preserve_terms):
"""Perform the actual translation."""
Purpose: Perform the actual translation.
Parameters:
– self: Instance reference
– text: Parameter for text
– source_lang: Parameter for source_lang
– target_lang: Parameter for target_lang
– quality: Parameter for quality
– style: Parameter for style
– preserve_terms: Parameter for preserve_terms
_generate_alternatives (Line 207)
def _generate_alternatives(self, text, source_lang, target_lang, count):
"""Generate alternative translations."""
Purpose: Generate alternative translations.
Parameters:
– self: Instance reference
– text: Parameter for text
– source_lang: Parameter for source_lang
– target_lang: Parameter for target_lang
– count: Parameter for count
_extract_terms (Line 226)
def _extract_terms(self, text, source_lang, target_lang):
"""Extract and translate terminology."""
Purpose: Extract and translate terminology.
Parameters:
– self: Instance reference
– text: Parameter for text
– source_lang: Parameter for source_lang
– target_lang: Parameter for target_lang
_check_translation_memory (Line 237)
def _check_translation_memory(self, text, source_lang, target_lang):
"""Check if translation exists in memory."""
Purpose: Check if translation exists in memory.
Parameters:
– self: Instance reference
– text: Parameter for text
– source_lang: Parameter for source_lang
– target_lang: Parameter for target_lang
_add_to_memory (Line 260)
def _add_to_memory(self, translation):
"""Add translation to memory."""
Purpose: Add translation to memory.
Parameters:
– self: Instance reference
– translation: Parameter for translation
_calculate_confidence (Line 276)
def _calculate_confidence(self, source, translation, quality):
"""Calculate translation confidence score."""
Purpose: Calculate translation confidence score.
Parameters:
– self: Instance reference
– source: Parameter for source
– translation: Parameter for translation
– quality: Parameter for quality
add_terminology (Line 295)
def add_terminology(self, term, translations):
"""Add term to terminology database."""
Purpose: Add term to terminology database.
Parameters:
– self: Instance reference
– term: Parameter for term
– translations: Parameter for translations
batch_translate (Line 299)
def batch_translate(self, texts, target_lang, source_lang):
"""Translate multiple texts."""
Purpose: Translate multiple texts.
Parameters:
– self: Instance reference
– texts: Parameter for texts
– target_lang: Parameter for target_lang
– source_lang: Parameter for source_lang
get_statistics (Line 303)
def get_statistics(self):
"""Get translation statistics."""
Purpose: Get translation statistics.
Parameters:
– self: Instance reference
TranslationPattern (Line 314)
Description: Translation Pattern – Manage translation agents.
Coordinates multiple translation agents for different purposes.
Methods:
__init__ (Line 321)
def __init__(self):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
create_agent (Line 324)
def create_agent(self, name):
"""Create a new translation agent."""
Purpose: Create a new translation agent.
Parameters:
– self: Instance reference
– name: Identifier or label
run (Line 331)
def run(self, agent_name, text, target_lang, source_lang, quality):
"""Perform translation using specified agent."""
Purpose: Perform translation using specified agent.
Parameters:
– self: Instance reference
– agent_name: Parameter for agent_name
– text: Parameter for text
– target_lang: Parameter for target_lang
– source_lang: Parameter for source_lang
– quality: Parameter for quality
Design Patterns Used
- Strategy Pattern: Different execution strategies for various scenarios
- State Pattern: Managing different states in the workflow
- Chain of Responsibility: Sequential processing through workflow nodes
- Observer Pattern: Tracking and monitoring pattern execution
- Factory Pattern: Creating instances with proper configuration
Usage Example
# Initialize the pattern
pattern = TranslationQuality(name="example", model_name="gpt-4")
# Configure and execute
result = pattern.execute(data={"key": "value"})
# Check results
print(result)
Key Concepts
- LLM Integration: Uses LangChain/OpenAI for intelligent decision-making
- Workflow Orchestration: LangGraph manages execution flow through nodes
- State Management: TypedDict defines workflow state structure
- Error Handling: Comprehensive error handling and fallback mechanisms
- Extensibility: Designed for easy customization and extension
Extension Points
This pattern can be extended by: 1. Adding custom workflow nodes 2. Implementing additional validation logic 3. Integrating with external services 4. Customizing LLM prompts and responses 5. Adding monitoring and logging capabilities