Servir un Método Personalizado como API
El api method de champollion le permite apuntar cualquier par de traducción a un endpoint HTTP externo. Así es como integra pipelines demasiado complejos para un único prompt de LLM — analizadores morfológicos, transductores de estados finitos (FSTs), cadenas de LLM de múltiples pasos, o cualquier método de investigación personalizado que haya desarrollado.
¿Por qué un Servicio API?
Algunos pipelines de traducción no pueden ejecutarse dentro de un ciclo simple de solicitud-respuesta:
| Paso del pipeline | Ejemplo |
|---|---|
| Descomposición morfológica | Dividir palabras polisintéticas en morfemas antes de la traducción |
| Validación FST | Rechazar salidas que violen reglas fonológicas o morfológicas |
| Cadenas de LLM de múltiples pasos | Ciclos de generar → verificar → corregir con diferentes modelos |
| Búsqueda en diccionario | Hacer referencia cruzada a un diccionario bilingüe curado durante el pipeline |
| Intervención humana | Encolar traducciones inciertas para revisión de expertos |
El api method trata su pipeline como una caja negra — champollion envía cadenas de origen, su servicio devuelve traducciones. Lo que sucede dentro depende completamente de usted.
Arquitectura
Configurar Su Servicio
Su servicio API debe implementar un único endpoint que acepte y devuelva JSON:
Formato de Solicitud
champollion envía este cuerpo JSON exacto (véase api.js):
POST /translate
Content-Type: application/json
Authorization: Bearer <CHAMPOLLION_API_KEY>
{
"source_locale": "en",
"target_locale": "crk",
"method": "crk-coached-v1",
"keys": {
"greeting": "Hello, welcome to our app",
"farewell": "Goodbye and thanks"
}
}
| Campo | Tipo | Descripción |
|---|---|---|
source_locale | string | Código de idioma de origen BCP 47 |
target_locale | string | Código de idioma de destino BCP 47 |
method | string | Nombre del plugin o "default" |
keys | object | Mapa de clave → cadena de origen a traducir |
Formato de Respuesta
Su servicio debe devolver:
### 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"
}
}
| Field | Type | Required | Description |
|---|---|---|---|
translations | object | ✅ | Map of key → translated string |
meta | object | — | Optional metadata |
meta.cost_usd | number | — | If present, displayed in champollion's output |
errors | object | — | For partial success (HTTP 207): map of key → { message } |
Minimal Express Server
import express from 'express';
const app = express();
app.use(express.json());
/**
* champollion 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 champollion
Point a translation pair at your running service in champollion.config.json:
### Configurar champollion
Agregue el endpoint a su configuración:
Then run sync as usual:
{
"inputLocale": "en",
"pairs": {
"en:crk": {
"method": "api",
"endpoint": "http://localhost:3001/translate",
"register": "Formal Plains Cree. Use SRO orthography."
}
}
}
champollion 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 arena project demonstrates this pattern. Its Plains Cree pipeline uses:
- Morphological decomposition — Break polysynthetic Cree words into translatable morpheme chains
- LLM translation — Context-enriched GPT-4o translation with coaching data (SRO orthography rules, register instructions)
- FST validation — Finite-state transducer checks that outputs conform to Cree phonological rules
- 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 champollion calls via the api method.
Running Evaluations
After translating, you can evaluate output quality using the harness directly:
Luego ejecute:
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:
npx champollion sync
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.
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:
### Evaluar Su Método
Use la herramienta de evaluación de MT Arena para comparar su método con otros:
`api`bash
# Clone the harness
git clone https://github.com/gamedaysuits/arena.git
cd arena
pip install -e .
# Run the evaluation against your method's output
mt-eval run --corpus data/edtekla-dev-v1.json --submit
`api`
## Autenticación
Si su servicio requiere autenticación, pase credenciales a través de variables de entorno:
`source_locale`json
{
"pairs": {
"en:crk": {
"method": "api",
"endpoint": "https://my-mt-service.example.com/translate",
"apiKey": "${CRK_API_KEY}"
}
}
}
`target_locale`
champollion inyectará la variable de entorno `CRK_API_KEY` en el header `Authorization: Bearer` de cada solicitud.
## Seguimiento de Costos
Si su pipeline incurre en costos (llamadas a LLM, acceso a API, etc.), devuelva información de costos en la respuesta:
`method`json
{
"translations": { "...": "..." },
"metadata": {
"cost": {
"estimatedCost": 0.0042,
"currency": "USD",
"source": "my-service-pricing"
}
}
}
`"default"`
## Mejores Prácticas
1. **Devuelva cadenas vacías para fallos** — No devuelva la cadena de origen como una "traducción". Devuelva `""` y la puerta de calidad de champollion lo detectará. La clave se omitirá y se reintentará en la siguiente sincronización.
2. **Incluya puntuaciones de confianza** — Si su pipeline puede estimar la calidad, devuélvala en metadatos. Esto ayuda con la auditoría de calidad.
3. **Implemente verificaciones de salud** — Agregue un endpoint `GET /health` para que champollion pueda verificar la conectividad antes de iniciar una sincronización grande.
4. **Limite la velocidad con elegancia** — Si su pipeline tiene límites de rendimiento, devuelva códigos de estado `429`. El sistema de lotes de champollion se retirará.
5. **Registre todo** — Los pipelines de múltiples pasos pueden fallar silenciosamente. Registre la entrada/salida de cada paso para depuración.
## Licencia
El patrón `api` method es completamente abierto — no hay restricciones de licencia para envolver su propio pipeline de traducción como un servicio HTTP. El `arena` está disponible bajo licencia MIT para implementaciones de referencia.
## Véase También
- [Métodos de Traducción](/docs/guides/translation-methods) — descripción general de cada método integrado (`openai`, `google`, `api`, etc.)
- [Especificación de Plugin](/docs/reference/plugin-spec) — esquema completo para `champollion.config.json` incluyendo campos del `api` method
- [Apoyar un Idioma de Bajo Recurso](https://mtevalarena.org/docs/community/low-resource-languages) — guía de extremo a extremo para idiomas insuficientemente dotados de recursos, incluyendo principios OCAP
- [Arquitectura](/docs/concepts/architecture) — cómo funcionan el bucle de sincronización, el lote y el envío de métodos de champollion
- [Evaluación de MT](https://mtevalarena.org/docs/leaderboard/rules) — metodología de evaluación, métricas y el proceso de envío del leaderboard
- [Leaderboard de Métodos](/leaderboard) — clasificaciones de calidad en vivo entre métodos y pares de idiomas