adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

pydantic.errors.PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for core_schema.IsInstanceSchema (<class 'httpx.Client'>)

Open diefergil opened this issue 1 year ago • 12 comments

** Please make sure you read the contribution guide and file the issues in the right place. ** Contribution guide.

Describe the bug uv run adk api_server is not rendering the /docs

For further information visit https://errors.pydantic.dev/2.12/u/invalid-for-json-schema`

To Reproduce Please share a minimal code and data to reproduce your problem. Steps to reproduce the behavior: 2. Run 'uv run adk api_server' 3. Open 'http://localhost:8000/docs' 4. Provie error or stacktrace 5.

raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}')
pydantic.errors.PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for core_schema.IsInstanceSchema (<class 'httpx.Client'>)

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

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

Desktop (please complete the following information):

  • OS: mac os
  • Python version(python -V): 3.12
  • ADK version(pip show google-adk):
pip list                                                                                                                                                                                                                   $(/opt/homebrew/bin/starship prompt --right --terminal-width="$COLUMNS" --keymap="${KEYMAP:-}" --status="$STARSHIP_CMD_STATUS" --pipestatus="${STARSHIP_PIPE_STATUS[*]}" --cmd-duration="${STARSHIP_DURATION:-}" --jobs="$STARSHIP_JOBS_COUNT")
Package                                    Version     Editable project location
------------------------------------------ ----------- --------------------------------------------------------
absolufy-imports                           0.3.1
ag-ui-adk                                  0.3.1
ag-ui-protocol                             0.1.9
aiohappyeyeballs                           2.6.1
aiohttp                                    3.13.1
aiosignal                                  1.4.0
alembic                                    1.17.0
annotated-types                            0.7.0
anyio                                      4.11.0
asyncio                                    4.0.0
attrs                                      25.4.0
Authlib                                    1.6.5
cachetools                                 6.2.1
certifi                                    2025.10.5
cffi                                       2.0.0
charset-normalizer                         3.4.4
click                                      8.3.0
cloudpickle                                3.1.1
cryptography                               46.0.3
distro                                     1.9.0
docstring_parser                           0.17.0
fastapi                                    0.118.3
fastuuid                                   0.14.0
filelock                                   3.20.0
frozenlist                                 1.8.0
fsspec                                     2025.9.0
google-adk                                 1.17.0
google-api-core                            2.28.0
google-api-python-client                   2.185.0
google-auth                                2.41.1
google-auth-httplib2                       0.2.0
google-cloud-aiplatform                    1.122.0
google-cloud-appengine-logging             1.7.0
google-cloud-audit-log                     0.4.0
google-cloud-bigquery                      3.38.0
google-cloud-bigtable                      2.34.0
google-cloud-core                          2.4.3
google-cloud-discoveryengine               0.13.12
google-cloud-logging                       3.12.1
google-cloud-monitoring                    2.28.0
google-cloud-resource-manager              1.15.0
google-cloud-secret-manager                2.25.0
google-cloud-spanner                       3.59.0
google-cloud-speech                        2.34.0
google-cloud-storage                       2.19.0
google-cloud-trace                         1.17.0
google-crc32c                              1.7.1
google-genai                               1.46.0
google-resumable-media                     2.7.2
googleapis-common-protos                   1.71.0
graphviz                                   0.21
grpc-google-iam-v1                         0.14.3
grpc-interceptor                           0.15.4
grpcio                                     1.76.0
grpcio-status                              1.76.0
h11                                        0.16.0
hf-xet                                     1.2.0
httpcore                                   1.0.9
httplib2                                   0.31.0
httpx                                      0.28.1
httpx-sse                                  0.4.3
huggingface-hub                            1.0.1
idna                                       3.11
importlib_metadata                         8.7.0
jaraco.classes                             3.4.0
jaraco.context                             6.0.1
jaraco.functools                           4.3.0
Jinja2                                     3.1.6
jiter                                      0.11.1
joblib                                     1.5.2
jsonschema                                 4.25.1
jsonschema-specifications                  2025.9.1
keyring                                    25.6.0
keyrings.google-artifactregistry-auth      1.1.2
litellm                                    1.76.3
Mako                                       1.3.10
MarkupSafe                                 3.0.3
mcp                                        1.19.0
more-itertools                             10.8.0
multidict                                  6.7.0
numpy                                      2.3.4
openai                                     2.6.1
opentelemetry-api                          1.37.0
opentelemetry-exporter-gcp-logging         1.10.0a0
opentelemetry-exporter-gcp-monitoring      1.10.0a0
opentelemetry-exporter-gcp-trace           1.10.0
opentelemetry-exporter-otlp-proto-common   1.37.0
opentelemetry-exporter-otlp-proto-http     1.37.0
opentelemetry-instrumentation              0.58b0
opentelemetry-instrumentation-google-genai 0.4b0
opentelemetry-proto                        1.37.0
opentelemetry-resourcedetector-gcp         1.10.0a0
opentelemetry-sdk                          1.37.0
opentelemetry-semantic-conventions         0.58b0
opentelemetry-util-genai                   0.2b0
packaging                                  25.0
pandas                                     2.3.3
pip                                        24.2
pluggy                                     1.6.0
propcache                                  0.4.1
proto-plus                                 1.26.1
protobuf                                   6.33.0
pyasn1                                     0.6.1
pyasn1_modules                             0.4.2
pycparser                                  2.23
pydantic                                   2.12.3
pydantic_core                              2.41.4
pydantic-settings                          2.11.0
pyparsing                                  3.2.5
python-dateutil                            2.9.0.post0
python-dotenv                              1.2.1
python-multipart                           0.0.20
pytz                                       2025.2
PyYAML                                     6.0.3
referencing                                0.37.0
regex                                      2025.10.23
requests                                   2.32.5
rpds-py                                    0.28.0
rsa                                        4.9.1
ruamel.yaml                                0.18.16
ruamel.yaml.clib                           0.2.14
scikit-learn                               1.7.2
scipy                                      1.16.2
shapely                                    2.1.2
shellingham                                1.5.4
six                                        1.17.0
sniffio                                    1.3.1
SQLAlchemy                                 2.0.44
sqlalchemy-spanner                         1.17.1
sqlparse                                   0.5.3
sse-starlette                              3.0.2
starlette                                  0.48.0
tenacity                                   8.5.0
threadpoolctl                              3.6.0
tiktoken                                   0.12.0
tokenizers                                 0.22.1
tqdm                                       4.67.1
typer-slim                                 0.20.0
typing_extensions                          4.15.0
typing-inspection                          0.4.2
tzdata                                     2025.2
tzlocal                                    5.3.1
uritemplate                                4.2.0
urllib3                                    2.5.0
uvicorn                                    0.38.0
watchdog                                   6.0.0
websockets                                 15.0.1
wrapt                                      1.17.3
yarl                                       1.22.0
zipp                                       3.23.0

Model Information:

  • Are you using LiteLLM: No
  • Which model is being used(e.g. gemini-2.5-pro)

Additional context Add any other context about the problem here.

diefergil avatar Oct 28 '25 16:10 diefergil

I'm encountering the same issue. I thought it might be related to the Pydantic version which could have been recently upgraded on my machine. I tried to revert to pydantic==2.11.1 and pydantic==2.11.10. Neither worked.

We're installing ADK this way google-cloud-aiplatform[agent_engines,adk,langchain,ag2,llama_index,evaluation]==1.120.0, and I believe this install requires pydantic>=2.11.1. Therefore, we probably can't revert to early versions of Pydantic.

Bottom line: reverting to an earlier Pydantic Version is unlikely to fix the issue.

Numantic-SGodfrey avatar Oct 28 '25 16:10 Numantic-SGodfrey

@diefergil It looks like you're running into a Pydantic schema error with httpx.Client. The best way to resolve this is to use FastAPI's dependency injection to manage the client instead of including it in your Pydantic model. This should fix the schema generation issue you're seeing. Lmk if you have any other questions. Thanks!

surajksharma07 avatar Oct 29 '25 18:10 surajksharma07

@surajksharma07 Could you please provide a little more detail on your suggested solution? I believe I'm encountering the same issue and the httpx.Client is not in my code.

I do use Pydantic in some agents. However, I encountered the same issue when I isolated agents and tried to use adk api_server to test them locally. In other words, I think this is happening with ADK agents that don't use Pydantic at the top level.

