or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdexternal-apis.mdindex.mdpackage-management.mdtext-processing.mdtranslation.md
tile.json

external-apis.mddocs/

External APIs

Integration with external translation services and language models, providing alternative translation backends when offline neural models are insufficient or unavailable. Supports LibreTranslate API services and OpenAI language models.

Capabilities

LibreTranslate API Integration

Client library for integrating with LibreTranslate translation services, enabling remote translation capabilities with API key authentication.

class LibreTranslateAPI:
    DEFAULT_URL = "https://translate.argosopentech.com/"
    
    def __init__(self, url: str = None, api_key: str = None):
        """
        Initialize LibreTranslate API client.
        
        Args:
            url (str, optional): LibreTranslate API endpoint URL
            api_key (str, optional): API key for authenticated requests
        """
    
    def translate(self, q: str, source: str = "en", target: str = "es") -> str:
        """
        Translate text using LibreTranslate API.
        
        Args:
            q (str): Text to translate
            source (str): Source language code (default: "en")
            target (str): Target language code (default: "es")
            
        Returns:
            str: Translated text
            
        Raises:
            Exception: If API request fails or authentication fails
        """
    
    def languages(self):
        """
        Get list of supported languages from LibreTranslate API.
        
        Returns:
            Language list from API response
        """
    
    def detect(self, q: str):
        """
        Detect language of input text using LibreTranslate API.
        
        Args:
            q (str): Text to analyze
            
        Returns:
            Language detection result from API
        """

OpenAI API Integration

Integration with OpenAI language models for advanced translation capabilities using large language models.

class OpenAIAPI:
    def __init__(self, api_key: str):
        """
        Initialize OpenAI API client.
        
        Args:
            api_key (str): OpenAI API key for authentication
        """
    
    def infer(self, prompt: str) -> str | None:
        """
        Run inference on language model with given prompt.
        
        Args:
            prompt (str): Prompt text for language model
            
        Returns:
            str | None: Model response or None if request fails
            
        Raises:
            Exception: If API request fails or authentication fails
        """

Language Model Interface

Abstract interface for language model implementations, enabling extensible integration with various AI services.

class ILanguageModel:
    """Abstract interface for language model implementations."""
    
    def infer(self, x: str) -> str | None:
        """
        Run language model inference on input text.
        
        Args:
            x (str): Input text for inference
            
        Returns:
            str | None: Model output or None if inference fails
        """

Remote Translation Implementation

Translation implementation that uses external API services for translation requests.

class RemoteTranslation(ITranslation):
    def __init__(self, from_lang: Language, to_lang: Language, api):
        """
        Initialize remote API translation.
        
        Args:
            from_lang (Language): Source language
            to_lang (Language): Target language
            api: API client (LibreTranslateAPI or compatible)
        """
    
    def hypotheses(self, input_text: str, num_hypotheses: int = 1) -> list[Hypothesis]:
        """
        Perform translation via remote API service.
        
        Args:
            input_text (str): Text to translate
            num_hypotheses (int): Number of hypotheses (usually 1 for APIs)
            
        Returns:
            list[Hypothesis]: Translation results with confidence scores
        """

Few-Shot Translation Implementation

Translation using large language models with few-shot prompting techniques for high-quality results.

class FewShotTranslation(ITranslation):
    def __init__(self, from_lang: Language, to_lang: Language, language_model: ILanguageModel):
        """
        Initialize few-shot language model translation.
        
        Args:
            from_lang (Language): Source language
            to_lang (Language): Target language
            language_model (ILanguageModel): Language model for translation
        """
    
    def hypotheses(self, input_text: str, num_hypotheses: int = 1) -> list[Hypothesis]:
        """
        Perform translation using language model with few-shot prompting.
        
        Args:
            input_text (str): Text to translate
            num_hypotheses (int): Number of hypotheses to generate
            
        Returns:
            list[Hypothesis]: Translation results from language model
        """

Few-Shot Prompt Generation

Utility functions for generating and parsing few-shot translation prompts for language models.

def generate_prompt(text: str, from_name: str, from_code: str, to_name: str, to_code: str) -> str:
    """
    Generate few-shot translation prompt for language model.
    
    Args:
        text (str): Text to translate
        from_name (str): Source language name (e.g., "English")
        from_code (str): Source language code (e.g., "en")
        to_name (str): Target language name (e.g., "Spanish")
        to_code (str): Target language code (e.g., "es")
        
    Returns:
        str: Formatted prompt for language model
    """

def parse_inference(output: str) -> str:
    """
    Parse language model inference output to extract translation.
    
    Args:
        output (str): Raw output from language model
        
    Returns:
        str: Extracted translation text
    """

Usage Examples

LibreTranslate API Usage

from argostranslate.apis import LibreTranslateAPI

# Initialize API client with default endpoint
api = LibreTranslateAPI()

# Translate text
result = api.translate("Hello world", source="en", target="es")
print(result)  # "Hola mundo"

# Use custom endpoint and API key
custom_api = LibreTranslateAPI(
    url="https://my-libretranslate.example.com/",
    api_key="your-api-key-here"
)

translation = custom_api.translate("Good morning", "en", "fr")
print(translation)  # "Bonjour"

