microsoft/autogen · error · ValueError

Failed to create a valid Pydantic v2 model for {name}

Error message

Failed to create a valid Pydantic v2 model for {name}

What it means

After resolving args_schema (either the tool's own or one synthesized via create_model), LangChainToolAdapter requires it to be a Pydantic v2 BaseModel subclass. Pydantic v1 model classes or non-model classes (dataclasses, TypedDict) fail issubclass() and raise ValueError. The adapter's run() relies on v2 model_dump(), so v1 schemas cannot work.

Source

Thrown at python/packages/autogen-ext/src/autogen_ext/tools/langchain/_langchain_adapter.py:179

            )

        # Determine args_type
        if self._langchain_tool.args_schema:  # pyright: ignore
            args_type = self._langchain_tool.args_schema  # pyright: ignore
        else:
            # Infer args_type from the callable's signature
            sig = inspect.signature(cast(Callable[..., Any], self._callable))  # type: ignore
            fields = {
                k: (v.annotation, Field(...))
                for k, v in sig.parameters.items()
                if k != "self" and v.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
            }
            args_type = create_model(f"{name}Args", **fields)  # type: ignore
            # Note: type ignore is used due to a LangChain typing limitation

        # Ensure args_type is a subclass of BaseModel
        if not issubclass(args_type, BaseModel):
            raise ValueError(f"Failed to create a valid Pydantic v2 model for {name}")

        # Assume return_type as Any if not specified
        return_type: Type[Any] = object

        super().__init__(args_type, return_type, name, description)

    async def run(self, args: BaseModel, cancellation_token: CancellationToken) -> Any:
        # Prepare arguments
        kwargs = args.model_dump()

        # Determine if the callable is asynchronous
        if inspect.iscoroutinefunction(self._callable):
            return await self._callable(**kwargs)
        else:
            # Run in a thread to avoid blocking the event loop
            return await asyncio.to_thread(self._call_sync, kwargs)

    def _call_sync(self, kwargs: Dict[str, Any]) -> Any:

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Rebuild the tool's args_schema as a Pydantic v2 model (from pydantic import BaseModel) and recreate the tool with @tool or StructuredTool.from_function.
  2. Re-register the legacy function through a fresh @tool decorator so a v2 schema is auto-generated from the signature.
  3. Upgrade langchain/langchain-core to a release that uses pydantic v2 schemas natively.
  4. Ensure only pydantic v2 is imported in your tool definition module (watch for 'from pydantic.v1 import BaseModel' imports).

Example fix

# before
from pydantic.v1 import BaseModel as V1BaseModel

class FetchArgs(V1BaseModel):
    q: str

fetch = StructuredTool(name="fetch", func=do_fetch, args_schema=FetchArgs)

# after
from pydantic import BaseModel, Field

class FetchArgs(BaseModel):
    q: str = Field(description="query")

fetch = StructuredTool.from_function(func=do_fetch, args_schema=FetchArgs)
Defensive patterns

Strategy: type-guard

Validate before calling

from pydantic import BaseModel

schema = getattr(tool, "args_schema", None)
if schema is not None and not (isinstance(schema, type) and issubclass(schema, BaseModel)):
    raise TypeError("args_schema must be a pydantic v2 BaseModel; rebuild the tool with @tool")

Type guard

from pydantic import BaseModel
from typing import Any, TypeGuard

def is_pydantic_v2_schema(schema: Any) -> TypeGuard[type[BaseModel]]:
    return isinstance(schema, type) and issubclass(schema, BaseModel)

Try / catch

try:
    adapter = LangChainToolAdapter(tool)
except ValueError as e:
    if "valid Pydantic v2 model" in str(e):
        raise TypeError("Rebuild the tool with a pydantic v2 args_schema") from e
    raise

Prevention

When it happens

Trigger: Wrapping a LangChain tool whose args_schema is a pydantic.v1.BaseModel (common with langchain<0.1 era tools or langchain_community tools still on v1), a dataclass, or a TypedDict. The issubclass(args_type, BaseModel) check fails and the error names the tool.

Common situations: Mixing old langchain-community tools (pydantic v1 schemas) with modern autogen-ext; having pydantic v1 installed alongside v2 via langchain's compat shim; a tool that sets args_schema to a plain class for documentation purposes.

Related errors


AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15). Data as JSON: /api/errors/2254751114d339d1. Report an issue: GitHub.