chore: import upstream snapshot with attribution
Continuous Integration / Pre-commit Linter (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.10) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.11) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.12) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.13) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.10) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.11) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.12) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.13) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.14) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Waiting to run
Copybara PR Handler / close-imported-pr (push) Waiting to run
Continuous Integration / Pre-commit Linter (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.10) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.11) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.12) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.13) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.10) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.11) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.12) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.13) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.14) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Waiting to run
Copybara PR Handler / close-imported-pr (push) Waiting to run
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
# Callback Sample
|
||||
|
||||
## Overview
|
||||
|
||||
This sample demonstrates how to use callbacks in ADK to intercept and handle events. Specifically, it shows:
|
||||
|
||||
1. **`before_tool_callback`**: Intercepts tool calls and conditionally short-circuits them.
|
||||
1. **`before_model_callback`**: Intercepts requests to the LLM and conditionally short-circuits them.
|
||||
1. **`after_model_callback`**: Runs after the model completes, allowing you to inspect or modify the response (e.g., appending token usage).
|
||||
|
||||
## Sample Inputs
|
||||
|
||||
- `What is the weather in Paris?`
|
||||
|
||||
*Calls the tool normally*
|
||||
|
||||
- `What is the weather in London?`
|
||||
|
||||
*Intercepted by the before_tool_callback and returns a mock response*
|
||||
|
||||
- `Hi`
|
||||
|
||||
*Intercepted by the before_model_callback and returns a direct response*
|
||||
|
||||
## How To
|
||||
|
||||
### Tool Callback
|
||||
|
||||
The sample defines a `before_tool_callback` function:
|
||||
|
||||
```python
|
||||
def before_tool_callback(
|
||||
tool: BaseTool,
|
||||
args: dict[str, Any],
|
||||
tool_context: ToolContext,
|
||||
) -> dict[str, Any] | None:
|
||||
# Intercept tool calls for London and return a mocked response
|
||||
if args.get("city") == "London":
|
||||
return {
|
||||
"result": "Weather in London is always rainy (intercepted by callback)."
|
||||
}
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
If the function returns a dictionary with a `result` key (or any other response data), ADK uses that as the tool output and skips calling the actual tool.
|
||||
|
||||
### Model Callback
|
||||
|
||||
The sample also defines a `before_model_callback` function:
|
||||
|
||||
```python
|
||||
def before_model_callback(
|
||||
callback_context: CallbackContext,
|
||||
llm_request: LlmRequest,
|
||||
) -> LlmResponse | None:
|
||||
# Short-circuit if the user simply says "Hi"
|
||||
if llm_request.contents:
|
||||
last_content = llm_request.contents[-1]
|
||||
if last_content.parts:
|
||||
last_part = last_content.parts[-1]
|
||||
if last_part.text and last_part.text.strip().lower() == "hi":
|
||||
return LlmResponse(
|
||||
content=types.Content(
|
||||
role="model",
|
||||
parts=[
|
||||
types.Part.from_text(
|
||||
text="Hello from before_model callback!"
|
||||
)
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
If this function returns an `LlmResponse`, ADK skips calling the LLM and returns this response to the user.
|
||||
|
||||
### After Model Callback
|
||||
|
||||
The sample also defines an `after_model_callback` function:
|
||||
|
||||
```python
|
||||
def after_model_callback(
|
||||
callback_context: CallbackContext,
|
||||
llm_response: LlmResponse,
|
||||
) -> LlmResponse:
|
||||
# Append token usage to the response text if available
|
||||
if llm_response.usage_metadata:
|
||||
usage = llm_response.usage_metadata
|
||||
usage_text = f"\n\nafter_model_callback: [Token Usage: Input={usage.prompt_token_count}, Output={usage.candidates_token_count}]"
|
||||
|
||||
if not llm_response.content:
|
||||
llm_response.content = types.Content(role="model", parts=[])
|
||||
|
||||
llm_response.content.parts.append(types.Part.from_text(text=usage_text))
|
||||
|
||||
return llm_response
|
||||
|
||||
```
|
||||
|
||||
This callback runs after the LLM returns a response. It checks if `usage_metadata` is available in the `llm_response`, constructs a string with input and output token counts, and appends it as a new part to the content.
|
||||
|
||||
All callbacks are registered in the `Agent` constructor:
|
||||
|
||||
```python
|
||||
root_agent = Agent(
|
||||
name="callback_demo_agent",
|
||||
tools=[get_weather],
|
||||
before_tool_callback=before_tool_callback,
|
||||
before_model_callback=before_model_callback,
|
||||
after_model_callback=after_model_callback,
|
||||
)
|
||||
```
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,118 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from google.adk.agents import Agent
|
||||
from google.adk.agents.callback_context import CallbackContext
|
||||
from google.adk.models.llm_request import LlmRequest
|
||||
from google.adk.models.llm_response import LlmResponse
|
||||
from google.adk.tools import BaseTool
|
||||
from google.adk.tools import ToolContext
|
||||
from google.genai import types
|
||||
|
||||
|
||||
def get_weather(city: str) -> str:
|
||||
return f"The weather in {city} is sunny."
|
||||
|
||||
|
||||
def before_tool_callback(
|
||||
tool: BaseTool,
|
||||
args: dict[str, Any],
|
||||
tool_context: ToolContext,
|
||||
) -> dict[str, Any] | None:
|
||||
"""A callback that runs before a tool is called.
|
||||
|
||||
Args:
|
||||
tool: The tool instance being called.
|
||||
args: The arguments passed to the tool.
|
||||
tool_context: The context for the tool execution.
|
||||
|
||||
Returns:
|
||||
A dict containing the mock response if the call should be short-circuited,
|
||||
or None to proceed with the actual tool call.
|
||||
"""
|
||||
# Intercept tool calls for London and return a mocked response
|
||||
if args.get("city") == "London":
|
||||
return {
|
||||
"result": "Weather in London is always rainy (intercepted by callback)."
|
||||
}
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def before_model_callback(
|
||||
callback_context: CallbackContext,
|
||||
llm_request: LlmRequest,
|
||||
) -> LlmResponse | None:
|
||||
"""A callback that runs before the model is called.
|
||||
|
||||
Args:
|
||||
callback_context: The context for the callback.
|
||||
llm_request: The request that is about to be sent to the model.
|
||||
|
||||
Returns:
|
||||
An LlmResponse to short-circuit the model call, or None to proceed.
|
||||
"""
|
||||
# Short-circuit if the user simply says "Hi"
|
||||
if llm_request.contents:
|
||||
last_content = llm_request.contents[-1]
|
||||
if last_content.parts:
|
||||
last_part = last_content.parts[-1]
|
||||
if last_part.text and last_part.text.strip().lower() == "hi":
|
||||
return LlmResponse(
|
||||
content=types.Content(
|
||||
role="model",
|
||||
parts=[
|
||||
types.Part.from_text(
|
||||
text="Hello from before_model callback!"
|
||||
)
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def after_model_callback(
|
||||
callback_context: CallbackContext,
|
||||
llm_response: LlmResponse,
|
||||
) -> LlmResponse:
|
||||
"""A callback that runs after the model is called."""
|
||||
if llm_response.usage_metadata:
|
||||
usage = llm_response.usage_metadata
|
||||
usage_text = (
|
||||
"\n\nafter_model_callback: [Token Usage:"
|
||||
f" Input={usage.prompt_token_count},"
|
||||
f" Output={usage.candidates_token_count}]"
|
||||
)
|
||||
|
||||
if not llm_response.content:
|
||||
llm_response.content = types.Content(role="model", parts=[])
|
||||
|
||||
llm_response.content.parts.append(types.Part.from_text(text=usage_text))
|
||||
print(llm_response.content)
|
||||
|
||||
return llm_response
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name="callback_demo_agent",
|
||||
tools=[get_weather],
|
||||
before_tool_callback=before_tool_callback,
|
||||
before_model_callback=before_model_callback,
|
||||
after_model_callback=after_model_callback,
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"events": [
|
||||
{
|
||||
"author": "user",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"text": "Hi"
|
||||
}
|
||||
],
|
||||
"role": "user"
|
||||
},
|
||||
"id": "e-1",
|
||||
"invocationId": "i-1",
|
||||
"nodeInfo": {
|
||||
"path": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"author": "callback_demo_agent",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"text": "Hello from before_model callback!"
|
||||
}
|
||||
],
|
||||
"role": "model"
|
||||
},
|
||||
"id": "e-2",
|
||||
"invocationId": "i-1",
|
||||
"nodeInfo": {
|
||||
"path": "callback_demo_agent@1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"events": [
|
||||
{
|
||||
"author": "user",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"text": "weather in London"
|
||||
}
|
||||
],
|
||||
"role": "user"
|
||||
},
|
||||
"id": "e-1",
|
||||
"invocationId": "i-1",
|
||||
"nodeInfo": {
|
||||
"path": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"author": "callback_demo_agent",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"functionCall": {
|
||||
"args": {
|
||||
"city": "London"
|
||||
},
|
||||
"id": "fc-1",
|
||||
"name": "get_weather"
|
||||
}
|
||||
},
|
||||
{
|
||||
"text": "\n\nafter_model_callback: [Token Usage: Input=22, Output=5]"
|
||||
}
|
||||
],
|
||||
"role": "model"
|
||||
},
|
||||
"finishReason": "STOP",
|
||||
"id": "e-2",
|
||||
"invocationId": "i-1",
|
||||
"longRunningToolIds": [],
|
||||
"nodeInfo": {
|
||||
"path": "callback_demo_agent@1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"author": "callback_demo_agent",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"functionResponse": {
|
||||
"id": "fc-1",
|
||||
"name": "get_weather",
|
||||
"response": {
|
||||
"result": "Weather in London is always rainy (intercepted by callback)."
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"role": "user"
|
||||
},
|
||||
"id": "e-3",
|
||||
"invocationId": "i-1",
|
||||
"nodeInfo": {
|
||||
"path": "callback_demo_agent@1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"author": "callback_demo_agent",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"text": "The weather in London is always rainy (intercepted by callback)."
|
||||
},
|
||||
{
|
||||
"text": "\n\nafter_model_callback: [Token Usage: Input=133, Output=13]"
|
||||
}
|
||||
],
|
||||
"role": "model"
|
||||
},
|
||||
"finishReason": "STOP",
|
||||
"id": "e-4",
|
||||
"invocationId": "i-1",
|
||||
"nodeInfo": {
|
||||
"path": "callback_demo_agent@1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"events": [
|
||||
{
|
||||
"author": "user",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"text": "weather in Sunnyvale"
|
||||
}
|
||||
],
|
||||
"role": "user"
|
||||
},
|
||||
"id": "e-1",
|
||||
"invocationId": "i-1",
|
||||
"nodeInfo": {
|
||||
"path": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"author": "callback_demo_agent",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"functionCall": {
|
||||
"args": {
|
||||
"city": "Sunnyvale"
|
||||
},
|
||||
"id": "fc-1",
|
||||
"name": "get_weather"
|
||||
}
|
||||
},
|
||||
{
|
||||
"text": "\n\nafter_model_callback: [Token Usage: Input=23, Output=6]"
|
||||
}
|
||||
],
|
||||
"role": "model"
|
||||
},
|
||||
"finishReason": "STOP",
|
||||
"id": "e-2",
|
||||
"invocationId": "i-1",
|
||||
"longRunningToolIds": [],
|
||||
"nodeInfo": {
|
||||
"path": "callback_demo_agent@1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"author": "callback_demo_agent",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"functionResponse": {
|
||||
"id": "fc-1",
|
||||
"name": "get_weather",
|
||||
"response": {
|
||||
"result": "The weather in Sunnyvale is sunny."
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"role": "user"
|
||||
},
|
||||
"id": "e-3",
|
||||
"invocationId": "i-1",
|
||||
"nodeInfo": {
|
||||
"path": "callback_demo_agent@1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"author": "callback_demo_agent",
|
||||
"content": {
|
||||
"parts": [
|
||||
{
|
||||
"text": "The weather in Sunnyvale is sunny."
|
||||
},
|
||||
{
|
||||
"text": "\n\nafter_model_callback: [Token Usage: Input=108, Output=8]"
|
||||
}
|
||||
],
|
||||
"role": "model"
|
||||
},
|
||||
"finishReason": "STOP",
|
||||
"id": "e-4",
|
||||
"invocationId": "i-1",
|
||||
"nodeInfo": {
|
||||
"path": "callback_demo_agent@1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user