I'm not sure what coding changes to make. If helpful, I can supply code.

Thanks

Numantic-SGodfrey avatar Oct 29 '25 19:10 Numantic-SGodfrey

@Numantic-SGodfrey To help us find that exact location in the ADK, it would be incredibly helpful if you could provide a minimal reproducible example of an agent that triggers this error.

surajksharma07 avatar Oct 29 '25 20:10 surajksharma07

@surajksharma07 the starter example,

from google.adk.agents.llm_agent import Agent

# Mock tool implementation
def get_current_time(city: str) -> dict:
    """Returns the current time in a specified city."""
    return {"status": "success", "city": city, "time": "10:30 AM"}

root_agent = Agent(
    model='gemini-2.5-flash',
    name='root_agent',
    description="Tells the current time in a specified city.",
    instruction="You are a helpful assistant that tells the current time in cities. Use the 'get_current_time' tool for this purpose.",
    tools=[get_current_time],
)

diefergil avatar Oct 29 '25 21:10 diefergil

Here is the issue that I see. Note these are screenshots of my code (not @diefergil example) and this may or may not be the issue experienced by others.

  1. My agents work fine when run from the local agent UI (adk web).
  2. I can call my agents from the local FastAPI api server.
  3. I get an error trying to load the docs from the local FastAPI server (\docs).
Image Image Image

Numantic-SGodfrey avatar Oct 29 '25 21:10 Numantic-SGodfrey

@hangfei Please take a look into it.

surajksharma07 avatar Oct 30 '25 17:10 surajksharma07

Same here – ADK 1.18.0 still pulls httpx.Client into the OpenAPI schema via GenerateContentConfig.tools, so FastAPI crashes until we override app.openapi.

sipos-zoli avatar Nov 11 '25 07:11 sipos-zoli

This happens because GenerateContentConfig contains httpx.Client fields that Pydantic can't serialize to JSON Schema. PR #3521 addresses this and should land soon.

As a workaround until then, override app.openapi in your FastAPI app to catch the schema generation error and return a simplified schema - this will get your /docs endpoint working again.

surajksharma07 avatar Nov 23 '25 18:11 surajksharma07

Example override:


from fastapi.openapi.utils import get_openapi
import pydantic.json_schema as pjs
import httpx

app: FastAPI = get_fast_api_app(....)

def make_openapi(app):
    def new_openapi():
        if app.openapi_schema:
            return app.openapi_schema

        original_is_instance_schema = pjs.GenerateJsonSchema.is_instance_schema

        def patched_is_instance_schema(self, schema):
            if isinstance(schema, dict) and schema.get("cls") is httpx.Client:
                return {}
            if isinstance(schema, dict) and schema.get("cls") is httpx.AsyncClient:
                return {}
            return original_is_instance_schema(self, schema)

        pjs.GenerateJsonSchema.is_instance_schema = patched_is_instance_schema
        try:
            app.openapi_schema = get_openapi(
                title=app.title,
                version=app.version,
                openapi_version=app.openapi_version,
                summary=app.summary,
                description=app.description,
                terms_of_service=app.terms_of_service,
                contact=app.contact,
                license_info=app.license_info,
                routes=app.routes,
                webhooks=app.webhooks.routes,
                tags=app.openapi_tags,
                servers=app.servers,
                separate_input_output_schemas=False,
            )
        finally:
            pjs.GenerateJsonSchema.is_instance_schema = original_is_instance_schema

        return app.openapi_schema

    return new_openapi

app.openapi = make_openapi(app)

c-lgrant avatar Nov 24 '25 17:11 c-lgrant

Thanks @c-lgrant for the detailed workaround! The Pydantic patching approach you've shared is solid and should help others hit by this issue.

Just to confirm - PR #3521 addresses this upstream by excluding httpx clients from schema generation, so once that's merged this workaround won't be needed. Appreciate you taking the time to document the temporary fix!

surajksharma07 avatar Nov 24 '25 17:11 surajksharma07

your workaround is excellent and imho is a good approach as it also keeps most of the schema intact which unfortunately gets lost in the PR #3521. Very appreciative of your work - thank you

pfrantz avatar Dec 04 '25 22:12 pfrantz