|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Tool for setting model response when using output_schema with other tools.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from typing import Any |
| 20 | +from typing import Optional |
| 21 | + |
| 22 | +from google.genai import types |
| 23 | +from pydantic import BaseModel |
| 24 | +from typing_extensions import override |
| 25 | + |
| 26 | +from ._automatic_function_calling_util import build_function_declaration |
| 27 | +from .base_tool import BaseTool |
| 28 | +from .tool_context import ToolContext |
| 29 | + |
| 30 | +MODEL_JSON_RESPONSE_KEY = 'temp:__adk_model_response__' |
| 31 | + |
| 32 | + |
| 33 | +class SetModelResponseTool(BaseTool): |
| 34 | + """Internal tool used for output schema workaround. |
| 35 | +
|
| 36 | + This tool allows the model to set its final response when output_schema |
| 37 | + is configured alongside other tools. The model should use this tool to |
| 38 | + provide its final structured response instead of outputting text directly. |
| 39 | + """ |
| 40 | + |
| 41 | + def __init__(self, output_schema: type[BaseModel]): |
| 42 | + """Initialize the tool with the expected output schema. |
| 43 | +
|
| 44 | + Args: |
| 45 | + output_schema: The pydantic model class defining the expected output |
| 46 | + structure. |
| 47 | + """ |
| 48 | + self.output_schema = output_schema |
| 49 | + |
| 50 | + # Create a function that matches the output schema |
| 51 | + def set_model_response() -> str: |
| 52 | + """Set your final response using the required output schema. |
| 53 | +
|
| 54 | + Use this tool to provide your final structured answer instead |
| 55 | + of outputting text directly. |
| 56 | + """ |
| 57 | + return 'Response set successfully.' |
| 58 | + |
| 59 | + # Add the schema fields as parameters to the function dynamically |
| 60 | + import inspect |
| 61 | + |
| 62 | + schema_fields = output_schema.model_fields |
| 63 | + params = [] |
| 64 | + for field_name, field_info in schema_fields.items(): |
| 65 | + param = inspect.Parameter( |
| 66 | + field_name, |
| 67 | + inspect.Parameter.KEYWORD_ONLY, |
| 68 | + annotation=field_info.annotation, |
| 69 | + ) |
| 70 | + params.append(param) |
| 71 | + |
| 72 | + # Create new signature with schema parameters |
| 73 | + new_sig = inspect.Signature(parameters=params) |
| 74 | + setattr(set_model_response, '__signature__', new_sig) |
| 75 | + |
| 76 | + self.func = set_model_response |
| 77 | + |
| 78 | + super().__init__( |
| 79 | + name=self.func.__name__, |
| 80 | + description=self.func.__doc__.strip() if self.func.__doc__ else '', |
| 81 | + ) |
| 82 | + |
| 83 | + @override |
| 84 | + def _get_declaration(self) -> Optional[types.FunctionDeclaration]: |
| 85 | + """Gets the OpenAPI specification of this tool.""" |
| 86 | + function_decl = types.FunctionDeclaration.model_validate( |
| 87 | + build_function_declaration( |
| 88 | + func=self.func, |
| 89 | + ignore_params=[], |
| 90 | + variant=self._api_variant, |
| 91 | + ) |
| 92 | + ) |
| 93 | + return function_decl |
| 94 | + |
| 95 | + @override |
| 96 | + async def run_async( |
| 97 | + self, *, args: dict[str, Any], tool_context: ToolContext # pylint: disable=unused-argument |
| 98 | + ) -> dict[str, Any]: |
| 99 | + """Process the model's response and return the validated dict. |
| 100 | +
|
| 101 | + Args: |
| 102 | + args: The structured response data matching the output schema. |
| 103 | + tool_context: Tool execution context. |
| 104 | +
|
| 105 | + Returns: |
| 106 | + The validated response as dict. |
| 107 | + """ |
| 108 | + # Validate the input matches the expected schema |
| 109 | + validated_response = self.output_schema.model_validate(args) |
| 110 | + |
| 111 | + # Return the validated dict directly |
| 112 | + return validated_response.model_dump() |
0 commit comments