Skip to content

SetModelResponseTool crashes with TypeError when output_schema is a raw dict #5469

Closed

Description

@harche

Bug Description

When passing a raw dict schema as output_schema to an LlmAgent, the SetModelResponseTool crashes with TypeError: unhashable type: 'dict' during function declaration generation.

Steps to Reproduce

from google.adk.agents import Agent

agent = Agent(
    name="test",
    model="gemini-2.5-flash",
    instruction="You are a helpful agent.",
    output_schema={"type": "object", "properties": {"result": {"type": "string"}}},
)

Running a query with this agent produces:

TypeError: unhashable type: 'dict'

Root Cause

In src/google/adk/tools/set_model_response_tool.py, the else branch (lines 90-99) handles non-BaseModel, non-list schemas by setting annotation=output_schema — i.e., the dict instance itself:

else:
    params = [
        inspect.Parameter(
            'response',
            inspect.Parameter.KEYWORD_ONLY,
            annotation=output_schema,  # <-- dict INSTANCE, e.g. {"type": "object", ...}
        )
    ]

Later, in _function_parameter_parse_util.py line 140, _is_builtin_primitive_or_compound does:

return annotation in _py_builtin_type_to_schema_type.keys()

This calls __hash__ on the annotation, but dict instances aren't hashable, so it raises TypeError.

Expected Behavior

Raw dict schemas should work — SchemaType = types.SchemaUnion explicitly includes dict[Any, Any], and _schema_utils.py documents support for "Raw dict schemas".

Suggested Fix

Add an isinstance(output_schema, dict) branch in SetModelResponseTool.__init__ before the else fallthrough:

elif isinstance(output_schema, dict):
    params = [
        inspect.Parameter(
            'response',
            inspect.Parameter.KEYWORD_ONLY,
            annotation=dict,  # the TYPE, not the instance
        )
    ]

This way _is_builtin_primitive_or_compound sees dict (the type, which is hashable and already mapped to types.Type.OBJECT in _py_builtin_type_to_schema_type).

Full Stack Trace

File "google/adk/flows/llm_flows/_output_schema_processor.py", line 54, in run_async
    llm_request.append_tools([set_response_tool])
File "google/adk/models/llm_request.py", line 256, in append_tools
    declaration = tool._get_declaration()
