Ir para o conteúdo principal

Servindo um Método Personalizado como uma API

O api method do champollion permite apontar qualquer par de tradução para um endpoint HTTP externo. É assim que você integra pipelines muito complexos para um único prompt de LLM — analisadores morfológicos, transdutores de estado finito (FSTs), cadeias de LLM multi-etapas, ou qualquer método de pesquisa personalizado que você tenha desenvolvido.

Por que um Serviço de API?

Alguns pipelines de tradução não conseguem rodar dentro de um simples ciclo de solicitação-resposta:

Etapa do pipelineExemplo
Decomposição morfológicaDividir palavras polissintéticas em morfemas antes da tradução
Validação FSTRejeitar saídas que violem regras fonológicas ou morfológicas
Cadeias de LLM multi-etapasGerar → verificar → corrigir ciclos com modelos diferentes
Busca em dicionárioFazer referência cruzada a um dicionário bilíngue curado no meio do pipeline
Human-in-the-loopEnfileirar traduções incertas para revisão de especialistas

O api method trata seu pipeline como uma caixa preta — champollion envia strings de origem, seu serviço retorna traduções. O que acontece dentro é inteiramente sua responsabilidade.

Arquitetura

Configurando Seu Serviço

Seu serviço de API deve implementar um único endpoint que aceita e retorna JSON:

Formato de Solicitação

champollion envia este corpo JSON exato (veja 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"
}
}
CampoTipoDescrição
source_localestringCódigo de idioma de origem BCP 47
target_localestringCódigo de idioma de destino BCP 47
methodstringNome do plugin ou "default"
keysobjectMapa de chave → string de origem para traduzir

Formato de Resposta

Seu serviço retorna este JSON:


### 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 champollion's output
errorsobjectFor partial success (HTTP 207): map of key → { message }

Minimal Express Server


### Exemplo: Express.js

FieldTypeRequiredDescription
translationsobjectMap of key → translated string
metaobjectOptional metadata
meta.cost_usdnumberIf present, displayed in champollion'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());

/**
* 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:


### Configurando champollion

Aponte seu par de tradução para o endpoint:

Then run sync as usual:

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

Then run sync as usual:


Depois execute a sincronização:

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:

  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 champollion calls via the api method.

Running Evaluations

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

npx champollion sync

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:

  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 champollion calls via the api method.

Running Evaluations

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


## Avaliando Sua Saída

Use o [MT Evaluation Arena](https://mtevalarena.org) para comparar sua saída com outros métodos:

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:

# 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

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:


## Autenticação

Se seu serviço requer autenticação, passe credenciais via variáveis de ambiente:

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.

dica

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:

{
"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.

dica

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:


## Rastreamento de Custos

Se seu pipeline tem custos associados, retorne-os em metadata:

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

## Melhores Práticas

1. **Retorne strings vazias para falhas** — Não retorne a string de origem como uma "tradução". Retorne `""` e o gate de qualidade do champollion vai detectar. A chave será pulada e retentada na próxima sincronização.
2. **Inclua scores de confiança** — Se seu pipeline conseguir estimar qualidade, retorne em metadata. Isso ajuda com auditoria de qualidade.
3. **Implemente health checks** — Adicione um `GET /health` endpoint para que champollion possa verificar conectividade antes de iniciar uma sincronização grande.
4. **Limite taxa graciosamente** — Se seu pipeline tem limites de throughput, retorne `429` status codes. O sistema de batch do champollion vai recuar.
5. **Registre tudo** — Pipelines multi-etapas podem falhar silenciosamente. Registre entrada/saída de cada etapa para debug.

## Licenciamento

O padrão `api` method é totalmente aberto — não há restrições de licenciamento ao envolver seu próprio pipeline de tradução como um serviço HTTP. O `arena` está disponível sob licença MIT para implementações de referência.

## Veja Também

- [Métodos de Tradução](/docs/guides/translation-methods) — visão geral de cada método integrado (`openai`, `google`, `api`, etc.)
- [Especificação de Plugin](/docs/reference/plugin-spec) — schema completo para `champollion.config.json` incluindo campos do `api` method
- [Suportar um Idioma de Baixo Recurso](https://mtevalarena.org/docs/community/low-resource-languages) — guia end-to-end para idiomas sub-recursos, incluindo princípios OCAP
- [Arquitetura](/docs/concepts/architecture) — como o loop de sincronização, batching e dispatch de método do champollion funcionam
- [Avaliação de MT](https://mtevalarena.org/docs/leaderboard/rules) — metodologia de avaliação, métricas e processo de submissão do leaderboard
- [Leaderboard de Métodos](/leaderboard) — rankings de qualidade ao vivo entre métodos e pares de idiomas