TnsAI
Coordination

Group Topologies

TnsAI.Coordination provides 8 group topologies for structuring multi-agent collaboration. Each topology has a dedicated builder and follows the lifecycle: create -> start -> execute -> stop.

Team

A Team is the most common topology. It groups agents by role (lead, member, expert, reviewer) and executes tasks using a configurable formation (parallel, sequential, hierarchical, etc.). Think of it like organizing a project team where each person has a defined responsibility.

TeamRole

Each agent in a team is assigned a role that determines its authority level and whether it actively participates in task execution.

RoleAuthorityParticipatesDescription
LEADYesYesCoordinates and delegates, final decision authority
CO_LEADYesYesAssists lead, takes over if lead unavailable
MEMBERNoYesExecutes assigned tasks
EXPERTNoYesSubject matter expert, consulted for specialized knowledge
REVIEWERNoYesValidates output, quality control
OBSERVERNoNoMonitors but does not participate
FACILITATORYesYesCoordinates discussions (used in DEBATE formation)

TeamFormation

The formation controls how the team executes its work. For example, PARALLEL runs all members at once for speed, while SEQUENTIAL passes context from one member to the next like a relay.

FormationDescriptionRequires LeadOrdered
PARALLELAll members work simultaneouslyNoNo
SEQUENTIALMembers work in sequence, passing contextNoYes
HIERARCHICALLead coordinates and delegatesYesNo
ADAPTIVEAdapts based on task complexityNoNo
DEBATEMembers discuss and debate to consensusNoNo
ROUND_ROBINMembers take turns adding perspectiveNoYes

Builder

Use the fluent builder to create a team by specifying its name, mission, formation, and members with their roles.

Team team = Team.builder()
    .name("Analysis Team")
    .mission("Analyze customer data and produce insights")
    .timeout(Duration.ofMinutes(30))
    .formation(TeamFormation.PARALLEL)
    .lead(coordinatorAgent)
    .member(analystAgent, TeamRole.EXPERT)
    .member(writerAgent, TeamRole.MEMBER)
    .member(reviewerAgent, TeamRole.REVIEWER)
    .autoStart(true)
    .build();

When HIERARCHICAL formation is used and no LEAD is explicitly set, the first member is auto-promoted.

Pipeline

A Pipeline processes data through a series of stages in strict order, where each stage's output becomes the next stage's input. This is ideal for ETL (extract-transform-load) workflows or any process with a fixed sequence of steps. Includes per-stage metrics tracking.

PipelineOrganization pipeline = PipelineOrganization.builder()
    .name("ETL Pipeline")
    .addStage("extract", extractorAgent)
    .addStage("transform", transformerAgent)
    .addStage("validate", validatorAgent)
    .addStage("load", loaderAgent)
    .autoStart(true)
    .build();

Stage Record

A stage represents one step in the pipeline, linking a name to an agent. Each stage is a record Stage(String name, String agentId, int index, UnaryOperator<String> transformFunction). The optional transformFunction preprocesses input before the agent sees it.

PipelineMetrics

The pipeline automatically tracks how long each stage takes, how often it runs, and how often it fails. This helps you identify bottlenecks in your processing chain.

PipelineMetrics metrics = pipeline.getMetrics();

// Per-stage stats
Optional<Duration> avgDuration = metrics.getAverageDuration("transform");
int executions = metrics.getExecutionCount("transform");
int failures = metrics.getFailureCount("transform");

// Bottleneck detection
Optional<String> bottleneck = metrics.getBottleneck(); // stage with highest avg duration

// Full summary
Map<String, String> summary = metrics.getSummary();
// {"extract": "executions=10, failures=0, avgMs=250", ...}

HubSpoke

In a HubSpoke topology, one central "hub" agent distributes tasks to multiple "spoke" agents that do the actual work. This is useful when you have a coordinator that needs to fan out work to a pool of workers. The hub distributes tasks to spoke agents using configurable load balancing.

HubSpoke hs = HubSpoke.builder()
    .name("Task Distributor")
    .hub(coordinatorAgent)
    .spoke(worker1)
    .spoke(worker2)
    .spoke(worker3)
    .loadBalancing(LoadBalancer.Strategy.LEAST_LOADED)
    .autoStart(true)
    .build();

LoadBalancer Strategies

The load balancer decides which spoke agent gets the next task. Choose the strategy that best fits your workload pattern.

StrategyDescription
ROUND_ROBINCycles through spokes in order
LEAST_LOADEDPicks spoke with fewest active tasks
RANDOMRandom spoke selection

The LoadBalancer tracks active task counts per agent via recordTaskAssigned() and recordTaskCompleted().

Hierarchy

A Hierarchy models a tree-structured organization chart where tasks flow downward through delegation and issues flow upward through escalation. This is useful for modeling management structures or any scenario where agents have parent-child reporting relationships.

Hierarchy hierarchy = Hierarchy.builder()
    .name("Engineering Org")
    .root(ctoAgent)
    .member(ctoAgent, teamLead1)
    .member(ctoAgent, teamLead2)
    .member(teamLead1, dev1)
    .member(teamLead1, dev2)
    .member(teamLead2, dev3)
    .autoStart(true)
    .build();

DelegationChain

The DelegationChain records the history of who delegated what to whom, and who escalated issues back up the chain. This provides an audit trail for task flow through delegation and escalation events.

DelegationChain chain = hierarchy.getDelegationChain();
chain.record("cto", "team-lead-1", "Review PR #42", DelegationChain.Type.DELEGATION);
chain.record("dev-1", "team-lead-1", "Need architecture review", DelegationChain.Type.ESCALATION);

List<DelegationChain.Entry> entries = chain.getEntries();
// Each entry: fromAgentId, toAgentId, task, type, timestamp

Swarm

A Swarm is a decentralized topology inspired by biological swarm intelligence (like ant colonies or bird flocks). Instead of a central coordinator, agents communicate indirectly through "pheromones" and local neighbor interactions to solve problems collectively.

Swarm swarm = Swarm.builder()
    .name("Explorer Swarm")
    .behavior(SwarmBehavior.EXPLORATION)
    .intelligence(SwarmIntelligence.antColony(0.5, 0.3))
    .neighborDetection(NeighborDetection.random())
    .neighborRadius(5)
    .pheromoneDecay(0.15)
    .add(agent1, agent2, agent3, agent4, agent5)
    .build();

SwarmBehavior

The behavior determines how swarm agents interact with each other and their environment. Different behaviors suit different problem types.

BehaviorUses PheromonesRequires NeighborsBest For
EXPLORATIONYesNoInformation gathering, search
FORAGINGYesYesResource collection, optimization
FLOCKINGNoYesCoordinated movement
AGGREGATIONYesYesConsensus building, clustering
TASK_ALLOCATIONNoNoDivision of labor
DIFFUSIONNoYesDistributed computation
QUORUM_SENSINGNoYesCollective decision making

SwarmIntelligence

The swarm intelligence algorithm determines how individual agent results are combined into a collective answer. TnsAI provides several built-in algorithms:

SwarmIntelligence.voting()              // Simple voting, first complete solution wins
SwarmIntelligence.consensus()           // Weighted averaging (max 10 iterations)
SwarmIntelligence.bestSelection()       // Best-of-N based on quality scores
SwarmIntelligence.antColony(0.5, 0.3)   // ACO with pheromoneWeight and explorationRate
SwarmIntelligence.iterativeRefinement() // Each agent improves on previous (max 5 iterations)

PheromoneType

Pheromones are signals that agents leave behind to communicate indirectly with other agents. Different pheromone types convey different meanings.

TypeDefault IntensityPurpose
ATTRACTION1.0Marks interesting locations
REPULSION0.8Marks areas to avoid
TRAIL0.9Path markers for ACO
COMPLETION0.5Prevents redundant work
RECRUITMENT1.2Calls for help
WARNING0.7Signals potential issues
QUALITY1.0Indicates solution quality
CUSTOM1.0User-defined

Coalition

A Coalition is a temporary alliance of agents formed around a specific goal. Unlike a permanent team, a coalition forms dynamically, executes a task, distributes rewards based on each member's contribution, and then dissolves. This is useful when different tasks need different combinations of agents.

Coalition coalition = Coalition.builder()
    .goal("Complete market analysis")
    .formation(CoalitionFormation.CAPABILITY_BASED)
    .rewardDistribution(RewardDistribution.SHAPLEY)
    .coalitionValue(100.0)
    .minMembers(2)
    .maxMembers(5)
    .add(agent1, agent2, agent3)
    .autoNegotiate(true)
    .build();

CoalitionFormation

The formation strategy determines how agents are selected to join the coalition. Some strategies let agents volunteer, while others pick agents based on capabilities or reputation.

FormationSelection-BasedDescription
VOLUNTARYNoAgents choose to participate
CAPABILITY_BASEDYesSelected by matching capabilities
REPUTATION_BASEDYesSelected by past performance
AUCTIONNoAgents bid for participation
RANDOMNoRandom selection from pool
INVITATIONYesCoordinator invites specific agents
MERIT_BASEDYesCombined capability + reputation score

RewardDistribution

After the coalition completes its goal, rewards are distributed among members. The strategy determines how fairly (or competitively) the total reward is split.

StrategyDescription
EQUALSame share for all members
PROPORTIONALBased on contribution ratio
SHAPLEYFair division based on marginal contribution to all sub-coalitions
NUCLEOLUSMinimizes maximum dissatisfaction (10% floor + 90% proportional)
PERFORMANCE_BASEDBased on task performance quality
SENIORITY_BASEDHigher share for earlier joiners
WINNER_TAKE_ALLBest performer gets 70%, rest share 30%
Map<String, Double> contributions = Map.of("agent-1", 40.0, "agent-2", 35.0, "agent-3", 25.0);
Map<String, Double> rewards = RewardDistribution.SHAPLEY.calculate(100.0, contributions);

Matrix

A Matrix topology models a dual-reporting structure where each agent can belong to multiple groups simultaneously. For example, a developer agent might belong to both the "Engineering" dimension (reporting to an engineering lead) and the "Product-A" dimension (reporting to a product lead). This mirrors how real-world matrix organizations work.

MatrixOrganization matrix = MatrixOrganization.builder()
    .name("Product Org")
    .member(dev1)
    .member(dev2)
    .member(engLead)
    .member(productLead)
    .assign(dev1, "Engineering", engLead)
    .assign(dev1, "Product-A", productLead)
    .assign(dev2, "Engineering", engLead)
    .assign(dev2, "Product-B", productLead)
    .autoStart(true)
    .build();

Agents can be assigned to a dimension with or without a lead: .assign(agent, "QA") omits the lead parameter.

NetworkMesh

A NetworkMesh is a peer-to-peer topology where agents connect directly to each other without a central coordinator. The mesh shape (full, partial, ring, or star) determines which agents can communicate directly.

NetworkMesh mesh = NetworkMesh.builder()
    .name("Agent Network")
    .topology(Topology.FULL_MESH)
    .add(agent1, agent2, agent3, agent4)
    .autoStart(true)
    .build();

Topology

The topology shape determines the connection pattern between agents in the mesh.

TopologyDescription
FULL_MESHEvery agent connected to every other
PARTIAL_MESHSelective peer connections
RINGCircular chain
STAROne central agent connected to all others

After build(), initializeTopology() is called automatically to wire up connections based on the chosen topology.

On this page