File "google/adk/tools/set_model_response_tool.py", line 116, in _get_declaration
    build_function_declaration(
File "google/adk/tools/_automatic_function_calling_util.py", line 259, in build_function_declaration
    from_function_with_options(func, variant)
File "google/adk/tools/_automatic_function_calling_util.py", line 340, in from_function_with_options
    schema = _function_parameter_parse_util._parse_schema_from_parameter(
File "google/adk/tools/_function_parameter_parse_util.py", line 227, in _parse_schema_from_parameter
    if _is_builtin_primitive_or_compound(param.annotation):
File "google/adk/tools/_function_parameter_parse_util.py", line 140, in _is_builtin_primitive_or_compound
    return annotation in _py_builtin_type_to_schema_type.keys()
TypeError: unhashable type: 'dict'

Environment

  • google-adk version: 1.31.1
  • Python: 3.12

Activity

  1. added
    tools
    on Apr 24, 2026
  2. added theissue type on Apr 24, 2026
  3. added a commit that references this issue on Apr 24, 2026
    6e44f37
  4. AlejandroBlanco2001 commented on Apr 25, 2026

    @AlejandroBlanco2001

    Hey @harche, I hit the same confusion before. I think the current behavior is mostly a docs/wording mismatch: output_schema expects a schema specifier (e.g. Pydantic model type, types.Schema, or typing constructs), not a JSON-schema dict literal.

    A simple way to keep things structured without Pydantic is to use a TypedDict, e.g.:

    from typing_extensions import TypedDict
    
    class OutputSchema(TypedDict):
      result: str
    
    agent = Agent(
        name="test",
        model="gemini-2.5-flash",
        instruction="You are a helpful agent.",
        output_schema=OutputSchema,
    )

    I can help with updating the docs in the Python docs

  5. harche commented on Apr 26, 2026

    @harche
    Author

    Thanks @nichochar — the TypedDict approach doesn't work either unfortunately. ADK's fallback path in _function_parameter_parse_util calls pydantic.TypeAdapter(annotation, config=ConfigDict(arbitrary_types_allowed=True)), and Pydantic 2.13+ rejects the config parameter for TypedDict types:

    pydantic.errors.PydanticUserError: Cannot use `config` when the type is a BaseModel, dataclass or TypedDict.
    

    After digging deeper, the issue is more fundamental than the unhashable dict crash. SetModelResponseTool tries to represent the output schema as a function parameter annotation, which downstream code must parse back into a Gemini Schema. This round-trip breaks for:

    • Raw dicts — unhashable (the original crash)
    • TypedDict — Pydantic rejects config= on TypedDict types
    • Dynamic Pydantic models with nested types — generates $ref/$defs in JSON schema, which types.Schema.model_validate() rejects as extra inputs

    The workaround we landed on: bypass SetModelResponseTool entirely and set response_schema + response_mime_type directly on GenerateContentConfig after agent construction. This uses the Gemini API's native JSON schema enforcement, which handles raw dict schemas perfectly.

    agent = Agent(name="test", model="gemini-2.5-flash", tools=[...])
    
    # Set after construction to bypass the field validator
    agent.generate_content_config.response_mime_type = "application/json"
    agent.generate_content_config.response_schema = {
        "type": "object",
        "properties": {"result": {"type": "string"}},
        "required": ["result"],
    }

    The root cause is that can_use_output_schema_with_tools() only returns True for Vertex AI, so API-key users always get routed through SetModelResponseTool even though the Gemini API natively supports response_schema for all auth methods. Ideally ADK would use native response_schema on GenerateContentConfig for all Gemini models, not just Vertex AI.

  6. llalitkumarrr commented on Apr 27, 2026

    @llalitkumarrr
    Collaborator

    Hello @harche ,

    We attempted to reproduce this issue but it worked as expected. We used google-adk==1.31.1 and python==3.13.7 for the reproduction and utilized the exact same agent definition you provided. For your reference, here is the code we used:

    from google.adk.agents import Agent
    from google.adk.tools.google_search_tool import google_search
    
    agent = Agent(
        name="test",
        model="gemini-2.5-flash",
        instruction="You are a helpful agent.",
        output_schema={"type": "object", "properties": {"result": {"type": "string"}}},
    )
    
    root_agent = agent
    

    We ran this with adk web and observed the following:

    Image

    I hope we understood your issue correctly. If not could you please let us know if the issue is reproducible 100% of the time or if this error occurs only in specific cases? If it is the latter, please detail those specific cases.

  7. harche commented on Apr 28, 2026

    @harche
    Author

    Hello @harche ,

    We attempted to reproduce this issue but it worked as expected

    Thanks, I will test this again by end of this week after dealing with some higher priority items, thanks.

  8. harche commented on May 1, 2026

    @harche
    Author

    @llalitkumarrr The bug is reproducible 100% of the time. The crash doesn't happen at Agent() construction — it happens when SetModelResponseTool._get_declaration() is called during a query run. adk web may not exercise that path with a simple prompt.

    Here's a minimal reproduction that doesn't require any API keys or a running model:

    from google.adk.agents import Agent
    from google.adk.tools.set_model_response_tool import SetModelResponseTool
    
    schema = {"type": "object", "properties": {"result": {"type": "string"}}}
    
    # Construction works fine:
    agent = Agent(
        name="test",
        model="gemini-2.5-flash",
        instruction="You are a helpful agent.",
        output_schema=schema,
    )
    print(f"Agent created OK, output_schema type: {type(agent.output_schema)}")
    
    # The crash is here — this is what the agent calls internally during run:
    tool = SetModelResponseTool(output_schema=agent.output_schema)
    tool._get_declaration()  # TypeError: unhashable type: 'dict'

    Output on google-adk==1.31.1, Python 3.13.13:

    Agent created OK, output_schema type: <class 'dict'>
    Traceback (most recent call last):
      ...
      File ".../google/adk/tools/_function_parameter_parse_util.py", line 140, in _is_builtin_primitive_or_compound
        return annotation in _py_builtin_type_to_schema_type.keys()
    TypeError: unhashable type: 'dict'
    

    The root cause is in SetModelResponseTool.__init__ — the else branch sets annotation=output_schema (the dict instance), which later fails the in check against _py_builtin_type_to_schema_type.keys() because dict instances aren't hashable.

  9. llalitkumarrr commented on May 5, 2026

    @llalitkumarrr
    Collaborator

    Hello @harche ,

    There is a PR linked to this issue, could you please check whether it resolves the problem?
    Also, could you share specific cases where you invoked model with tool access and encountered this error? If possible, include your complete code along with the prompts you used. That will help us investigate and analyze the issue more effectively.

  10. harche commented on May 5, 2026

    @harche
    Author

    Thanks for looking into this. The linked PR fixes the crash by setting annotation=dict for raw dict schemas, but it loses the schema structure — the model only sees "a dict" as the type hint, with no enforcement of the actual schema shape.

    We ran into this in production and worked around it by bypassing SetModelResponseTool entirely and using Gemini's native response_schema on GenerateContentConfig:

    https://github.com/openshift/lightspeed-agentic-sandbox/blob/65420e154c2cc6d8d01ad1b2d6f0654dd6a8a019/src/lightspeed_agentic/providers/gemini.py#L118

    agent = Agent(name=..., model=..., instruction=..., tools=tools)
    
    if output_schema:
        gen_cfg = agent.generate_content_config
        gen_cfg.response_mime_type = "application/json"
        gen_cfg.response_schema = output_schema

    This gives hard schema enforcement at the API layer rather than relying on the model to voluntarily call a tool.

  11. llalitkumarrr commented on Jun 11, 2026

    @llalitkumarrr
    Collaborator

    Hello @harche ,

    Apologies for delayed response and thank you for sharing the update. Just to confirm, is this issue fixed with the work around you provided?

  12. added
    stale
    request clarification
    on Jun 22, 2026
  13. adk-bot commented on Jun 30, 2026

    @adk-bot
    Collaborator

    This has been automatically closed because it has been marked as stale for over 7 days.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

request clarificationstaletools

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions