map.go

Overview

This file implements the parentmap package that provides a specialized mapping structure to represent and navigate hierarchical relationships among agents. Specifically, it constructs and manages a "parent map" for an agent tree, where each agent (except the root) has a single parent. This enables efficient retrieval of an agent's parent and traversal to the root agent. The package also supports storing and retrieving the parent map within a context.Context for convenient propagation across API boundaries.

The core functionality centers on verifying tree integrity (unique agent names, single-parent constraints) and facilitating upward navigation in the agent hierarchy. The file interacts with the agent.Agent interface from the google.golang.org/adk/agent package, which defines the agent abstraction including agent names and sub-agent relationships.


Types and Functions

Type: Map

type Map map[string]agent.Agent

Function: New

func New(root agent.Agent) (Map, error)

Method: RootAgent

func (m Map) RootAgent(cur agent.Agent) agent.Agent

Function: ToContext

func ToContext(ctx context.Context, parents Map) context.Context

Function: FromContext

func FromContext(ctx context.Context) Map

Internal Type: ctxKey and Constant mapCtxKey

type ctxKey int

const mapCtxKey ctxKey = 0

Interactions with Other Components


Implementation Details and Algorithms


Usage Examples

// Constructing a parent map for an agent tree.
rootAgent := getRootAgent()
parentMap, err := parentmap.New(rootAgent)
if err != nil {
    // handle invalid tree: duplicate names or multiple parents
}

// Find the root agent of any agent.
someAgent := getSomeAgent()
root := parentMap.RootAgent(someAgent)

// Passing parent map through context.
ctx := context.Background()
ctxWithMap := parentmap.ToContext(ctx, parentMap)

// Retrieving parent map from context.
retrievedMap := parentmap.FromContext(ctxWithMap)

Diagram: Structure and Main Function Relationships

classDiagram
class Map {
+RootAgent()
}
class New {
<<function>>
}
class ToContext {
<<function>>
}
class FromContext {
<<function>>
}
Map --> New : "created by"
ToContext --> Map : "stores in context"
FromContext --> Map : "retrieves from context"

This diagram shows the main entities and their relations: New creates a Map, which provides the RootAgent method, and ToContext/FromContext allow embedding and extracting the map from a context.Context.