Cannot access agent's final output from after_agent_callback
Describe the bug
As per official documentation, we should be able to modify the final agent response by operating at after_agent_callback level.
As per ADK 1.5, however, it seems there is no way to publicly access the agent's final output from within the callback_context parameter. This clearly is either a BUG in the code or an error in the documentation.
To Reproduce Steps to reproduce the behavior:
- Create an agent
- Register a
after_agent_callback - Debug and inspect the values of callback_context variable
Expected behavior There should a way to access the final output of the agent via the callback_context or via another parameter passed to the callback.
Screenshots
Desktop (please complete the following information):
- OS: Windows 11
- Python version(python -V): 3.13
- ADK version(pip show google-adk): 1.5
Model Information:
Gemini 2.5-flash
Additional context
Possibly related to #1231. However, in my opinion, this has to be considered a BUG and not a feature request, unless we clearly change the documentation.
Any news on this?
You can access the agents' (model) output through the after_model_callback. It takes the callback_context and the LlmResponse as arguments. I think this is a documentation error.
That's what I did as a workaround, but it is suboptimal. An agent might call the model multiple times in a single iteration, especially if we have tooling involved (there might be multiple tooling calls for the same task). This requires us to handle the intermediate output of the model. I believe it would be really useful to have the opportunity to change the entire output of the agent once it has been processed, just before returning it to the user. Again, the documentation is misleading and suggests one can manipulate the agent's output, while that's not the case: we can only overwrite it.
Any update on this??
My goal is to validate and postprocess the agent's final output before it is returned. I am using the after_agent_callback for this, as the documentation suggests it runs after the agent's main logic has finished and produced its result.
Expected Behavior: I expected the session.state object within the after_agent_callback to contain the agent's final output, which should have been saved to the output_key specified in the agent's configuration.
Actual Behavior: The session.state available in the after_agent_callback often does not contain the agent's final output, even though the output_key is correctly set. It seems the callback is being triggered before the state is fully updated with the final result, or there is a race condition.
ADK version 1.17.0.
Hello
It is possible to modify and completely change model final response using after_model_callback. I might have to add some conditions to only modify final output of the agent. Below is example code for reference:
Code:
from google.adk.agents import LlmAgent
from google.adk.agents.callback_context import CallbackContext
from google.adk.models import LlmResponse
from google.adk.runners import Runner
from google.genai import types
from google.adk.sessions import InMemorySessionService
from google.adk.tools import FunctionTool
from dotenv import load_dotenv
import os
import asyncio
load_dotenv()
api = os.environ.get("GEMINI_API_KEY")
os.environ["api_key"] = api
GEMINI_2_FLASH="gemini-2.0-flash"
def get_capital_city(country: str) -> str:
"""Retrieves the capital city of a given country."""
country_capitals = {
"united states": "Washington, D.C.",
"canada": "Ottawa",
"france": "Paris",
"germany": "Berlin",
}
return {"result": country_capitals.get(country.lower(), f"Capital not found for {country}")}
capital_tool = FunctionTool(func=get_capital_city)
def simple_after_model_modifier(llm_response: LlmResponse, callback_context: CallbackContext):
is_final_response_generation = (
llm_response.content and
llm_response.content.parts and
llm_response.content.parts[0].text and
not llm_response.content.parts[0].function_call
)
if is_final_response_generation:
print(f"[Callback] Original LLM response: '{llm_response.content.parts[0].text}'")
prefix = "[Modified by Callback] "
# llm_response.content.parts[0].text = prefix + llm_response.content.parts[0].text
llm_response.content.parts[0].text = prefix
my_llm_agent = LlmAgent(
name="AfterToolCallbackAgent",
model=GEMINI_2_FLASH,
instruction="You are an agent that finds capital cities using the get_capital_city tool. Report the result clearly.",
description="An LLM agent demonstrating after_tool_callback",
tools=[capital_tool], # Add the tool
after_model_callback=simple_after_model_modifier # Assign the callback
)
APP_NAME = "guardrail_app"
USER_ID = "user_1"
SESSION_ID = "session_001"
async def setup_session_and_runner():
session_service = InMemorySessionService()
session = await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=my_llm_agent, app_name=APP_NAME, session_service=session_service)
return session, runner
async def call_agent_async(query):
content = types.Content(role='user', parts=[types.Part(text=query)])
session, runner = await setup_session_and_runner()
events = runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=content)
async for event in events:
if event.is_final_response():
final_response = event.content.parts[0].text
print("Final agent Response after callback and tool call: ", final_response)
asyncio.run(call_agent_async("united states"))
Reponse:
[Callback] Original LLM response: 'The capital city of the United States is Washington, D.C.
'
Final agent Response after callback and tool call: [Modified by Callback]
Closing this issue, please free feel to reach out if you still face this issue.