Passer au contenu principal

Exposer une méthode personnalisée sous forme d'API

La méthode api d'i18n-rosetta vous permet de diriger n'importe quelle paire de traduction vers un endpoint HTTP externe. C'est ainsi que vous intégrez des pipelines qui sont trop complexes pour un simple prompt LLM — analyseurs morphologiques, transducteurs à états finis (FST), chaînes LLM à plusieurs étapes, ou toute méthode de recherche personnalisée que vous avez développée.

Pourquoi un service API ?

Certains pipelines de traduction ne peuvent pas s'exécuter dans un simple cycle prompt-réponse :

Étape du pipelineExemple
Décomposition morphologiqueSéparer les mots polysynthétiques en morphèmes avant la traduction
Validation FSTRejeter les résultats qui enfreignent les règles phonologiques ou morphologiques
Chaînes LLM à plusieurs étapesCycles de génération → vérification → correction avec différents modèles
Recherche dans un dictionnaireCroiser les données avec un dictionnaire bilingue révisé au milieu du pipeline
Intervention humaineMettre en file d'attente les traductions incertaines pour une révision par des experts

La méthode api traite votre pipeline comme une boîte noire — i18n-rosetta envoie les chaînes sources, votre service renvoie les traductions. Ce qui se passe à l'intérieur dépend entièrement de vous.

Architecture

Configuration de votre service

Votre service API doit implémenter un endpoint unique qui accepte et renvoie du JSON :

Format de la requête

rosetta envoie exactement ce corps JSON (voir api.js) :

POST /translate
Content-Type: application/json
Authorization: Bearer <ROSETTA_API_KEY>

{
"source_locale": "en",
"target_locale": "crk",
"method": "crk-coached-v1",
"keys": {
"greeting": "Hello, welcome to our app",
"farewell": "Goodbye and thanks"
}
}
ChampTypeDescription
source_localestringCode de langue source BCP 47
target_localestringCode de langue cible BCP 47
methodstringNom du plugin ou "default"
keysobjectMapping de la clé → chaîne source à traduire

### Response Format

Your service must return a `translations` object. An optional `meta` object can include cost and diagnostic info:

```json
{
"translations": {
"greeting": "tânisi, pê-kîwêw ôta",
"farewell": "ekosi mâka, kinanâskomitin"
},
"meta": {
"model": "my-custom-pipeline/v1",
"cost_usd": 0.0042,
"method": "decompose-translate-validate"
}
}
FieldTypeRequiredDescription
translationsobjectMap of key → translated string
metaobjectOptional metadata
meta.cost_usdnumberIf present, displayed in rosetta's output
errorsobjectFor partial success (HTTP 207): map of key → { message }

Minimal Express Server

import express from 'express';

const app = express();
app.use(express.json());

/**
* rosetta API contract:
*
* Request: { source_locale, target_locale, method, keys: { "key": "source" } }
* Response: { translations: { "key": "translated" }, meta: { ... } }
*/
app.post('/translate', async (req, res) => {
const { source_locale, target_locale, method, keys } = req.body;

const translations = {};

for (const [key, source] of Object.entries(keys)) {
// --- Your pipeline goes here ---
// Step 1: Morphological decomposition
const morphemes = await decompose(source, source_locale);

// Step 2: LLM translation with context
const draft = await llmTranslate(morphemes, target_locale);

// Step 3: FST validation
const validated = await fstValidate(draft, target_locale);

// Step 4: Post-processing (orthography normalization, etc.)
translations[key] = await postProcess(validated);
}

res.json({
translations,
meta: {
model: 'my-custom-pipeline/v1',
method: 'decompose-translate-validate',
},
});
});

app.listen(3001, () => {
console.log('Translation API running on http://localhost:3001');
});

Configuring i18n-rosetta

Point a translation pair at your running service in i18n-rosetta.config.json:

{
"inputLocale": "en",
"pairs": {
"en:crk": {
"method": "api",
"endpoint": "http://localhost:3001/translate",
"register": "Formal Plains Cree. Use SRO orthography."
}
}
}

Then run sync as usual:

npx i18n-rosetta sync

i18n-rosetta will POST your source strings to the endpoint and write the returned translations to crk.json.

Case Study: Plains Cree Pipeline

:::info Under Development The Plains Cree pipeline described below is under active development and is not yet running in production. Details here reflect the current design direction and may change as the project evolves. :::

The gds-mt-eval-harness project demonstrates this pattern. Its Plains Cree pipeline uses:

  1. Morphological decomposition — Break polysynthetic Cree words into translatable morpheme chains
  2. LLM translation — Context-enriched GPT-4o translation with coaching data (SRO orthography rules, register instructions)
  3. FST validation — Finite-state transducer checks that outputs conform to Cree phonological rules
  4. Confidence scoring — Each translation gets a confidence score based on FST pass rate and dictionary coverage

The entire pipeline runs as a single HTTP endpoint that i18n-rosetta calls via the api method.

Running Evaluations

After translating, you can evaluate output quality using the harness directly:

# Clone the harness
git clone https://github.com/gamedaysuits/gds-mt-eval-harness.git
cd gds-mt-eval-harness
pip install -e .

# Run the evaluation against your method's output
python eval/baseline_experiment.py --dataset data/edtekla-dev-v1.json --submit

This produces structured evaluation records with chrF++, BLEU, and exact match scores that can be used as regression baselines.

Authentication

If your API requires authentication, set the apiKey field or use an environment variable:

{
"pairs": {
"en:crk": {
"method": "api",
"endpoint": "https://my-mt-service.example.com/translate",
"apiKey": "${CRK_API_KEY}"
}
}
}

Data Sovereignty & OCAP Principles

The api method is particularly important for Indigenous language communities. By self-hosting the translation pipeline, a community keeps full control over:

  • Proprietary coaching data — register instructions, orthography rules, and domain glossaries never leave community infrastructure.
  • Linguistic resources — curated dictionaries, FST grammars, and elder-verified translations remain under community ownership.
  • Access policies — the community decides who can call the endpoint and under what terms.

This aligns with OCAP® principles (Ownership, Control, Access, Possession), ensuring that sensitive language data is governed by the community rather than a third-party platform.

astuce

Combine the api method with a private deployment (e.g., a community-hosted VM or on-prem server) for the strongest data-sovereignty posture. See Support a Low-Resource Language for a full walkthrough.

Cost Estimation

The api method returns null for cost estimation by default — your service controls pricing. If you want to provide cost transparency, have your API return a cost field in the metadata:

{
"translations": { "...": "..." },
"metadata": {
"cost": {
"estimatedCost": 0.0042,
"currency": "USD",
"source": "my-service-pricing"
}
}
}

Bonnes pratiques

  1. Renvoyez des chaînes vides en cas d'échec — Ne renvoyez pas la chaîne source en tant que "traduction". Renvoyez "" et le contrôle qualité d'i18n-rosetta l'interceptera. La clé sera ignorée et une nouvelle tentative aura lieu lors de la prochaine synchronisation.
  2. Incluez des scores de confiance — Si votre pipeline peut estimer la qualité, renvoyez-la dans les métadonnées. Cela facilite l'audit de qualité.
  3. Implémentez des vérifications d'état (health checks) — Ajoutez un endpoint GET /health afin qu'i18n-rosetta puisse vérifier la connectivité avant de lancer une synchronisation massive.
  4. Gérez les limites de requêtes (rate limit) avec souplesse — Si votre pipeline a des limites de débit, renvoyez les codes d'état 429. Le système de traitement par lots d'i18n-rosetta réduira sa cadence.
  5. Journalisez tout — Les pipelines à plusieurs étapes peuvent échouer silencieusement. Journalisez les entrées/sorties de chaque étape pour faciliter le débogage.

Licence

Le modèle de la méthode api est entièrement ouvert — il n'y a aucune restriction de licence pour encapsuler votre propre pipeline de traduction sous forme de service HTTP. Le gds-mt-eval-harness est disponible sous licence MIT pour les implémentations de référence.

Voir aussi