context.go
Overview
The context.go file defines core internal context handling utilities for managing tool execution within the agent framework. It provides an implementation of the tool.Context interface that wraps an agent's invocation context, facilitating artifact management, event action tracking, and memory search capabilities during tool execution. This file ties together agent session state, artifact versioning, and event delta recording in a unified context object used by tools to interact with the broader agent environment.
It primarily implements the toolContext struct and a related internal wrapper for artifact saving that tracks version deltas in session event actions. The file also contains the factory function NewToolContext which initializes this context, ensuring proper setup of state delta maps and unique function call IDs.
This functionality is crucial for enabling tools invoked by agents to persist artifacts, update session state, and perform memory queries while correctly propagating event changes and maintaining traceability via function call IDs.
Types and Functions
internalArtifacts struct
type internalArtifacts struct {
agent.Artifacts
eventActions *session.EventActions
}
Description:
An internal wrapper around theagent.Artifactsinterface that enhances artifact saving by tracking artifact version deltas within the associatedsession.EventActions. This allows the session's event state to reflect changes made to artifacts during tool execution.Fields:
Artifacts: Embeddedagent.Artifactsinterface providing the basic artifact operations.eventActions: Pointer tosession.EventActionscapturing state changes and event deltas.
Methods:
Save(ctx context.Context, name string, data *genai.Part) (*artifact.SaveResponse, error)Purpose:
Overrides the standard save operation to record the version of the saved artifact into theArtifactDeltamap of the session's event actions. This enables downstream processing components to detect and react to new artifact versions.Parameters:
ctx: Execution context for cancellation and deadlines.name: The artifact name (key) under which data is saved.data: The artifact content represented as agenai.Part.
Returns:
*artifact.SaveResponse: Contains metadata about the saved artifact, including its version.error: Any error encountered during save.
Implementation Details:
Delegates actual save to the embedded
agent.Artifacts.Save.If
eventActionsis non-nil, initializesArtifactDeltamap if needed.Updates
ArtifactDelta[name]with the returned artifact version.Contains a TODO note regarding concurrency control (RWLock) for handling concurrent saves.
Usage Example:
resp, err := internalArtifacts.Save(ctx, "example.txt", dataPart) if err != nil { // handle error } // resp.Version contains the new artifact version
NewToolContext function
func NewToolContext(ctx agent.InvocationContext, functionCallID string, actions *session.EventActions) tool.Context
Purpose:
Factory function to create a newtool.Contextimplementation that wraps an agent's invocation context. Ensures proper initialization of event action state deltas and generates a unique function call ID if not provided.Parameters:
ctx: Theagent.InvocationContextrepresenting the current agent invocation lifecycle context.functionCallID: Optional string to identify this particular tool invocation; if empty, a new UUID is generated.actions: Pointer tosession.EventActionsused to track event and state deltas; if nil, a new emptyEventActionswith initialized state delta map is created.
Returns:
tool.Context: The resulting context object implementing thetool.Contextinterface, wrapping the input context and event actions.
Implementation Details:
Ensures
functionCallIDis set, generating a UUID if empty.Ensures
actionsand itsStateDeltamap are non-nil.Creates a
CallbackContextfrom the internal context package using the state delta map.Constructs a
toolContextinstance embedding these elements and wrapping the agent's artifacts withinternalArtifactsto track artifact deltas.
Usage Example:
toolCtx := NewToolContext(invocationCtx, "", nil)
toolContext struct
type toolContext struct {
agent.CallbackContext
invocationContext agent.InvocationContext
functionCallID string
eventActions *session.EventActions
artifacts *internalArtifacts
}
Description:
Implementstool.Contextby embeddingagent.CallbackContextand extending it with fields to store invocation context, function call ID, event actions, and an internal artifacts wrapper.Fields:
CallbackContext: Embedded context handling callbacks and state delta injection (Agent Lifecycle and Callbacks).invocationContext: The underlying agent invocation context (Agent Invocation Context).functionCallID: Unique identifier string for the particular tool or function call, useful for tracing and correlation.eventActions: Pointer to the session's event actions tracking state and artifact deltas (Session Management).artifacts: Internal wrapper ofagent.Artifactsthat tracks artifact saves.
Methods:
Artifacts() agent.ArtifactsReturns the wrapped
internalArtifactsinstance that tracks artifact saves and versions.
FunctionCallID() stringReturns the unique identifier for this function call context.
Actions() *session.EventActionsReturns the pointer to the current session event actions, allowing tools to inspect or modify event/state deltas.
AgentName() stringReturns the name of the agent associated with the invocation context.
SearchMemory(ctx context.Context, query string) (*memory.SearchResponse, error)Delegates a memory search query to the underlying agent's memory store, returning results or errors.
Usage Example:
agentName := toolCtx.AgentName() resp, err := toolCtx.SearchMemory(ctx, "search query")
Important Implementation Details and Algorithms
Artifact Delta Tracking:
TheinternalArtifactsstruct extends the artifact save process to record the version of artifacts saved into theArtifactDeltamap of thesession.EventActions. This mechanism supports event-driven updates and synchronization by tracking exactly which artifacts were changed during tool execution.State Delta Injection:
ThetoolContextembedsagent.CallbackContextconstructed with a state delta map. This enables automatic injection and tracking of state changes within instructions or callbacks, as detailed in Session State Injection and Agent Lifecycle and Callbacks.Function Call Identification:
Each tool context is assigned a uniquefunctionCallID(UUID if not provided) to correlate actions, artifact saves, and event deltas to a specific function or tool invocation, enhancing observability and debugging.Memory Search Delegation:
TheSearchMemorymethod exposes the underlying agent's memory search capability, supporting tools that require retrieval of context or historical data from memory stores (Agent Invocation Context).Thread Safety Considerations:
The TODO comment ininternalArtifacts.Savehighlights the need to implement read-write lock mechanisms to handle concurrent artifact saves reliably, ensuring version consistency when multiple tools might save to the same artifact.
Interaction with Other System Components
Agent Invocation Context (
agent.InvocationContext):
ThetoolContextwraps this interface to access the agent's artifacts, memory, and agent metadata. This integration allows tools to directly operate on agent resources during execution (Agent Invocation Context).Session Event Actions (
session.EventActions):
The context propagates and updates event actions that capture state deltas and artifact version changes, enabling session state synchronization and event-driven workflows (Session Management).Artifact Management (
agent.Artifactsandartifact.SaveResponse):
Artifact saving is delegated to the underlying agent artifact service, with added tracking of artifact version changes to support session event updates (Artifact Management).Callback Context (
agent.CallbackContext):
Embedded intoolContextto support lifecycle hooks and state injection during callback execution (Agent Lifecycle and Callbacks).Memory Search (
memory.SearchResponse):
Provides search functionality over the agent's memory store, allowing tools to query prior knowledge or session data (Agent Invocation Context).
Structure Diagram
classDiagram
class internalArtifacts {
+Save()
-Artifacts
-eventActions
}
class toolContext {
+Artifacts()
+FunctionCallID()
+Actions()
+AgentName()
+SearchMemory()
-CallbackContext
-invocationContext
-functionCallID
-eventActions
-artifacts
}
internalArtifacts --> agent.Artifacts
toolContext --> agent.CallbackContext
toolContext --> agent.InvocationContext
toolContext --> session.EventActions
toolContext --> internalArtifacts