contents_processor.go
Overview
The contents_processor.go file is responsible for populating the Contents field of an LLMRequest based on the invocation context and session event history. It filters, rearranges, and processes session events to build a coherent context for large language model (LLM) requests, supporting multi-agent interaction, function call/response merging, and selective content inclusion policies.
This file primarily interacts with:
The agent invocation context (
agent.InvocationContext) to access session events and agent metadata.The session event system (
session.Event) to read and manipulate event histories.The LLM request model (
model.LLMRequest) to inject processed content.The internal utilities and data structures within the google.golang.org/genai and google.golang.org/adk modules for content handling.
Its main goal is to prepare the conversation or tool call context properly for LLM consumption, including merging asynchronous function call responses and handling multi-agent scenarios.
Key Functions and Methods
ContentsRequestProcessor
func ContentsRequestProcessor(ctx agent.InvocationContext, req *model.LLMRequest) error
Purpose: Entry point to populate the
req.Contentsbased on the invocation context, including previous session events.Parameters:
ctx: The invocation context providing access to the agent, session, and events.req: The LLM request object to be populated with content.
Returns: An error if any occurs during content building.
Usage: Called during LLM request preparation to enrich the request with relevant conversation or tool interaction content.
Details:
Determines whether to include full history or only current turn context based on agent configuration.
Extracts all session events when available.
Calls appropriate content building function (
buildContentsDefaultorbuildContentsCurrentTurnContextOnly).Appends the processed contents to the request.
buildContentsDefault
func buildContentsDefault(agentName, invocationBranch string, events []*session.Event) ([]*genai.Content, error)
Purpose: Processes a list of session events to generate a filtered, rearranged, and cleaned list of
genai.Contentfor LLM consumption.Parameters:
agentName: Current agent's name for filtering purposes.invocationBranch: The branch ID to filter events by conversation branch.events: The slice of session events to process.
Returns: A slice of pointers to
genai.Contentand an error if processing fails.Details:
Filters events to include only those relevant to the current branch, authored by the user or the current agent or other agents.
Converts events authored by other agents into "user" role content for context.
Removes authorization events related to credential requests.
Rearranges events to merge asynchronous function call responses ensuring proper history consistency.
Cleans up empty or invalid content parts.
Removes client-specific function call IDs for privacy or abstraction.
Usage Example:
contents, err := buildContentsDefault("agent1", "branch_0", sessionEvents) if err != nil { // handle error } req.Contents = append(req.Contents, contents...)
buildContentsCurrentTurnContextOnly
func buildContentsCurrentTurnContextOnly(agentName, branch string, events []*session.Event) ([]*genai.Content, error)
Purpose: Builds content limited to the current turn, excluding conversation history, useful when
include_contents='none'.Parameters: Same as
buildContentsDefault.Returns: Contents for the current turn only or all events if no user or other agent turn is found.
Details:
Finds the latest event authored by a user or another agent and builds content from that point onward.
Usage: Used in scenarios where only the present user input and tool calls/responses are relevant, avoiding older history pollution.
rearrangeEventsForLatestFunctionResponse
func rearrangeEventsForLatestFunctionResponse(events []*session.Event) ([]*session.Event, error)
Purpose: Ensures that the most recent function response event is correctly paired with its function call event by merging intermediate responses.
Parameters: List of session events.
Returns: Reorganized event slice or error if validation fails.
Details:
Detects if the last event contains function responses.
Searches backward to find the matching function call event.
Removes unrelated intermediate events.
Merges all relevant response events into a single event.
Algorithm: Uses backward iteration and ID matching to validate and merge events.
rearrangeEventsForFunctionResponsesInHistory
func rearrangeEventsForFunctionResponsesInHistory(events []*session.Event) ([]*session.Event, error)
Purpose: Cleans and rearranges the entire event history so that every function call event is immediately followed by a consolidated single function response event.
Parameters: Full event history.
Returns: A reordered slice of events with merged function response events or error.
Details:
Builds a map from function call IDs to their corresponding response event indices.
Iterates over events to rebuild the list, merging multiple response events for the same call.
Use Case: Useful for managing long-running or asynchronous tool calls where responses may be spread over multiple events.
mergeFunctionResponseEvents
func mergeFunctionResponseEvents(functionResponseEvents []*session.Event) (*session.Event, error)
Purpose: Merges multiple function response events into one consolidated event that follows its corresponding function call.
Parameters: Sorted list of function response events related to the same function call.
Returns: A single merged event or an error if merging fails.
Details:
Uses the first event as a base.
Builds an index mapping function call IDs to response part indices.
Updates or appends function response parts from later events.
Appends any non-function-response parts at the end.
Important: Does not support parallel calls with async function calls of the same name simultaneously.
ConvertForeignEvent
func ConvertForeignEvent(ev *session.Event) *session.Event
Purpose: Converts events authored by other agents into user-like events for context inclusion.
Parameters: An event authored by a different agent.
Returns: A new event with
Roleset to"user"and content parts rewritten to include author attribution.Details:
Prepends contextual text indicating the original author and nature of each content part.
Useful for multi-agent scenarios enabling continuity by providing previous agents' outputs as user input.
Example:
An event from agent "agentB" with function call parts will be converted with text like
[agentB] called tool "toolName" with parameters: ...
Helper Functions
*isOtherAgentReply(currentAgentName string, ev session.Event) bool: Checks if an event is authored by another agent (not the current agent or user).
*isAuthEvent(ev session.Event) bool: Detects if an event is related to credential requests by checking for a special function call name.
**listFunctionCallsFromEvent(e session.Event) []genai.FunctionCall: Extracts all function calls from an event's content parts.
**listFunctionResponsesFromEvent(e session.Event) []genai.FunctionResponse: Extracts all function responses from an event's content parts.
**cloneEvent(e session.Event) session.Event: Deep copies an event, including its content parts, preserving immutability during rearrangements.
stringify(v any) string: JSON marshals a value to string for logging or display purposes.
Important Implementation Details and Algorithms
Event Filtering and Branch Matching: Events are filtered by branch using string prefix checks to ensure content consistency with the current invocation context.
Function Call/Response Pairing and Merging: Uses unique IDs from function calls and responses to ensure responses are combined and ordered correctly, avoiding duplication or fragmentation of asynchronous tool call results.
Multi-Agent Context Handling: Foreign agent events are converted to user role content to maintain a coherent conversational history usable by the current agent.
Content Part Cleaning: Empty or zero-valued content parts are removed to prevent malformed LLM inputs.
Authorization Event Exclusion: Special function calls related to credential requests are excluded from content to avoid leaking sensitive data.
Deep Copying Events: To avoid mutating shared references in session events, cloning is used before modifications.
Interaction with Other Components
Agent Invocation Context (
agent.InvocationContext): Provides access to the current agent, session, and session events.Session Events (
session.Event): Core data structure representing conversational turns, function calls, and responses.LLM Request Model (
model.LLMRequest): Target for populated content used to query LLMs.Utilities (
utils.Content): Helper functions to extract content from events.GenAI Content (
genai.Contentandgenai.Part): Data structures representing the actual text, function calls, and function responses parts passed to the LLM.
Visual Diagram: Flowchart of Main Functions and Their Relationships
flowchart TD
CRP[ContentsRequestProcessor]
BCD[buildContentsDefault]
BCC[buildContentsCurrentTurnContextOnly]
RAF[rearrangeEventsForLatestFunctionResponse]
RAFH[rearrangeEventsForFunctionResponsesInHistory]
MFR[mergeFunctionResponseEvents]
CFE[ConvertForeignEvent]
CRP -->|decides function| BCD
CRP -->|decides function| BCC
BCD --> RAF
BCD --> RAFH
RAF --> MFR
RAFH --> MFR
BCD --> CFE