Skip to content

v2.0: Agent Swarms with Emergent Specialization — market-based role negotiation #734

Closed

Description

@AmitoVrito

Summary

Extend AgentFederation so agents negotiate roles dynamically via an internal market: each agent bids on incoming tasks based on its historical cost/quality from CostQualityRouter. Roles emerge from the market, not from hardcoded orchestration graphs.

Motivation

Today's multi-agent frameworks (CrewAI, AutoGen, our own AgentFederation) require humans to pre-assign roles. This is brittle: as the agent fleet grows, role assignments become stale. A market mechanism self-organizes the team and naturally exploits the strongest specialist for each task.

Design Sketch

from synapsekit import AgentSwarm, MarketPolicy, BidStrategy

swarm = AgentSwarm(
    agents=[researcher, coder, critic, planner, summarizer, ...],
    market=MarketPolicy(
        bid_strategy=BidStrategy.cost_quality_pareto(),
        auction_type=\"sealed_bid\",
        budget_per_task=10_000,  # tokens
        learning_rate=0.1,  # how fast agents update bids from outcomes
    ),
    registry=AgentRegistry.redis(\"redis://...\"),
)

result = await swarm.execute(\"Write a market analysis on quantum compute startups\")
# Swarm dynamically assembles: planner -> 3 researchers -> critic -> summarizer
# Bids logged. Winners' bid models update from final reward.

Mechanism

  1. Task broadcast — task posted to swarm with budget
  2. Bid — each agent submits (estimated_cost, estimated_quality, confidence) using its own CostQualityRouter history
  3. Auction — MarketPolicy selects winner(s) — supports single-winner, multi-winner (parallel), and coalition (cooperative) modes
  4. Execute — winner runs, emits result + actual cost
  5. Settle — actual reward updates each agent's bid model (online learning)
  6. Reputation — AgentRegistry tracks per-agent track record per task category

Components

  • AgentSwarm orchestrator
  • MarketPolicy (auction types: sealed-bid, English, Vickrey)
  • BidStrategy interface (cost-quality, Thompson sampling, UCB)
  • AgentBidder mixin — adds .bid(task) -> Bid to any agent
  • Reputation store — Redis-backed, per-(agent, task_category) Bayesian posterior
  • CoalitionFormer — agents bid as teams for tasks beyond any single agent
  • Visualization: swarm.trace_to_mermaid() — show which agent won which sub-task

Use Cases

  • Heterogeneous fleets (GPT-4o + Claude Opus + local Llama) where each excels at different things
  • Cost-bounded research where the market routes to the cheapest sufficient agent
  • Emergent specialization: agents that consistently win "code review" tasks become the de-facto reviewers without being labeled as such

Risks

  • Cold start — new agents have no bid history. Mitigate with optimistic priors + epsilon-greedy exploration.
  • Collusion / runaway bidding — bound bids to budget; cap concentration (no single agent > 70% of tasks).
  • Cost of the auction itself — keep bid evaluation O(N), cache reputation lookups

Acceptance Criteria

  • Demo: 5-agent swarm outperforms hardcoded AgentFederation on a 100-task benchmark by ≥15%
  • Cost reduction ≥25% vs. always-route-to-best-model baseline
  • Live dashboard via PrometheusMetrics: bids/sec, win rate per agent, avg reward
  • Determinism mode for testing (market.seed=42)
  • Replayable role-allocation receipt (h/t @clementineCU) — every auction emits an AgentSwarmReceipt that can be replayed without trusting the final answer, built in two phases so the reputation prior is never overwritten before it's recorded:
    • Auction-time fields (captured before record_outcome() runs): task_id, candidate agent ids, bid inputs each agent was allowed to see, reputation prior version (the exact snapshot bids were scored against), selected role, rejected roles, budget allocated.
    • Settlement-time fields (captured after execution): budget consumed, outcome_score_source (external_override vs. self_reported — collapsed to a two-way grounded/ungrounded split, since agent-returned output fields aren't meaningfully more trustworthy than the bid's own estimate), and learning_rule_version.
    • Grounding is tracked, not silently trusted: a winning agent's own estimated_quality/output-reported quality may appear in the receipt as evidence, but the ReputationSnapshot it produces is tagged grounded=False unless an externally-supplied reward/quality override was passed to execute(). Ungrounded updates still persist (preserves online learning with no external judge wired up) but are discounted/filterable downstream. Hard-refusing ungrounded updates is opt-in via MarketPolicy.require_grounded_reward=True, not the default.
    • Spec test: tests/agents/test_agent_swarm_receipt.py::test_auction_receipt_is_replayable_without_trusting_final_answer (currently xfail; extend with the grounded/ungrounded invariant before removing the marker).

Related

Activity

  1. added
    enhancement
    v2.0
    research
    agents
    on Jun 25, 2026
  2. added this to the v2.0.0 milestone on Jun 25, 2026
  3. added
    v2.0.1
    and removed
    v2.0
    on Jul 18, 2026
  4. modified the milestones: v2.0.0, v2.0.1 on Jul 18, 2026
  5. clementineCU commented on Jul 18, 2026

    @clementineCU

    One acceptance test I would add: every auction should emit a role-allocation receipt that can be replayed without trusting the final answer.

    Minimum fields: task_id, candidate agents, bid inputs each agent was allowed to see, cost/quality prior version, bid value, selected role, rejected roles, budget consumed, outcome score source, and the rule that updates future bids.

    That keeps emergent specialization inspectable. If an agent wins because the learning rule drifted, a reviewer can see whether the market learned from a real outcome or just reinforced a stale/self-reported score.

  6. self-assigned this
    on Jul 18, 2026
  7. AmitoVrito commented on Jul 18, 2026

    @AmitoVrito
    CollaboratorAuthor

    Status update (2026-07-18) — retargeted to v2.0.1

    Same picture as #735: the mechanism is fully built, not unstarted.

    Done

    • AgentSwarm orchestrator, MarketPolicy, BidStrategy, AuctionType, AgentBidder protocol
    • Sealed-bid auction + multi-winner + CoalitionFormer (cooperative bidding, deterministic combo selection)
    • Reputation store (in-memory) + RedisReputation — both implemented in agent_registry.py, matches AgentFederation/AgentRegistry (feat: distributed agent registry and federation #718) pattern
    • Determinism mode — MarketPolicy.seed wired through to random.Random(seed)
    • swarm.trace_to_mermaid() visualization
    • examples/agent_swarm_market.py demo
    • 18 passing tests in tests/agents/test_agent_swarm_market.py

    Remaining

    1. 100-task benchmark vs. hardcoded AgentFederation — no benchmark harness exists proving the swarm beats hardcoded orchestration by ≥15%. This is the acceptance criterion with zero code against it.
    2. Cost reduction ≥25% vs. always-route-to-best-model baseline — same gap, no baseline comparison built.
    3. Live PrometheusMetrics dashboard (bids/sec, win rate per agent, avg reward) — no wiring between AgentSwarm/Reputation and PrometheusMetrics yet; grepped observability/ and found nothing referencing swarm.

    Net: like #735, this is a benchmark + observability-wiring PR, not a from-scratch build. The market mechanism itself (auction, bidding, coalition, reputation, Redis backend) is done and tested.

  8. AmitoVrito commented on Jul 18, 2026

    @AmitoVrito
    CollaboratorAuthor

    @clementineCU this is a valid and important gap — thanks for flagging it.

    I checked the code: it's not just theoretical. _actual_quality() (agent_swarm.py) falls back to the winning agent's own estimated_quality from its bid when no external quality/reward is supplied at execute time — so today the reputation store can update purely from an agent grading its own bid, with no external grounding. That's exactly the "market learned from a real outcome vs. reinforced a stale/self-reported score" risk you're describing.

    Added it as an acceptance criterion above, and wrote a spec test (tests/agents/test_agent_swarm_receipt.py, currently xfail since the receipt fields don't exist yet) capturing the minimum fields you listed: task_id, candidate agents, bid inputs, reputation prior version, selected/rejected roles, budget consumed, outcome score source, and the learning rule version.

    Would you like to take this one?

  9. AmitoVrito commented on Jul 18, 2026

    @AmitoVrito
    CollaboratorAuthor

    Spec test committed: tests/agents/test_agent_swarm_receipt.py (commit e772e8c, xfail pending implementation). Acceptance criteria list above is up to date.

  10. clementineCU commented on Jul 18, 2026

    @clementineCU

    Thanks for turning it into a spec test. I would keep this as a maintainer-owned implementation, but the clean shape I would use is:

    1. Emit an AgentSwarmReceipt at the auction boundary, before the reputation update path runs.
    2. Bind the receipt to the exact learning input: task_id, candidate agent ids, visible bid inputs, reputation/prior version, selected role, rejected roles, budget consumed, outcome_score_source, and learning_rule_version.
    3. Treat outcome_score_source=self_reported_bid as an explicit degraded source, not a normal success path. The reputation update should either refuse, no-op, or mark the update as ungrounded unless an external reward/quality signal is supplied.
    4. Add the invariant to the xfail test: a winning agent's own estimated_quality may appear in the receipt as evidence, but it cannot be the only source that advances reputation without being labeled self-reported.

    That gives reviewers the thing the market needs most: not just "who won", but whether the market learned from an external outcome or from its own stale prior.

  11. AmitoVrito commented on Jul 18, 2026

    @AmitoVrito
    CollaboratorAuthor

    @clementineCU makes sense, and it's aligned with the direction — a few responses:

    Agreed, and this is more than style — it's a correctness fix: building the receipt at the auction boundary, before record_outcome() runs, isn't optional. Checked the code again: _score_bids() reads reputation.get(...) at auction time, then record_outcome() later mutates that same store. If the receipt were assembled after settlement, reputation_prior would show the post-update snapshot, not the one bids were actually scored against. So in practice the receipt needs two write points, not one atomic emission: auction-time (candidates, bids, prior, selected/rejected roles, budget allocated) and settlement-time (budget consumed, outcome_score_source, actual reward) — same fields you listed, just acknowledging they land at different moments.

    Agreed on the field list — matches what's already in the acceptance criteria and the xfail test.

    Pushback on refuse/no-op as the default: I'd split "label as degraded" (yes, unconditionally) from "block the reputation update" (not by default). The issue's own design sketch wants online learning without requiring an external judge for every task — most callers won't wire up independent grading, so hard-refusing self-reported outcomes by default means the swarm mostly never learns, which undercuts the emergent-specialization pitch. Proposal instead: always persist the update, but tag the ReputationSnapshot with grounded=False provenance so it can be discounted, filtered, or weighted down by a stricter learning rule downstream. Hard refusal becomes an opt-in MarketPolicy.require_grounded_reward=True for audited/regulated deployments, not global default behavior.

    One addition to your source taxonomy: "extracted from output" isn't necessarily more trustworthy than the bid fallback — it's still the same agent self-reporting a quality/score key in its own return value, just at finer granularity. Nothing stops an agent from always returning {"quality": 1.0}. Only an explicit caller-supplied override (independent eval/judge) is actually externally grounded. Worth being precise that it's a two-way split (grounded vs. self-reported), not three tiers of decreasing trust.

    Agreed on the test invariant — will extend the xfail test so a winning agent's own estimated_quality can appear in the receipt as evidence but can never advance reputation as grounded=True on its own.

    Since you're not taking implementation, I'll own it — will fold this into the receipt spec (two-phase emission, grounded flag, opt-in strict mode) before scoping the actual PR.

  12. added a commit that references this issue on Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

agentsenhancementresearchv2.0.1

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions