team

package
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package team provides multi-agent orchestration with inter-agent communication.

Teams coordinate multiple agents working together using different strategies: sequential (pipeline), parallel (fan-out/fan-in), router (intelligent dispatch), or coordinator (LLM-driven task decomposition). Communication flows through the protocol.Bus with optional direct agent-to-agent channels for low-latency paths.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateHandoffTools added in v0.3.0

func CreateHandoffTools(agents []*agent.Agent) map[string][]*tool.Definition

CreateHandoffTools generates transfer tools for a set of agents. Each agent gets a tool to transfer to every other agent.

func HandoffResult added in v0.3.0

func HandoffResult(result any) (agentID, response string, err error)

HandoffResult extracts the handoff result from a tool call response.

func NewHandoffTool added in v0.3.0

func NewHandoffTool(cfg HandoffConfig) *tool.Definition

NewHandoffTool creates a tool that hands off conversation to another agent. The calling agent can invoke this tool to delegate work to the target agent with specific instructions.

func SwarmHandoffTool added in v0.3.0

func SwarmHandoffTool(targetID, targetName, description string) *tool.Definition

SwarmHandoffTool creates a tool for peer-to-peer handoff in a swarm. Unlike the standard handoff tool, this one includes the full task context.

Types

type AgentInfo

type AgentInfo struct {
	ID           string   `json:"id"`
	Name         string   `json:"name"`
	Description  string   `json:"description"`
	Capabilities []string `json:"capabilities"`
}

AgentInfo is a lightweight descriptor exposed to routing functions.

type ErrorStrategy

type ErrorStrategy int

ErrorStrategy controls how agent failures are handled.

const (
	ErrorStrategyFailFast   ErrorStrategy = iota // abort on first error
	ErrorStrategyCollect                         // collect all errors, return combined
	ErrorStrategyBestEffort                      // ignore errors, return successful results
)

type HandoffConfig added in v0.3.0

type HandoffConfig struct {
	TargetAgent  *agent.Agent
	Description  string
	Instructions string
}

HandoffConfig configures a handoff tool for a specific target agent.

type HierarchyConfig added in v0.3.0

type HierarchyConfig struct {
	// Root is the top-level supervisor.
	Root *SupervisorNode
}

HierarchyConfig configures a hierarchical multi-level supervisor team.

type MergeFunc

type MergeFunc func(results []graph.State) graph.State

MergeFunc combines results from parallel agent executions.

type ModelRouterFunc

type ModelRouterFunc func(ctx context.Context, state graph.State, agents []AgentInfo) (string, error)

ModelRouterFunc selects an agent using model-based reasoning. It receives the full state plus a list of available agents with descriptions.

func NewModelRouter added in v0.10.0

func NewModelRouter(provider model.Provider) ModelRouterFunc

NewModelRouter returns a ModelRouterFunc that asks an LLM to pick the single best-suited agent for the task described in the state.

The router builds a system prompt from the agents' IDs, names, descriptions, and capabilities, sends the task (state["message"], or a flattened view of the state) as the user turn, and requests a JSON object of the form {"agent_id": "<id>"}. The returned ID is validated against the supplied agent list; if the model answers with prose or an unknown ID, the router attempts to recover the choice by scanning the response for a known agent ID before failing. Temperature is pinned to 0 for deterministic dispatch.

Pair it with StrategyRouter via Team.SetModelRouter. Unlike the capability heuristic (the zero-config fallback), this makes routing decisions from the task's actual meaning rather than string overlap with state keys.

type RouterFunc

type RouterFunc func(state graph.State) string

RouterFunc selects an agent ID based on the current state.

type Strategy

type Strategy string

Strategy defines how work is distributed across team members.

const (
	StrategySequential  Strategy = "sequential"
	StrategyParallel    Strategy = "parallel"
	StrategyRouter      Strategy = "router"
	StrategyCoordinator Strategy = "coordinator"
	StrategySwarm       Strategy = "swarm"
	StrategyHierarchy   Strategy = "hierarchy"
)

type SupervisorNode added in v0.3.0

type SupervisorNode struct {
	// Supervisor is the agent that manages this level.
	Supervisor *agent.Agent
	// Workers are leaf-level agents at this level.
	Workers []*agent.Agent
	// SubTeams are nested supervisor nodes.
	SubTeams []*SupervisorNode
}

SupervisorNode represents a node in the supervisor hierarchy. It can contain either agents (leaf workers) or other supervisors (sub-teams).

type SwarmConfig added in v0.3.0

type SwarmConfig struct {
	// Agents is the set of agents in the swarm.
	Agents []*agent.Agent
	// InitialAgent is the agent that handles the first message.
	InitialAgent string
	// MaxHandoffs limits the total number of handoffs (0 = 10 default).
	MaxHandoffs int
}

SwarmConfig configures a swarm-style team where agents hand off directly to each other without a central coordinator.

type Team

type Team struct {
	ID       string
	Name     string
	Agents   map[string]*agent.Agent
	Order    []string
	Strategy Strategy

	Router      RouterFunc
	ModelRouter ModelRouterFunc
	Merge       MergeFunc
	Bus         *protocol.Bus

	MaxConcurrency int           // for parallel strategy; 0 = unbounded
	ErrorMode      ErrorStrategy // how to handle agent failures
	Coordinator    *agent.Agent  // explicit coordinator agent (for StrategyCoordinator)
	MaxIterations  int           // max coordinator planning iterations; 0 = 1

	CompiledGraph *graph.CompiledGraph // for swarm/hierarchy graph-based execution

	SharedContext map[string]any
	// contains filtered or unexported fields
}

