autogen icon indicating copy to clipboard operation
autogen copied to clipboard

Error in LangChainToolAdapter GoogleDriveSearchTool: Unable to generate pydantic-core schema

Open dnascimento opened this issue 1 year ago • 8 comments

What happened?

Describe the bug The pytdantic-core schema seems to be failing with tools like GoogleDriveSearchTool. What am I missing here?

pydantic==2.10.6
pydantic-settings==2.8.1
pydantic_core==2.27.2
langchain==0.3.24
langchain-aws==0.2.18
langchain-community==0.3.22
langchain-core==0.3.55
langchain-experimental==0.3.4
langchain-text-splitters==0.3.8
autogen-agentchat==0.4.9.2
autogen-core==0.5.4
autogen-ext==0.5.4

ERROR:root:An error occurred: Unable to generate pydantic-core schema for <class 'langchain_core.callbacks.manager.CallbackManagerForToolRun'>. Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.

If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.

For further information visit https://errors.pydantic.dev/2.11/u/schema-for-unknown-type
Traceback (most recent call last):
  File "tests/tool_langchain.py", line 112, in <module>
    asyncio.run(main())
  File "/usr/lib/python3.12/asyncio/runners.py", line 194, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/asyncio/base_events.py", line 687, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "tests/tool_langchain.py", line 80, in main
    autogen_tool = LangChainToolAdapter(drive_tool)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/autogen_ext/tools/langchain/_langchain_adapter.py", line 175, in __init__
    args_type = create_model(f"{name}Args", **fields)  # type: ignore
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/main.py", line 1772, in create_model
    return meta(
           ^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_model_construction.py", line 237, in __new__
    complete_model_class(
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_model_construction.py", line 597, in complete_model_class
    schema = gen_schema.generate_schema(cls)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 706, in generate_schema
    schema = self._generate_schema_inner(obj)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 984, in _generate_schema_inner
    return self._model_schema(obj)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 817, in _model_schema
    {k: self._generate_md_field_schema(k, v, decorators) for k, v in fields.items()},
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 1186, in _generate_md_field_schema
    common_field = self._common_field_schema(name, field_info, decorators)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 1352, in _common_field_schema
    schema = self._apply_annotations(
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 2264, in _apply_annotations
    schema = get_inner_schema(source_type)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__
    schema = self._handler(source_type)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 2246, in inner_handler
    schema = self._generate_schema_inner(obj)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 989, in _generate_schema_inner
    return self.match_type(obj)
           ^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 1103, in match_type
    return self._match_generic_type(obj, origin)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 1126, in _match_generic_type
    return self._union_schema(obj)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 1414, in _union_schema
    choices.append(self.generate_schema(arg))
                   ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 706, in generate_schema
    schema = self._generate_schema_inner(obj)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 989, in _generate_schema_inner
    return self.match_type(obj)
           ^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 1107, in match_type
    return self._unknown_type_schema(obj)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py", line 634, in _unknown_type_schema
    raise PydanticSchemaGenerationError(
pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'langchain_core.callbacks.manager.CallbackManagerForToolRun'>. Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.

If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.

For further information visit https://errors.pydantic.dev/2.11/u/schema-for-unknown-type

To Reproduce

import asyncio
import os
from autogen_ext.tools.langchain import LangChainToolAdapter
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_agentchat.messages import TextMessage
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_core import CancellationToken
from google.oauth2 import service_account
from langchain_googledrive.tools.google_drive.tool import GoogleDriveSearchTool
from langchain_googledrive.utilities.google_drive import GoogleDriveAPIWrapper
import logging

async def main() -> None:
    # Step 1: Authenticate with service account
    SERVICE_ACCOUNT_FILE = "./service-account.json"
    SCOPES = ["https://www.googleapis.com/auth/drive.readonly"]

    try:
        credentials = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES
        )
        logging.info(f"Using service account: {credentials.service_account_email}")

        # Initialize Google Drive API wrapper
        folder_id = "root"
        drive_wrapper = GoogleDriveAPIWrapper(
            credentials=credentials,
            folder_id=folder_id,
            num_results=20,
            template="gdrive-query-in-folder",
            mode="documents-markdown"
        )
        
        # Create the Google Drive search tool
        drive_tool = GoogleDriveSearchTool(api_wrapper=drive_wrapper)

        print(drive_tool.invoke("my_docs"))
        
        # # Wrap the LangChain tool with Autogen adapter
        autogen_tool = LangChainToolAdapter(drive_tool)
        
        # Initialize the model client
        model_client = OpenAIChatCompletionClient(
            model="gpt-4",
            api_key=os.getenv("OPENAI_API_KEY"),
            model_config={"arbitrary_types_allowed": True}
        )
        
        # Create the assistant agent with the Google Drive tool
        agent = AssistantAgent(
            "assistant",
            tools=[autogen_tool],
            model_client=model_client,
            system_message="You can search for files in Google Drive using the provided tool."
        )
        
        await Console(
            agent.on_messages_stream(
                [TextMessage(content="Tell me about the user", source="user")],
                CancellationToken()
            )
        )

    except Exception as e:
        logging.error(f"An error occurred: {str(e)}")
        raise

if __name__ == "__main__":
    logging.info("Starting Google Drive search tool")
    asyncio.run(main())
    logging.info("Done")

Expected behavior A clear and concise description of what you expected to happen.

Screenshots If applicable, add screenshots to help explain your problem.

Additional context Add any other context about the problem here.

Which packages was the bug in?

Python Extensions (autogen-ext)

AutoGen library version.

Python 0.5.4

Other library version.

No response

Model used

gpt-4

Model provider

OpenAI

Other model provider

No response

Python version

3.12

.NET version

None

Operating system

Ubuntu

dnascimento avatar Apr 24 '25 09:04 dnascimento

Hi @dnascimento! Is this still open? If so,i would like to work on it,may i?

Tweezky66 avatar Jun 28 '26 12:06 Tweezky66

Root cause: when a LangChain tool has no explicit args_schema (true for GoogleDriveSearchTool), LangChainToolAdapter.__init__ falls back to inspect.signature(self._callable) on the tool's _run method and builds a pydantic model from every parameter it finds -- including run_manager: Optional[CallbackManagerForToolRun], which is the standard injected parameter on virtually every LangChain BaseTool._run override. pydantic.create_model() chokes on that type, which is exactly the schema error in your traceback. LangChain's own core (langchain_core/tools/base.py) has a constant, FILTERED_ARGS = ("run_manager", "callbacks"), specifically to strip these before building any args schema -- the adapter's fallback path just doesn't replicate that filter. The fix is small:

FILTERED_ARGS = ("run_manager", "callbacks")
fields = {
    k: (v.annotation, Field(...))
    for k, v in sig.parameters.items()
    if k not in ("self", *FILTERED_ARGS) and v.kind not in (...)
}

Until that lands, a workaround is wrapping the tool with an explicit args_schema yourself (or use Tool.from_function style construction) so the adapter takes the args_schema branch instead of the signature-inspection fallback.

ErenAta16 avatar Jul 12 '26 18:07 ErenAta16

Agentic systems are turning into always-on factories: one request fans out into model calls, tool calls, policy checks, and storage.

The hard part is rarely tokens/sec — it is control-plane reliability:

  1. Fan-out control — hard cap on tools/steps per request before external writes
  2. Durable id + idempotency — one write per business object (ledger / preflight)
  3. Observable long jobs — progress + cooperative cancel on multi-minute runs
  4. Expected vs actual — durable artifact id before marking success
  5. Policy before action — gate that can refuse known-bad side effects

If you share one sanitized failing run (expected vs actual + tool result), I can map which pillar is broken. Architecture only.

IgorGanapolsky avatar Jul 24 '26 18:07 IgorGanapolsky

Hi, I’d like to investigate the LangChainToolAdapter schema error. I can reproduce it with the Google Drive search tool, compare it with the other tool adapters, and add a focused test around the Pydantic schema generation before changing the adapter. Is this still open for an external contributor, or is someone already working on it?

Gambit-Checkmate avatar Aug 22 '26 04:08 Gambit-Checkmate

@Gambit-Checkmate sorry this sat for ten days. The answer to your question is yes, someone is working on it, and there is more than one of them, so it is worth knowing what is already there before you start.

Two PRs are open against this issue right now, both editing the same file:

#7808  tysoncung       07 Jun   +14/-1     no tests
#7994  godququ5-code   24 Jul   +176/-7    +110 of tests
        both: python/.../tools/langchain/_langchain_adapter.py, mergeable_state=blocked

Three more have already been closed (#6894, #7241, #8061), so this is the fourth and fifth attempt at the same fix rather than an untouched issue.

#7994 is the one I would read first. Its title is the diagnosis: skip the LangChain callback manager when inferring the args schema. That matches what I found in July, that with no explicit args_schema the adapter falls back to inspect.signature over _run and builds a pydantic model from every parameter, run_manager included, which is the one pydantic cannot generate a schema for. It also carries the tests, which #7808 does not.

Both sit at mergeable_state=blocked, so the thing standing between this issue and a fix is not another implementation. It is that nobody has reviewed the two that exist.

If you want to be useful here, and I think you genuinely can be, the highest-value version of what you offered is the reproduction plus the review rather than a sixth branch. You said you can reproduce it with the Google Drive search tool and compare against the other adapters. Doing exactly that against #7994's head, and saying whether it fixes your reproduction and whether its handling matches the sibling adapters, is the thing neither PR has and the thing a maintainer would need before merging either.

I have no standing to assign anything here, to be clear. This is just what the tracker says today.

ErenAta16 avatar Sep 01 '26 07:09 ErenAta16

I'd like to take this one — I'll follow up with a PR. (claiming via @LeonxLJX)

LeonxLJX avatar Sep 01 '26 08:09 LeonxLJX

Hi! I'd like to fix the GoogleDriveSearchTool generation error. Plan: reproduce, fix, add a test. May I be assigned?

LeonxLJX avatar Sep 01 '26 10:09 LeonxLJX

@LeonxLJX before you start: the implementation exists twice already, so a third one would not move this.

#7994  godququ5-code   skips the callback manager in the inspect.signature fallback
#7808  tysoncung       rebuilds the model from tool.args in the args_schema branch

Both are open and both sit at mergeable_state=blocked. They are not duplicates of each other, which took me a while to work out: they patch the two different branches of the same if self._langchain_tool.args_schema: in _langchain_adapter.py. GoogleDriveSearchTool declares no args_schema, so it takes the else branch, which means #7994 is the one that fixes this issue and #7808 covers a case this issue does not reach.

What actually moved it was not more code. @z2Ace0107 reproduced the failure with langchain-googledrive on main, confirmed it is gone on #7994's head, and ran the focused tests. That is the contribution this issue was short of, and it is still short of one for #7808.

So if you want to spend the time here, the two useful things are reproducing against #7808's head to confirm its branch behaves, or reviewing either diff. I said the same to @Gambit-Checkmate on 1 September a couple of hours before your comment, so you may simply not have seen it rather than disagreed with it.

ErenAta16 avatar Sep 11 '26 07:09 ErenAta16