utils.go
Overview
The utils.go file provides a collection of utility functions designed to facilitate working with genai.Content messages and related types within the AI agent framework. These utilities primarily support handling function call and response IDs, extracting specific parts from genai.Content, and augmenting LLM requests with system instructions. The file serves as a helper layer to streamline interactions with the content structures used in event streams and LLM agent requests, ensuring reliable ID management and convenient content manipulation.
Functions and Methods
PopulateClientFunctionCallID
func PopulateClientFunctionCallID(c *genai.Content)
Purpose: Ensures that all
FunctionCallobjects within agenai.Contentinstance have unique IDs assigned. This is necessary because some models omit these IDs, but downstream components (e.g., LLMAgent) rely on these IDs to correlateFunctionCallandFunctionResponseevents.Parameters:
c *genai.Content: The content object containing function calls.
Returns: None.
Usage: Call before sending content to the agent/event stream to guarantee function call IDs exist.
Implementation Details: Iterates through all function calls extracted from
cand assigns a new UUID with the prefix"adk-"if the ID is empty.
RemoveClientFunctionCallID
func RemoveClientFunctionCallID(c *genai.Content)
Purpose: Removes function call IDs that were previously set by
PopulateClientFunctionCallID. This is important when sending data back to the model to avoid exposing client-generated IDs.Parameters:
c *genai.Content: The content object containing function calls and function responses.
Returns: None.
Usage: Call before returning content to the LLM model to sanitize client-generated IDs.
Implementation Details: Iterates through both function calls and function responses in the content, clearing IDs that start with the
"adk-"prefix.
Content
func Content(ev *session.Event) *genai.Content
Purpose: Convenience function to extract the
genai.Contentfrom asession.Event.Parameters:
ev *session.Event: The event object from which to extract content.
Returns:
*genai.Content: The content of the event's LLM response; returnsnilif the event isnil.
Usage: Simplifies access to content nested within session events.
FunctionCalls
func FunctionCalls(c *genai.Content) []*genai.FunctionCall
Purpose: Extracts all
FunctionCallparts contained in agenai.Content.Parameters:
c *genai.Content: The content object to inspect.
Returns:
Slice of pointers to
genai.FunctionCall.
Usage: Useful for processing or analyzing all function calls embedded in content parts.
Implementation Details: Iterates through
c.Partsand collects all non-nilFunctionCallpointers.
FunctionResponses
func FunctionResponses(c *genai.Content) []*genai.FunctionResponse
Purpose: Extracts all
FunctionResponseparts from the content.Parameters:
c *genai.Content: The content to search.
Returns:
Slice of pointers to
genai.FunctionResponse.
Usage: Used to retrieve function response parts for processing or event correlation.
Implementation Details: Iterates parts to collect all non-
nilFunctionResponsepointers.
TextParts
func TextParts(c *genai.Content) []string
Purpose: Extracts all text segments from the content parts.
Parameters:
c *genai.Content: The content containing parts.
Returns:
Slice of text strings found in the parts.
Usage: Useful when only the plain text content is needed from a complex message.
Implementation Details: Collects non-empty
Textfields from each part.
FunctionDecls
func FunctionDecls(c *genai.GenerateContentConfig) []*genai.FunctionDeclaration
Purpose: Extracts all function declarations from the tools defined in a
GenerateContentConfig.Parameters:
c *genai.GenerateContentConfig: The configuration containing tool definitions.
Returns:
Slice of pointers to
genai.FunctionDeclaration.
Usage: Useful for retrieving all function declarations that might be registered in a request configuration.
Implementation Details: Iterates through
Toolsand accumulates theirFunctionDeclarations.
Must
func Must[T agent.Agent](a T, err error) T
Purpose: Helper function to wrap agent creation or retrieval calls that return
(agent.Agent, error). Panics if an error is encountered.Parameters:
a T: An agent instance.err error: The error to check.
Returns:
The agent instance
aiferrisnil.
Usage: Used to simplify initialization code where error handling is not desired or expected.
Implementation Details: Panics on any non-
nilerror.
AppendInstructions
func AppendInstructions(r *model.LLMRequest, instructions ...string)
Purpose: Appends one or more instructions to the
SystemInstructionfield of anLLMRequest'sGenerateContentConfig.Parameters:
r *model.LLMRequest: The LLM request to modify.instructions ...string: One or more instruction strings to append.
Returns: None.
Usage: Enhances or modifies system-level instructions in an LLM request by appending additional text.
Implementation Details:
Joins instructions with double newlines.
Initializes
ConfigorSystemInstructionifnil.Appends the new instructions as additional parts to the existing system instruction content.
Important Implementation Details
Function Call ID Handling
The prefix"adk-"is used to mark client-generated function call IDs for internal tracking. This ensures that IDs added by the client can be distinguished and removed before sending data back to the model, maintaining ID integrity and preventing leakage.Content Part Extraction
The utilities rely on thePartsslice withingenai.Contentto extract different message components (FunctionCall,FunctionResponse,Text). This modular approach allows flexible processing of composite content messages.Generics Usage in Must
TheMustfunction uses Go generics to work with any type implementingagent.Agent, enforcing type safety while simplifying error handling patterns.Appending Instructions
TheAppendInstructionsfunction carefully handles cases where theConfigorSystemInstructionfields arenil, ensuring that instructions can always be appended without external checks.
Interaction with Other System Components
LLMAgent and Event Stream
ThePopulateClientFunctionCallIDandRemoveClientFunctionCallIDfunctions integrate tightly with the event stream processing in theLLMAgentby ensuring function call IDs are consistently present or removed as needed for event correlation.Session Events
TheContentfunction provides a straightforward way to extract LLM response content from session events (session.Event), which are core to session management and event-driven workflows.LLMRequest Configuration
AppendInstructionsmodifiesmodel.LLMRequestinstances, which are fundamental in generating content from language models. This utility supports enhancing system instructions dynamically as part of agent workflows.Agent Interface Usage
TheMustfunction simplifies working with agents implementing theagent.Agentinterface, facilitating cleaner agent initialization and error handling in calling code.
Flowchart of Main Utilities and Their Relationships
flowchart TD
A[Content from session.Event]
B[Extract FunctionCalls]
C[Extract FunctionResponses]
D[Extract TextParts]
E[Populate FunctionCall IDs]
F[Remove FunctionCall IDs]
G[Extract FunctionDecls from GenerateContentConfig]
H[Append Instructions to LLMRequest]
I["Must (Agent Helper)"]
A --> B
A --> C
A --> D
B --> E
B & C --> F
G --> H
I --> H
Usage Examples
Assigning FunctionCall IDs Before Sending to Agent
content := getGenAIContent()
utils.PopulateClientFunctionCallID(content)
// Now content function calls have unique IDs for event tracking
Removing Client-Generated IDs Before Returning to Model
content := getGenAIContent()
utils.RemoveClientFunctionCallID(content)
// Client IDs cleared to avoid leaking internal IDs
Extracting Text from Content
textSegments := utils.TextParts(content)
for _, text := range textSegments {
fmt.Println(text)
}
Appending Instructions to LLMRequest
req := &model.LLMRequest{}
utils.AppendInstructions(req, "First instruction", "Second instruction")
// req.Config.SystemInstruction now contains appended instructions
Using Must for Agent Creation
agent, err := agent.NewMyAgent(params)
agent = utils.Must(agent, err)
// agent is guaranteed non-nil, or panic occurred
This file is central to handling content-related operations in the AI agent ecosystem, ensuring consistent ID management, part extraction, and request augmentation, thereby supporting the robust functioning of agents, sessions, and LLM interactions.
For more detailed concepts on agent lifecycle and invocation, see Agent Lifecycle and Callbacks and LLM Integration and Agents. For session-related event handling, refer to Session Management.