DEV Community

Cover image for Building a Language-Aware Guardrail Layer for LLM Apps (So You Stop Shipping English Errors to Spanish Users)
Diogo Heleno
Diogo Heleno

Posted on Originally published at m21global.com

Building a Language-Aware Guardrail Layer for LLM Apps (So You Stop Shipping English Errors to Spanish Users)

If you've shipped a multilingual product with an LLM in the loop, you've probably hit this bug: a user chats in Portuguese, the model replies in English halfway through, and nobody notices until a support ticket shows up. This isn't a translation bug in the traditional sense. It's an architecture gap.

A good write-up on the problem space is this article on localising generative AI products, which breaks down why static i18n workflows don't map cleanly onto generated text. That article is aimed at product and localisation teams. This one is for the people who actually have to build the thing: what does a language-aware guardrail layer look like in code, and where do you draw the line between "let the model handle it" and "never let the model touch this"?

The three layers, from an engineering point of view

You've got three places where language matters, and they need completely different tooling:

  1. Static UI strings — solved problem. i18next, react-intl, .po files, whatever. Not interesting here.
  2. System prompts — these are code, but they're rarely treated like code. They get hardcoded in English, then someone pastes them into a translation tool once and forgets about them.
  3. Generated output — no fixed string exists. You're not translating text, you're constraining a distribution.

Most multilingual incidents come from treating layer 3 like layer 1, or not treating layer 2 as a first-class config at all.

Don't let the model author your compliance text

The single highest-leverage fix: pull anything with legal, safety, or compliance weight out of the generative path entirely. Let the model narrate around it, but inject the actual warning as a fixed, versioned string.

// bad: model phrases the warning itself
const reply = await llm.chat({
  messages: [...history, userMessage],
  system: "Warn the user this advice is not a medical diagnosis."
});

// better: deterministic injection, model fills in the conversational part
const DISCLAIMERS = {
  en: "This is not a medical diagnosis. Consult a professional.",
  pt: "Isto não é um diagnóstico médico. Consulte um profissional.",
  es: "Esto no es un diagnóstico médico. Consulte a un profesional.",
};

const reply = await llm.chat({
  messages: [...history, userMessage],
  system: "Respond helpfully. Do not add medical disclaimers yourself; one will be appended."
});

const finalReply = `${reply}\n\n${DISCLAIMERS[detectedLang] ?? DISCLAIMERS.en}`;
Enter fullscreen mode Exit fullscreen mode

This gives you two things for free:

  • Auditability: if a regulator or legal team wants every warning your app can show, you grep DISCLAIMERS and hand over a static list, not a log of generated text that varies between runs.
  • Versioning: you can diff the warning text across releases, run it through normal translation review, and know exactly when it changed.

Treat DISCLAIMERS, error messages, and anything safety-critical as config, reviewed and translated the same way you'd handle any other resource file. Don't let it live inside a prompt string.

Localise the system prompt, not just the output

System prompts encode behavioural instructions — tone, register, refusal style. If your system prompt says "be concise and professional" in English and you rely on the model to generically apply that instruction while replying in Japanese, you'll get inconsistent register. A literal translation of the instruction itself isn't the fix either; "concise and professional" maps to different defaults in different languages and cultures.

Treat system prompts as localisable artifacts with their own review cycle:

const SYSTEM_PROMPTS = {
  en: "Respond concisely, in a professional tone suited to B2B software support.",
  de: "Antworten Sie präzise und in einem formellen, professionellen Ton, wie es im B2B-Softwaresupport üblich ist.",
  pt_BR: "Responda de forma clara e acessível, mantendo um tom profissional mas próximo, adequado ao suporte de software B2B.",
};

function buildSystemPrompt(lang) {
  return SYSTEM_PROMPTS[lang] ?? SYSTEM_PROMPTS.en;
}
Enter fullscreen mode Exit fullscreen mode

Note the German and Brazilian Portuguese versions aren't translations of each other. They're adapted instructions written for how formality actually works in each market. This needs input from someone who knows the register expectations, not just a bilingual engineer.

Testing behaviour, not strings

This is the part that trips up most CI setups. You can't unit test "the model replied correctly" the way you test a translated string's existence. You need scenario-based eval suites per language.

test_scenarios = [
    {"id": "refund_request", "lang": "es", "input": "Quiero cancelar mi suscripción"},
    {"id": "refund_request", "lang": "pt", "input": "Quero cancelar a minha subscrição"},
    {"id": "out_of_scope", "lang": "fr", "input": "Peux-tu me donner un conseil juridique ?"},
]

for case in test_scenarios:
    reply = run_chat(case["input"], lang=case["lang"])
    assert detect_language(reply) == case["lang"], "language drift"
    assert_terminology_consistent(reply, glossary[case["lang"]])
    assert_no_banned_phrases(reply, risk_terms[case["lang"]])
Enter fullscreen mode Exit fullscreen mode

Three checks matter most in practice:

  • Language drift detection: run every reply through a language identifier (fasttext's lid.176 model works fine for this) and fail the test if output language doesn't match input language.
  • Terminology consistency: maintain a per-language glossary and flag replies that use inconsistent terms for the same concept across a conversation. Simple string matching against a glossary dict catches most of it.
  • Refusal behaviour: boundary cases (the model declining to answer) need their own test set per language, because refusal phrasing and what triggers it culturally differ. A refusal that reads as polite in Japanese can read as evasive translated literally into English.

Routing review effort by risk, not by volume

Not everything needs a human linguist in the loop. A useful split:

  • High risk (legal, safety, compliance): fixed strings, translated and reviewed by a second linguist, version-controlled like any other config.
  • Medium risk (general UI, system prompts): machine-translated with a human post-edit pass, especially for system prompts where tone matters.
  • Low risk, high volume (FAQ banks, prompt test fixtures): machine translation with spot-checks on the segments your eval suite flags as error-prone.

This mirrors how solid SaaS localisation pipelines are structured generally, something covered in more depth in this piece on ISO 17100 workflows for SaaS platforms. The pattern holds for AI products: separate content by risk, match the review intensity to the risk, don't apply one workflow to everything.

The takeaway for implementation

If you're building multilingual AI features, the fix isn't "add more languages to the system prompt." It's architectural:

  • Pull compliance and safety text out of the generative path into versioned, reviewed config.
  • Treat system prompts as localised artifacts, not English strings the model generalises from.
  • Build scenario-based eval suites per language that check behaviour (drift, terminology, refusals), not just string presence.
  • Route human review effort based on risk, not uniformly across all content.

None of this requires exotic tooling. It requires treating language as a first-class dimension of your test matrix, the same way you already treat browsers or device sizes.

Top comments (0)