Language Detector API
This package wraps the built-in Language Detector API. It returns confidence scores and sorted alternatives. It also adds session reuse, optional result caching, and abort cleanup. For React, see useDetector.
Before shipping, review the Production checklist for intent-driven preparation, task-relevant input, progress, and cache freshness.
Use prepareLanguageDetector to warm a session on user intent and release it when the feature closes. See the Session lifecycle guide.
import { detect } from "@web-ai-sdk/detector";
const result = await detect({ input: "Olá, mundo" });console.log(result.output?.language); // result: "pt"console.log(result.output?.confidence); // result: 0.98console.log(result.output?.all); // result: [{ detectedLanguage, confidence }, ...]result.output is the detection result with language (BCP-47), confidence, and all (full sorted candidates), or null for empty input or when the top confidence is below minConfidence. result.cached indicates whether the response came from the cache without invoking the model.
Options
Section titled “Options”interface DetectOptions { input: string; expectedInputLanguages?: readonly string[]; minConfidence?: number; monitor?: (m: CreateMonitor) => void; cache?: "session" | "local" | { get, set }; cacheKey?: string; cacheTtl?: number; // built-in shortcut TTL in ms; default 1 hour cacheRefresh?: boolean; // skip the cache read, write the fresh result signal?: AbortSignal;}Returns
Section titled “Returns”interface DetectResult { output: { language: string; confidence: number; all: DetectionResult[] } | null; cached: boolean;}How it works
Section titled “How it works”Chrome’s LanguageDetector exposes LanguageDetector.create({...}) to spin up a session and detector.detect(text) to run it. The wrapper does the same three things on top that the other packages do:
- Feature detection.
isAvailable()/checkAvailability()returnfalse/nullon browsers without the API. The vanilladetect()throwsDetectorUnavailableError; the React hook surfacesstatus: "unavailable". - Session reuse. Internally caches
LanguageDetector.create()byexpectedInputLanguagesshape. Cold-start is fast on this model (~100-300ms); warm calls are sub-50ms. - Optional result cache. Off by default. Pass
cache: "session"to memoize results insessionStorage, orcache: "local"forlocalStorage, or any{ get, set }-shaped object for a custom backend. Built-in"session"/"local"entries expire after one hour by default. PasscacheTtl(milliseconds) to change the TTL per call. PasscacheRefresh: trueto skip the read and replace the cached value after a successful run. Custom{ get, set }caches own their expiry policy.
Confidence threshold
Section titled “Confidence threshold”By default, detect() returns the highest-confidence candidate regardless of how confident the model actually is. For ambiguous input (single word, emoji-only, gibberish) the model may return detectedLanguage: "und" with low confidence. Set minConfidence to suppress these:
const result = await detect({ input: "??", minConfidence: 0.8 });// returns { output: null, cached: false }When output is null due to threshold, the full candidate list isn’t returned. Lower minConfidence to 0 and inspect result.output.all if you need to see the alternates.
Bias hints
Section titled “Bias hints”Pass expectedInputLanguages when you have a prior on what to expect. The model uses it to break ties between similar languages (e.g. pt vs gl, no vs nb):
detect({ input: "Lorem ipsum dolor sit amet", expectedInputLanguages: ["la", "en", "it"],});The hint is also forwarded to availability() so the capability check and creation request use the same shape.
Composing with the other packages
Section titled “Composing with the other packages”The detector intentionally doesn’t reach into the other packages; one package wraps one capability. To skip the manual language: "en" argument when the input language isn’t known ahead of time, wire the two yourself:
import { detect } from "@web-ai-sdk/detector";import { summarize } from "@web-ai-sdk/summarizer";
const { output } = await detect({ input: articleText });await summarize({ language: output?.language ?? "en", input: articleText,});A first-class language: "auto" shortcut isn’t planned for this package. Multi-package compositions like detect-then-summarize, detect-then-translate, or detect-then-prompt are written in consumer code.
Aborting
Section titled “Aborting”AbortSignal is supported. The result cache is not written for aborted runs.
const controller = new AbortController();detect({ input: "long input…", signal: controller.signal });controller.abort();Errors and unavailability
Section titled “Errors and unavailability”The vanilla detect() throws DetectorUnavailableError when the API is missing or reports availability: "unavailable". Callers branch explicitly:
import { detect, DetectorUnavailableError } from "@web-ai-sdk/detector";
try { const result = await detect({ input });} catch (err) { if (err instanceof DetectorUnavailableError) { return null; } throw err;}