Add options to limit history content count included in LLM call
Is your feature request related to a problem? Please describe. Currently the LLM calls include all history from the session. Please add an option to cap the amount of history by time or count.
Describe the solution you'd like An option on how much history to include, not just all or nothing.
Describe alternatives you've considered I think it is possible to modify the history with callbacks but that seems hacky.
I think what we can do is allowing specifying more options in include_contents:
- A time limit.
'30m','12h', etc. - A number indicating the max number of events. E.g. 200.
Contributions are welcome! Thanks.
On this issue I think it is also very important to consider what happens to events that are not included. In my mind there are two good approaches to handling this.
Summarization
- when does this summary get regenerated?
- summarize chunks -> summary of summaries, or single turn summary?
Similarity search.
- include last
x(time,num_events,num tokens) + similarity search on contents that are not included.
Both of these patterns are easy-ish to implement via callbacks but are also fairly core to how agents work and would definitely be a welcome inclusion in ADK.
Related to: https://github.com/google/adk-python/pull/656
Thanks for the suggestions @BenMawnMahlauNBTC
For summarization and similarity search, some of those can be handled by the MemoryService. We will share more once we finalize our design.
As InMemorySessionService class already have a feature limiting the amount of events in the get_session method, we should be able to use these limits as the code exists in get_session.
But the problem is that the run_async method of Runner class doesn't use the config: Optional[GetSessionConfig] of the get_session method InMemorySessionService class:
with tracer.start_as_current_span('invocation'):
session = self.session_service.get_session(
app_name=self.app_name, user_id=user_id, session_id=session_id
)
To override this problem, I built for my own usage a custom class which is working like that:
class LimitedContextGetSessionService(InMemorySessionService):
"""
An InMemorySessionService that limits the number of events returned by get_session,
in order to control the size of the context sent to the LLM.
"""
def __init__(self, max_recent_events_for_llm: int = 10):
super().__init__()
self.max_recent_events_for_llm = max_recent_events_for_llm
print(f"--- LimitedContextGetSessionService initialized: will limit LLM context to "
f"{self.max_recent_events_for_llm} recent events when reading ---")
@override
def get_session(
self,
*,
app_name: str,
user_id: str,
session_id: str,
config: Optional[GetSessionConfig] = None,
) -> Optional[Session]:
# Prepare an effective configuration to limit events
effective_config = config
if effective_config is None:
# If the caller (Runner/Agent) does not provide a config, we apply our default limit.
effective_config = GetSessionConfig(num_recent_events=self.max_recent_events_for_llm)
elif effective_config.num_recent_events is None:
# If the caller's config does not have num_recent_events, we apply our limit.
effective_config.num_recent_events = self.max_recent_events_for_llm
elif effective_config.num_recent_events > self.max_recent_events_for_llm:
# If the caller requests more than our cap, we cap it.
effective_config.num_recent_events = self.max_recent_events_for_llm
return super().get_session(
app_name=app_name,
user_id=user_id,
session_id=session_id,
config=effective_config
)
Then we can inject it into a Runner:
session_service = LimitedContextGetSessionService(max_recent_events_for_llm=15)
runner = Runner(
agent=root_agent,
app_name="My Agent",
session_service=session_service
)
That works fine as a temporary bypass but shouldn't we have the session config directly as an attribute of the abstract class BaseSessionService as it should be used by all the inherited classes : DatabaseSessionService, InMemorySessionService and VertexAiSessionService ?
How about a two-phased approach?
-
Short-term: Direct History Limits.
-
Modify
Runner(or similar) to accepthistory_max_events/history_max_durationconfig. -
Pass this to
session_service.get_sessionviaGetSessionConfig. -
Uses existing
SessionServicecapabilities for a quick fix, as @vlevorato highlighted.# In Runner - def __init__(self, ..., session_service): + def __init__(self, ..., session_service, history_max_events: Optional[int] = None): # and/or duration # ... + self.history_max_events = history_max_events # In run_async - session = self.session_service.get_session(...) + session_config = GetSessionConfig(num_recent_events=self.history_max_events) if self.history_max_events else None + session = self.session_service.get_session(..., config=session_config)
-
-
Long-term: Introduce a
MemoryManagerservice/strategy.- This service would handle more advanced context (summarization, similarity search per @BenMawnMahlauNBTC, and what @boyangsvl suggested with
MemoryService). - The simple limits from Phase 1 could become one strategy within this manager.
- This service would handle more advanced context (summarization, similarity search per @BenMawnMahlauNBTC, and what @boyangsvl suggested with
I have a very similar problem I know i we use the same session there's a chain of events within the session, and its somehow important to give some context to agent, but how can we limit this, I have over 200 events and the input context blows to over 30000 input tokens and hence inducing latency. Any suggestions?
This is related to: https://github.com/google/adk-python/issues/614
We are looking into this issue. Please let us know if you have similar needs, your use cases, and your requirements.
I have a good idea:
Create a before_model_callback method to trim excess contents.
def simple_before_model_modifier(
callback_context: CallbackContext, llm_request: LlmRequest
) -> Optional[LlmResponse]:
"""删减发送给LLM的contents"""
agent_name = callback_context.agent_name
logger.info(f"[回调] 模型调用前的代理: {agent_name}")
logger.info(f"llm_request内存占用[删减前]: {asizeof.asizeof(llm_request)} 字节")
try:
if len(llm_request.contents) > 3:
llm_request.contents = llm_request.contents[-3:]
# 如果修改后的LLM请求仍然太大,则只保留最后一条消息
if asizeof.asizeof(llm_request) > 40000:
llm_request.contents = llm_request.contents[-1]
except Exception as e:
logger.error(f"删除llm_request.contents失败: {e}")
logger.info(f"llm_request内存占用: {asizeof.asizeof(llm_request)} 字节")
return None
So
- By default the LLM is provided all the history.
- Randomly trimming conversations is not a best idea as the LLM request may not include what the user wants.
- A middle ground could be trimming the user interactions (so one user interaction can have many messages like user message, model response which could be a tool call, tool call response and then final summary to end the interaction)
- The user (agent user) should be provided an option to determine how many "user conversations" should be sent back to LLM during an LLM request
- I have found following working reasonably well for our use case.
- The advantage of this method is that since the session (created by db based session service) has all the contents. Users can test what combination works best for them by running with different MAX_PREV_USER_INTERACTIONS during testing.
# use this as the before_model_callback when defining the agent.
# MAX_PREV_USER_INTERACTIONS should be set in the environment
def bmc_trim_llm_request(
callback_context: CallbackContext, llm_request: LlmRequest
) -> Optional[LlmResponse]:
max_prev_user_interactions = int(os.environ.get("MAX_PREV_USER_INTERACTIONS","-1"))
# Everytime the entire new / full list comes from Execution Logic
logging.info(f"Number of contents going to LLM - {len(llm_request.contents)}, MAX_PREV_USER_INTERACTIONS = {max_prev_user_interactions}")
temp_processed_list = []
if max_prev_user_interactions == -1:
return None
else:
user_message_count = 0
# Iterate in reverse order
for i in range(len(llm_request.contents) - 1, -1, -1):
item = llm_request.contents[i]
# Check if the item is a user message and has text content and is not a transfer to agent content
if item.role == "user" and item.parts[0] and item.parts[0].text and item.parts[0].text != "For context:":
logging.info(f"Encountered a user message => {item.parts[0].text}")
user_message_count += 1
if user_message_count > max_prev_user_interactions:
logging.info(f"Breaking at user_message_count => {user_message_count}")
temp_processed_list.append(item) # make sure we add this user message.
break
temp_processed_list.append(item)
# Reverse the temp_processed_list to restore the original chronological order
final_list = temp_processed_list[::-1]
# If user_message_count didn't reach the limit, the list remains unchanged.
if user_message_count < max_prev_user_interactions:
logging.info("User message count did not reach the allowed limit. List remains unchanged.")
else:
logging.info(f"User message count reached {max_prev_user_interactions}. List truncated.")
llm_request.contents = final_list
# we still want LLM to be called, only sometimes with reduced number of contents.
return None
My implementation
# Set the number of history dialogue turns to retain; 0 means no history will be kept
HISTORY_LENGTH = 2
async def before_model_callback(
callback_context: CallbackContext, llm_request: LlmRequest
) -> Optional[LlmResponse]:
if not llm_request.contents:
return None
user_indices = [
i
for i, item in enumerate(llm_request.contents)
if item.role == "user" and item.parts and item.parts[0].text
]
if not user_indices:
return None
hist = HISTORY_LENGTH + 1
keep_turns = min(hist, len(user_indices))
start_user_idx = user_indices[-keep_turns]
llm_request.contents = llm_request.contents[start_user_idx:]
return None
@hangfei can you get someone to implement this feature, i am using an external db and as the context grows response time is more and more!
When will this feature released?
Edit: proving an simpler and improved version, more aligned with the Google ADK SDK. Works fine both with mono and multi-agents setups.
"""
This module provides a callback function to trim the conversation history to a specified number of recent user turns.
For more informations, please check: https://google.github.io/adk-docs/tutorials/agent-team/#step-5-adding-safety-input-guardrail-with-before_model_callback
"""
from typing import Callable, Optional
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 loguru import logger
def get_trim_model_history_callback(
max_history_length: int,
) -> Callable[[CallbackContext, LlmRequest], Optional[LlmResponse]]:
"""
Returns the trim_model_history_callback function. This function truncates the conversation history
to the specified number of recent turns.
What is a turn?
> A turn is defined as the aggregation of all the events between two not user messages flagged as is_final_response().
> A turn can be also obtained by aggregating all the events having the same invocation_id.
Args:
max_history_length (int): The maximum number of recent turns to keep in the conversation history, including the current turn.
Returns:
Callable[[CallbackContext, LlmRequest], Optional[LlmResponse]]: The callback function
"""
def _trim_model_history_callback(
callback_context: CallbackContext, # pylint: disable=unused-argument
llm_request: LlmRequest,
) -> Optional[LlmResponse]:
"""
Callback function to truncate conversation history before sending to the model.
Identifies turn boundaries and keeps only the most recent complete turns.
"""
if not llm_request.contents:
logger.warning(
"No conversation history to trim, llm_request.contents is empty."
)
return None
events = (
callback_context._invocation_context.session.events # pylint: disable=protected-access
)
# important assumption: the length of the session events and the llm_request.contents must be the same
if len(events) != len(llm_request.contents):
raise ValueError(
f"Length mismatch between session events: {len(events)} and llm_request.contents: {len(llm_request.contents)}"
)
# let's extract the indexes of the first event of each turn
turn_start_indexes = [0] # always keep the first event
for idx, event in enumerate(events):
if (
event.is_final_response() and event.author != "user"
): # for some reason, user messages have is_final_response() set to True
turn_start_indexes.append(idx + 1)
# Now we can determine the starting index to keep
if len(turn_start_indexes) <= max_history_length:
logger.debug(
f"Current number of turns is {len(turn_start_indexes)}, which is within the max history length of {max_history_length}. No trimming needed."
)
return None
logger.debug(
f"Trimming conversation history to the last {max_history_length} turns from {len(turn_start_indexes)} total turns."
)
start_idx = turn_start_indexes[-max_history_length]
llm_request.contents = llm_request.contents[start_idx:]
# --- for pure debugging, print the resulting trimmed history ---
# uncomment to enable
# for ev in callback_context._invocation_context.session.events:
# print(
# ev.invocation_id,
# ev.author,
# ev.is_final_response(),
# (
# ev.content.parts[0].text[:20] + "..."
# if ev.content.parts[0].text
# else None
# ),
# )
# if ev.is_final_response() and ev.author != "user":
# print("------ TURN -------")
# Returning None signals ADK to continue normally
return None
return _trim_model_history_callback
Now it's provided as a plugin: https://github.com/google/adk-python/blob/main/src/google/adk/plugins/context_filter_plugin.py.
Thanks for the feedback and discussion!
@hangfei I had some issues with the custom_filter type custom_filter: Optional[Callable[[List[Event]], List[Event]]] = None, - it seems to expect List[Event] but receives List[Content] - unless I am using it wrong