|
| 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 | +from typing import Any |
| 16 | + |
| 17 | +from google.adk.agents import LlmAgent |
| 18 | +from google.adk.apps.app import App |
| 19 | +from google.adk.plugins import LoggingPlugin |
| 20 | +from google.adk.plugins import ReflectAndRetryToolPlugin |
| 21 | + |
| 22 | +APP_NAME = "basic" |
| 23 | +USER_ID = "test_user" |
| 24 | + |
| 25 | + |
| 26 | +def guess_number_tool(query: int) -> dict[str, Any]: |
| 27 | + """A tool that guesses a number. |
| 28 | +
|
| 29 | + Args: |
| 30 | + query: The number to guess. |
| 31 | +
|
| 32 | + Returns: |
| 33 | + A dictionary containing the status and result of the tool execution. |
| 34 | + """ |
| 35 | + target_number = 3 |
| 36 | + if query == target_number: |
| 37 | + return {"status": "success", "result": "Number is valid."} |
| 38 | + |
| 39 | + if abs(query - target_number) <= 2: |
| 40 | + return {"status": "error", "error_message": "Number is almost valid."} |
| 41 | + |
| 42 | + if query > target_number: |
| 43 | + raise ValueError("Number is too large.") |
| 44 | + |
| 45 | + if query < target_number: |
| 46 | + raise ValueError("Number is too small.") |
| 47 | + |
| 48 | + raise ValueError("Number is invalid.") |
| 49 | + |
| 50 | + |
| 51 | +class CustomRetryPlugin(ReflectAndRetryToolPlugin): |
| 52 | + |
| 53 | + async def extract_error_from_result( |
| 54 | + self, *, tool, tool_args, tool_context, result |
| 55 | + ): |
| 56 | + return result if result.get("status") == "error" else None |
| 57 | + |
| 58 | + |
| 59 | +root_agent = LlmAgent( |
| 60 | + name="hello_world", |
| 61 | + description="Helpful agent", |
| 62 | + instruction="""Use guess_number_tool to guess a number.""", |
| 63 | + model="gemini-2.5-flash", |
| 64 | + tools=[guess_number_tool], |
| 65 | +) |
| 66 | + |
| 67 | + |
| 68 | +app = App( |
| 69 | + name=APP_NAME, |
| 70 | + root_agent=root_agent, |
| 71 | + plugins=[ |
| 72 | + CustomRetryPlugin( |
| 73 | + max_retries=6, throw_exception_if_retry_exceeded=False |
| 74 | + ), |
| 75 | + LoggingPlugin(), |
| 76 | + ], |
| 77 | +) |
0 commit comments