MistralTranslator
Ruby gem for AI-powered translation and text summarization using Mistral AI API, with advanced Rails support.
Quick Start
# Installation
gem 'mistral_translator'
# Configuration
MistralTranslator.configure do |config|
config.api_key = ENV['MISTRAL_API_KEY']
end
# Basic usage
MistralTranslator.translate("Bonjour le monde", from: "fr", to: "en")
# => "Hello world"Key Features
- Smart translation with context and custom glossaries
- Native Rails integration (Mobility, Globalize, I18n attributes)
- Batch processing for high-volume translations
- Multi-level summarization with translation
- Robust error handling with automatic retries; unusable responses raise instead of being returned
- Complete monitoring with metrics and callbacks
- Thread-safe & concurrent with connection pooling (docs)
- Built-in rate limiting and security
Supported Languages
Every language CLDR names, 619 in all: the 182 ISO 639-1 languages (fr, en, ja, ht, wo…) and the languages that only have an ISO 639-3 code (haw, yue, fil…). MistralTranslator.supported_locales lists them.
A locale can add a script and a region (pt-BR, zh-Hant-TW, es-419): the model is told which variant to write, and results are keyed by that locale. ISO 639-3 codes (hat for ht) and English, French or native names ("German", "allemand") are accepted in place of codes. Variants and extensions (ca-ES-valencia, en-US-u-ca-gregory) are not.
MistralTranslator.translate(text, from: "fr", to: "pt-BR")
MistralTranslator::Locale.parse("zh_hant_tw").to_s # => "zh-Hant-TW"The languages, scripts and regions come from the CLDR data of macOS 27.2, through bin/generate_languages (2026-11-17).
Translation quality depends on the Mistral model: excellent for widely used languages, weaker for rare ones. Check the output before relying on a rare language.
Installation
Add to your Gemfile:
gem 'mistral_translator'Then run:
bundle installAPI Key Setup
Get your API key from Mistral AI Console and configure it:
# Environment variable (recommended)
export MISTRAL_API_KEY="your_api_key_here"
# Or in Rails config/initializers/mistral_translator.rb
MistralTranslator.configure do |config|
config.api_key = ENV['MISTRAL_API_KEY']
config.enable_metrics = Rails.env.production?
endBasic Usage Examples
Simple Translation
# Basic translation
result = MistralTranslator.translate("Bonjour", from: "fr", to: "en")
# => "Hello"
# With context for better accuracy
result = MistralTranslator.translate(
"Le produit est disponible",
from: "fr",
to: "en",
context: "E-commerce website"
)
# => "The product is available"
# With custom glossary
result = MistralTranslator.translate(
"Notre API est performante",
from: "fr",
to: "en",
glossary: { "API" => "API" } # Preserve technical terms
)
# => "Our API is high-performing"Auto-Detection
# Automatic source language detection
MistralTranslator.translate_auto("¡Hola mundo!", to: "fr")
# => "Salut le monde !"Batch Processing
texts = ["Bonjour", "Merci", "Au revoir"]
results = MistralTranslator.translate_batch(texts, from: "fr", to: "en")
# => {0 => "Hello", 1 => "Thank you", 2 => "Goodbye"}Text Summarization
long_text = "Ruby on Rails is a web framework..."
# Simple summary
summary = MistralTranslator.summarize(long_text, language: "en", max_words: 50)
# Summary with translation
summary = MistralTranslator.summarize_and_translate(
long_text,
from: "en",
to: "fr",
max_words: 100
)Rails Integration
# With Mobility
class Article < ApplicationRecord
extend Mobility
translates :title, :content, backend: :table
def translate_to_all_languages!
MistralTranslator::RecordTranslation.translate_mobility_record(
self,
[:title, :content],
source_locale: I18n.locale
)
end
end
# Usage
article = Article.create!(title_fr: "Titre français", content_fr: "Contenu...")
article.translate_to_all_languages!Configuration Options
MistralTranslator.configure do |config|
# Required
config.api_key = ENV['MISTRAL_API_KEY']
# Optional
config.model = "mistral-small-latest" # AI model to use (an alias that follows the current Mistral Small)
config.retry_delays = [1, 2, 4, 8, 16] # Retry delays in seconds
config.enable_metrics = true # Enable performance metrics
config.proxy = :env # HTTP proxy: nil (default), "http://host:port", or :env
# to read HTTPS_PROXY / HTTP_PROXY and NO_PROXY
config.open_timeout = 60 # Seconds to open the connection (default 60)
config.read_timeout = 60 # Seconds to wait for the API's answer (default 60);
# raise it for long texts or summaries
# Callbacks for monitoring
config.on_translation_complete = ->(from, to, orig_len, trans_len, duration) {
Rails.logger.info "Translation #{from}→#{to} completed in #{duration.round(2)}s"
}
config.on_translation_error = ->(from, to, error, attempt, timestamp) {
Rails.logger.error "Translation failed: #{error.message} (attempt #{attempt})"
}
endConfigure the gem before the first call. The module-level methods (MistralTranslator.translate, summarize…) share one client, which reads api_key, model, api_url, retry_delays and the connection settings (read_timeout, proxy, SSL) on the first call. To change them afterwards, call MistralTranslator.reset_configuration! and configure again, or create a MistralTranslator::Translator.new (or Summarizer.new), which builds its own client from the current configuration.
Error Handling
begin
result = MistralTranslator.translate("Hello", from: "en", to: "fr")
rescue MistralTranslator::RateLimitError
# Rate limit hit - automatic retry with backoff
retry
rescue MistralTranslator::AuthenticationError
# Invalid API key
Rails.logger.error "Check your Mistral API key"
rescue MistralTranslator::UnsupportedLanguageError => e
# Language not supported
Rails.logger.error "Language '#{e.language}' not supported"
rescue MistralTranslator::InvalidResponseError, MistralTranslator::EmptyTranslationError
# The model kept returning an unusable answer after the retries: nothing is returned
Rails.logger.error "Translation unavailable"
rescue MistralTranslator::Error => e
# General error handling
Rails.logger.error "Translation failed: #{e.message}"
endPerformance Monitoring
# Enable metrics
MistralTranslator.configure { |c| c.enable_metrics = true }
# View metrics
metrics = MistralTranslator.metrics
puts "Total translations: #{metrics[:total_translations]}"
puts "Average time: #{metrics[:average_translation_time]}s"
puts "Error rate: #{metrics[:error_rate]}%"📖 Complete Documentation
For comprehensive guides, advanced usage, and Rails integration examples:
The complete documentation includes:
- Getting Started Guide - Step-by-step tutorials
- Advanced Usage - Context, glossaries, batch processing, monitoring
- Rails Integration - Mobility, Globalize, jobs, controllers
- API Reference - Complete method documentation
- Examples - Ready-to-use code samples
- Error Handling - Comprehensive error management strategies
Quick Links
- Installation & Setup
- Rails Integration Guide
- API Methods Reference
- Error Handling Guide
- Monitoring Setup
Requirements
- Ruby 3.2+
- Mistral AI API key, on a plan with API access (Mistral's free plan cannot generate text)
- Rails 6.0+ (optional, for Rails integration features)
Testing
# Install dependencies
bundle install
# Run all unit tests (no API key required)
bundle exec rspec spec/mistral_translator/
# Run all tests with documentation format
bundle exec rspec --format documentation
# Check the API key and default model, then run the examples against the real
# API (reads MISTRAL_TEST_API_KEY, .env or asks for the key, never prints it)
bin/check_apiIntegration Tests
Integration tests require a real Mistral API key. Never commit API keys to version control.
# Set API key via environment variable (recommended)
export MISTRAL_API_KEY="your_api_key_here"
# Run integration tests
bundle exec rspec spec/integration/
**Security Note:** Use a dedicated test API key with limited quotas for integration testing.Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
See CONTRIBUTING.md for detailed guidelines.
License
MIT License. See LICENSE for details.
Support
- 📖 Documentation
- 🐛 Issues
- 📧 Support: Create an issue for help
☕ Support the Project
If this gem helps you, consider supporting its development:
Built with Ruby ❤️ by @peyochanchan