Team orchestrates multiple agents working together.

func New

func New(id, name string, strategy Strategy) *Team

New creates a team with the given strategy.

func NewHierarchy added in v0.3.0

func NewHierarchy(cfg HierarchyConfig) (*Team, error)

NewHierarchy creates a hierarchical team where supervisors delegate to mid-level supervisors, which delegate to worker agents.

func NewSwarm added in v0.3.0

func NewSwarm(cfg SwarmConfig) (*Team, error)

NewSwarm creates a swarm team where any agent can hand off to any other agent. Each agent receives handoff tools for all other agents in the swarm.

func (*Team) AddAgent

func (t *Team) AddAgent(a *agent.Agent) *Team

AddAgent adds an agent to the team and registers it on the communication bus.

func (*Team) Broadcast

func (t *Team) Broadcast(ctx context.Context, fromAgent, subject string, data map[string]any) error

Broadcast sends a message from one agent to all others via the bus.

func (*Team) DelegateTask

func (t *Team) DelegateTask(ctx context.Context, from, to, subject string, task protocol.TaskPayload) (*protocol.ResultPayload, error)

DelegateTask uses the bus to delegate a task from one agent to another.

func (*Team) DirectChannel

func (t *Team) DirectChannel(agentA, agentB string, bufSize int) *protocol.DirectChannel

DirectChannel returns (or creates) a dedicated low-latency channel between two agents that bypasses the central bus.

func (*Team) MessageHistory

func (t *Team) MessageHistory() []*protocol.Envelope

MessageHistory returns all inter-agent messages exchanged during the team run.

func (*Team) Run

func (t *Team) Run(ctx context.Context, input graph.State) (graph.State, error)

Run executes the team's strategy with the given input.

func (*Team) RunStream added in v0.8.0

func (t *Team) RunStream(ctx context.Context, input graph.State) (<-chan TeamStreamEvent, error)

RunStream executes the team's strategy and streams agent output token by token. It returns a channel of TeamStreamEvent that the caller must drain to completion; the channel is closed when the run finishes.

The stream always ends with exactly one terminal event: TeamEventComplete (carrying the merged final State) on success, or TeamEventError on failure.

Streaming is supported for the sequential, parallel, router, coordinator and hierarchy strategies. The swarm strategy runs to completion but does not emit token events, because it inspects tool-call output to route handoffs.

func (*Team) SetCoordinator

func (t *Team) SetCoordinator(a *agent.Agent) *Team

SetCoordinator sets an explicit coordinator agent (for StrategyCoordinator). The coordinator is automatically registered on the bus so it can delegate tasks.

func (*Team) SetErrorStrategy

func (t *Team) SetErrorStrategy(es ErrorStrategy) *Team

SetErrorStrategy controls how agent failures are handled.

func (*Team) SetMaxConcurrency

func (t *Team) SetMaxConcurrency(n int) *Team

SetMaxConcurrency limits goroutines for parallel execution.

func (*Team) SetMaxIterations

func (t *Team) SetMaxIterations(n int) *Team

SetMaxIterations sets the max number of coordinator planning iterations.

func (*Team) SetMerge

func (t *Team) SetMerge(fn MergeFunc) *Team

SetMerge sets the merge function (for StrategyParallel).

func (*Team) SetModelRouter

func (t *Team) SetModelRouter(fn ModelRouterFunc) *Team

SetModelRouter sets a model-based routing function (for StrategyRouter).

func (*Team) SetRouter

func (t *Team) SetRouter(fn RouterFunc) *Team

SetRouter sets a static routing function (for StrategyRouter).

type TeamEventType added in v0.8.0

type TeamEventType string

TeamEventType classifies a TeamStreamEvent.

const (
	// TeamEventAgentStart is emitted just before an agent begins producing output.
	TeamEventAgentStart TeamEventType = "agent_start"
	// TeamEventToken carries a single text fragment from an agent as it streams.
	TeamEventToken TeamEventType = "token"
	// TeamEventAgentEnd is emitted after an agent finishes producing output.
	TeamEventAgentEnd TeamEventType = "agent_end"
	// TeamEventComplete is the final event carrying the team's merged output state.
	TeamEventComplete TeamEventType = "complete"
	// TeamEventError is a terminal event carrying a fatal error.
	TeamEventError TeamEventType = "error"
)

type TeamStreamEvent added in v0.8.0

type TeamStreamEvent struct {
	Type    TeamEventType `json:"type"`
	AgentID string        `json:"agent_id,omitempty"`
	Content string        `json:"content,omitempty"` // token text for TeamEventToken
	State   graph.State   `json:"state,omitempty"`   // final state for TeamEventComplete
	Err     error         `json:"-"`                 // set for TeamEventError
}

TeamStreamEvent is a single event emitted while a team runs in streaming mode. Events from different agents may interleave (e.g. under the parallel strategy); use AgentID to attribute each token to its producer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL