Skip to content

Fix KeyError in _parse_type_hint when Union contains Any#44525

Merged
Rocketknight1 merged 2 commits intohuggingface:mainfrom
jnMetaCode:fix/chat-template-get-json-schema-keyerror
Mar 9, 2026
Merged

Fix KeyError in _parse_type_hint when Union contains Any#44525
Rocketknight1 merged 2 commits intohuggingface:mainfrom
jnMetaCode:fix/chat-template-get-json-schema-keyerror

Conversation

@jnMetaCode
Copy link
Copy Markdown
Contributor

Summary

Fixes a KeyError crash in _parse_type_hint in chat_template_utils.py (line 117).

When processing Union types, the code accesses subtype["type"] without checking the key exists. _get_json_schema_type(Any) returns {} (empty dict with no "type" key), so Union types containing Any (e.g., Union[str, Any]) crash with a KeyError.

# Before:
elif all(isinstance(subtype["type"], str) for subtype in subtypes):

# After:
elif all("type" in subtype and isinstance(subtype["type"], str) for subtype in subtypes):

This guard ensures the code falls through to the anyOf branch for types that don't have a simple "type" key.

Test plan

  • Verified _get_json_schema_type(Any) returns {} with no "type" key
  • Verified the fix correctly falls through to the anyOf branch
  • Existing tests should continue to pass

In _parse_type_hint, when processing Union types, the code
accesses subtype["type"] without checking the key exists.
Union types containing `Any` crash because _get_json_schema_type(Any)
returns {} with no "type" key, causing a KeyError.

Add a guard to check "type" key existence before accessing it.

Signed-off-by: JiangNan <1394485448@qq.com>
Copy link
Copy Markdown
Member

@Rocketknight1 Rocketknight1 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, LGTM!

@Rocketknight1 Rocketknight1 enabled auto-merge (squash) March 9, 2026 13:30
@HuggingFaceDocBuilderDev
Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@Rocketknight1 Rocketknight1 merged commit 0130c7d into huggingface:main Mar 9, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants