iflytek/astron-agent · warning · ValueError

Invalid target language

Error message

Invalid target language: {value}.
Valid options: {list(VALID_LANGUAGE_CODES)}

What it means

The `validate_target_language` pydantic field validator raises this ValueError when `target_language` is not one of the keys in VALID_LANGUAGE_CODES. The upstream translation API only accepts a fixed set of language codes, so invalid codes are rejected at request-validation time. The error message itself lists all accepted codes.

Solutions

  1. Use a code from the list printed in the error message (VALID_LANGUAGE_CODES), e.g. "cn" for Chinese.
  2. Map your client's codes to the API's scheme before calling (e.g. zh → cn).
  3. Populate the language dropdown in the UI from the same VALID_LANGUAGE_CODES source to prevent drift.
  4. Normalize casing/whitespace on the client since the membership check is exact.

Example fix

// before
await translate({ text, target_language: 'zh' });
// after
const CODE_MAP = { zh: 'cn', 'zh-cn': 'cn', en: 'en' };
await translate({ text, target_language: CODE_MAP[target] ?? target });
Defensive patterns

Strategy: validation

Validate before calling

function isValidTargetLang(code) {
  return VALID_LANGUAGE_CODES.includes(code);
}

Type guard

function isApiLangCode(v: string): v is ApiLangCode {
  return (VALID_LANGUAGE_CODES as readonly string[]).includes(v);
}

Try / catch

try:
    inp = TranslationInput(**payload)
except ValidationError as e:
    if 'Invalid target language' in str(e):
        return error_response(f'支持的语言: {sorted(VALID_LANGUAGE_CODES)}', 400)
    raise

Prevention

When it happens

Trigger: Constructing TranslationInput with target_language like "zh", "chinese", "EN", "fr" or any code absent from VALID_LANGUAGE_CODES — wrong casing, full language names, or codes for languages the API doesn't support.

Common situations: Client uses ISO 639-1 codes ("zh", "en") while the API expects its own scheme ("cn"); UI sends human-readable names; typos like "chn"; hardcoded defaults from another product's code set.

Understand the failure class

Background: Invalid enum value errors: "Unknown type", "Invalid scope", "must be one of" — when a string is not on the library's allowed list — this error's family across 23 libraries.

Related errors


AI-assisted analysis of iflytek/astron-agent@5e758547a8 (2026-09-12). Data as JSON: /api/errors/1f8e4a248733d564. Report an issue: GitHub.

Appendix: source

Thrown at core/plugin/aitools/service/translation/translation_service.py:58

        CHINESE_LANGUAGE_CODE  # Source language code, default Chinese
    )

    @field_validator("text")
    @classmethod
    def validate_text(cls, value: str) -> str:
        """validate text"""
        if not value or not value.strip():
            raise ValueError("Translation text cannot be empty")
        if len(value) > 5000:
            raise ValueError("Translation text cannot exceed 5000 characters")
        return value

    @field_validator("target_language")
    @classmethod
    def validate_target_language(cls, value: str) -> str:
        """validate target language"""
        if value not in VALID_LANGUAGE_CODES:
            raise ValueError(
                f"Invalid target language: {value}.\n"
                f"Valid options: {list(VALID_LANGUAGE_CODES)}"
            )
        return value

    @field_validator("source_language")
    @classmethod
    def validate_source_language(cls, value: str) -> str:
        """validate source language"""
        if value not in VALID_LANGUAGE_CODES:
            raise ValueError(
                f"Invalid source language: {value}.\n"
                f"Valid options: {list(VALID_LANGUAGE_CODES)}"
            )
        return value

    @model_validator(mode="after")
    def validate_language_combination(self) -> "TranslationInput":

View on GitHub (pinned to 5e758547a8)