Skip to content

fix(cli): Fix TypeAdapter NameError when pydantic is not installed#43842

Open
Mr-Neutr0n wants to merge 1 commit intohuggingface:mainfrom
Mr-Neutr0n:fix/serve-typeadapter-import
Open

fix(cli): Fix TypeAdapter NameError when pydantic is not installed#43842
Mr-Neutr0n wants to merge 1 commit intohuggingface:mainfrom
Mr-Neutr0n:fix/serve-typeadapter-import

Conversation

@Mr-Neutr0n
Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes a NameError: name 'TypeAdapter' is not defined error when importing transformers without pydantic installed.

Problem

The TypeAdapter class from pydantic was used as a type annotation in _validate_request() at line 588:

def _validate_request(
    self,
    request: dict,
    schema: TypedDict,
    validator: TypeAdapter,  # <-- NameError here
    unused_fields: set,
):

However, TypeAdapter is only imported inside an if serve_dependencies_available: block, which requires pydantic to be installed. When pydantic is not installed, Python raises NameError when parsing the class definition.

Solution

  1. Added TypeAdapter to the TYPE_CHECKING imports block
  2. Changed the type annotation to use a string literal "TypeAdapter" for forward reference

This ensures the type annotation is only evaluated during static type checking, not at runtime.

Fixes #43824

TypeAdapter was used as a type annotation at runtime, but it was only
imported inside an 'if serve_dependencies_available' block. This caused
NameError when pydantic is not installed.

Fix by adding TypeAdapter to TYPE_CHECKING imports and using a string
annotation for the type hint so it's only evaluated during type checking.

Fixes huggingface#43824
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.

ImportError: cannot import name 'Qwen2_5_VLForConditionalGeneration' from 'transformers'

2 participants