huggingface/transformers · error · HTTPException
Unexpected fields in the request: {unexpected}
Error message
Unexpected fields in the request: {unexpected} What it means
HTTP 422 from the generic request validator shared by the JSON-body handlers (chat/completions style endpoints). It subtracts the request body's keys from the handler's params class __mutable_keys__ and rejects any key the params class does not declare. Recognized-but-unsupported fields only log a warning; unknown fields fail.
Source
Thrown at src/transformers/cli/serving/utils.py:1092
def __init__(
self,
model_manager: "ModelManager",
generation_state: GenerationState,
chat_template_kwargs: dict | None = None,
):
self.model_manager = model_manager
self.generation_state = generation_state
self.chat_template_kwargs = chat_template_kwargs or {}
def _validate_request(self, body: dict) -> None:
"""Validate request fields against the handler's params class and unused fields."""
from fastapi import HTTPException
input_keys = set(body.keys())
if self._valid_params_class is not None:
unexpected = input_keys - getattr(self._valid_params_class, "__mutable_keys__", set())
if unexpected:
raise HTTPException(status_code=422, detail=f"Unexpected fields in the request: {unexpected}")
unused = input_keys & self._unused_fields
if unused:
logger.warning_once(f"Ignoring unsupported fields in the request: {unused}")
@staticmethod
def chunk_to_sse(chunk: "str | pydantic.BaseModel") -> str:
"""Format a pydantic model or string as an SSE ``data:`` line."""
if isinstance(chunk, str):
return chunk if chunk.startswith("data: ") else f"data: {chunk}\n\n"
return f"data: {chunk.model_dump_json(exclude_none=True)}\n\n"
def _resolve_model(self, body: dict) -> tuple[str, "PreTrainedModel", "ProcessorMixin | PreTrainedTokenizerFast"]:
"""Apply force_model, load model + processor.
Returns ``(model_id, model, processor)``.
"""
from fastapi import HTTPException
View on GitHub (pinned to a597f97485)
Solutions
- Drop the fields named in the error detail from the request body
- Print the handler's params class __mutable_keys__ to see the accepted schema for your transformers version
- If you control both sides, add the field to the params class instead of sending unknown keys
Example fix
// before
body = {model: 'gpt2', messages, user_id: 'abc'}
// after
body = {model: 'gpt2', messages} Defensive patterns
Strategy: validation
Validate before calling
allowed = set(ParamsClass.__mutable_keys__) # the handler's params class
clean = {k: v for k, v in body.items() if k in allowed}
body = clean Try / catch
if resp.status_code == 422 and 'Unexpected fields' in resp.text:
unexpected = set(re.findall(r"'([^']+)'", resp.json()['detail']))
body = {k: v for k, v in body.items() if k not in unexpected}
resp = client.post('/v1/chat/completions', json=body) Prevention
- Filter request bodies against the params class before sending
- Pin the transformers version on both client and server so the accepted schema is stable
When it happens
Trigger: POST to a chat/completions-style endpoint with body keys outside the handler's params class — e.g. custom params like 'top_k' where unsupported, 'user_id', or misspelled names like 'temperatur'.
Common situations: Clients written against the OpenAI API sending extensions this server does not define; version skew where a field was added or renamed between transformers releases; SDK defaults injecting metadata fields.
Related errors
- 'input' must be a string or list
- Unsupported input item type: {item_type!r}
- Missing `model` field in the request body.
- Unexpected fields in the request: {unexpected}
- Expected file upload, got string
AI-assisted analysis of huggingface/transformers@a597f97485 (2026-08-14).
Data as JSON: /api/errors/a777c3a2587dae37.
Report an issue: GitHub.