# Get supported languages
languages = api.languages()
for lang in languages:
    print(f"{lang['code']}: {lang['name']}")

# Detect language
detection = api.detect("Bonjour le monde")
print(f"Detected language: {detection}")

OpenAI API Integration

from argostranslate.apis import OpenAIAPI
from argostranslate.fewshot import generate_prompt, parse_inference

# Initialize OpenAI client
openai_api = OpenAIAPI(api_key="your-openai-api-key")

# Generate translation prompt
prompt = generate_prompt(
    text="The weather is beautiful today",
    from_name="English",
    from_code="en", 
    to_name="Japanese",
    to_code="ja"
)

# Get translation from language model
response = openai_api.infer(prompt)
if response:
    translation = parse_inference(response)
    print(f"Translation: {translation}")

Remote Translation with Translation Interface

from argostranslate import translate
from argostranslate.apis import LibreTranslateAPI
from argostranslate.translate import RemoteTranslation

# Set up LibreTranslate API
api = LibreTranslateAPI(api_key="your-api-key")

# Get language objects
en_lang = translate.get_language_from_code("en")
es_lang = translate.get_language_from_code("es")

if en_lang and es_lang:
    # Create remote translation
    remote_translation = RemoteTranslation(en_lang, es_lang, api)
    
    # Use translation interface
    result = remote_translation.translate("How are you today?")
    print(result)
    
    # Get hypotheses (typically just one for APIs)
    hypotheses = remote_translation.hypotheses("How are you today?")
    for hyp in hypotheses:
        print(f"Translation: {hyp.value} (score: {hyp.score})")

Few-Shot Translation with Language Models

from argostranslate import translate
from argostranslate.apis import OpenAIAPI
from argostranslate.translate import FewShotTranslation

# Set up OpenAI API
openai_api = OpenAIAPI(api_key="your-openai-api-key")

# Get language objects
en_lang = translate.get_language_from_code("en")
zh_lang = translate.get_language_from_code("zh")

if en_lang and zh_lang:
    # Create few-shot translation
    fewshot_translation = FewShotTranslation(en_lang, zh_lang, openai_api)
    
    # Perform translation
    result = fewshot_translation.translate("I love learning new languages")
    print(f"Few-shot translation: {result}")

Combining Local and Remote Translation

from argostranslate import translate, package
from argostranslate.apis import LibreTranslateAPI
from argostranslate.translate import RemoteTranslation, CachedTranslation

# Set up remote API as fallback
api = LibreTranslateAPI(api_key="your-api-key")

def get_best_translation(from_code: str, to_code: str):
    """Get best available translation (local preferred, remote fallback)."""
    
    # Try to get local translation first
    local_translation = translate.get_translation_from_codes(from_code, to_code)
    if local_translation:
        return CachedTranslation(local_translation)
    
    # Fall back to remote API
    from_lang = translate.get_language_from_code(from_code)
    to_lang = translate.get_language_from_code(to_code)
    
    if from_lang and to_lang:
        remote_translation = RemoteTranslation(from_lang, to_lang, api)
        return CachedTranslation(remote_translation)
    
    return None

# Use hybrid translation
translation = get_best_translation("en", "ko")
if translation:
    result = translation.translate("Machine learning is fascinating")
    print(result)

Error Handling and Fallbacks

from argostranslate.apis import LibreTranslateAPI, OpenAIAPI
import argostranslate.settings as settings

def robust_translate(text: str, from_code: str, to_code: str) -> str:
    """Translate with multiple fallback options."""
    
    # Try local translation first
    try:
        return translate.translate(text, from_code, to_code)
    except Exception as e:
        print(f"Local translation failed: {e}")
    
    # Try LibreTranslate API
    if settings.libretranslate_api_key:
        try:
            api = LibreTranslateAPI(api_key=settings.libretranslate_api_key)
            return api.translate(text, from_code, to_code)
        except Exception as e:
            print(f"LibreTranslate API failed: {e}")
    
    # Try OpenAI as last resort
    if settings.openai_api_key:
        try:
            openai_api = OpenAIAPI(api_key=settings.openai_api_key)
            prompt = generate_prompt(text, from_code, from_code, to_code, to_code)
            response = openai_api.infer(prompt)
            if response:
                return parse_inference(response)
        except Exception as e:
            print(f"OpenAI API failed: {e}")
    
    # Return original text if all methods fail
    return text

# Use robust translation
result = robust_translate("Hello world", "en", "ja")
print(result)

Configuration

External API integration is configured through the settings module:

import argostranslate.settings as settings

# LibreTranslate API configuration
settings.libretranslate_api_key = "your-libretranslate-key"

# OpenAI API configuration  
settings.openai_api_key = "your-openai-key"

# Model provider selection
from argostranslate.settings import ModelProvider
settings.model_provider = ModelProvider.LIBRETRANSLATE  # or OPENAI

API Key Management

For security, API keys should be managed through environment variables:

# Set environment variables
export LIBRETRANSLATE_API_KEY="your-libretranslate-key"
export OPENAI_API_KEY="your-openai-key"

The library will automatically load these keys from the environment when available.

Backward Compatibility

# Legacy alias maintained for backward compatibility
LibreTranslateTranslation = RemoteTranslation