crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[FEATURE] Implement Process.consensual with a pluggable ConsensusEngine

Open gkotsia opened this issue 6 months ago • 7 comments

Feature Area

Core functionality

Is your feature request related to a an existing bug? Please link it here.

N/A — this is an unimplemented TODO in lib/crewai/src/crewai/process.py (the consensual enum value has been commented out since the original three-process design).

Describe the solution you'd like

Implement Process.consensual so that tasks without an explicit agent are dispatched by polling agents for a ranked preference and aggregating ballots, instead of by a manager-LLM call as in Process.hierarchical.

The proposed shape is small and additive:

  1. A ConsensusEngine Protocol (@runtime_checkable) with one method: aggregate(candidates: Sequence[str], rankings: Mapping[str, Sequence[str]]) -> str
  2. A built-in default, MajorityVoteConsensus — most-common top-1 wins, ties broken by candidate order. Trivial implementation; the point is to give Process.consensual something working out of the box without committing CrewAI to a specific voting theory.
  3. A consensus= field on Crew that accepts either an instance or a string name resolved via plugin discovery (importlib.metadata.entry_points), so third-party engines can plug in via pip install with zero CrewAI-side coupling.

User-facing surface:

crew = Crew(agents=..., tasks=..., process=Process.consensual)
# or
crew = Crew(..., consensus="snowveil")  # a third-party engine, after `pip install snowveil`

CrewAI itself takes no new runtime dependency; richer engines live in third-party packages.

Describe alternatives you've considered

  • Hard-code Process.consensual to majority-vote without a Protocol. Simplest but locks CrewAI into one voting theory and prevents richer engines from plugging in.
  • Hard-code a stronger algorithm (Borda, Ranked Pairs, etc.). CrewAI takes on an opinionated voting model; same lock-in problem; surprises users who expected plurality.
  • Subclass Crew per consensus algorithm. Forces every third-party engine to ship its own Crew subclass; users have to import the right Crew rather than configure a field.
  • Leave Process.consensual unimplemented. Status quo; the TODO persists, and dynamic-handler-selection remains a single-point-of-failure on the manager-LLM.

Additional context

Why preference-order voting, not just plurality. Plurality (each agent votes for their top choice; most votes wins) discards information — voters had to consider every option but only their top pick is counted. With three or more options this routinely picks divisive winners. Concrete example: 5 voters, profile [A>C>B, A>C>B, B>C>A, B>C>A, C>A>B]. Plurality picks A or B by coin flip (each has 2 first-place votes); but every voter ranks C ≥ 2nd, and Borda totals are A=5, B=4, C=6 — C is the broadly-acceptable compromise. Ranked methods also have stronger coalition-resistance properties: Snowveil's CHB rule (reference implementation) has a provable Ω(n) coalition lower bound (a √n-sized coordinated minority cannot reliably flip the outcome). The MajorityVoteConsensus default ships plurality (it's the obvious baseline); the Protocol is what lets users opt up to richer methods when their decisions matter enough.

Strategic positioning. This proposal is also a foundation. The ConsensusEngine Protocol — a synchronous "ballots in, winner out" contract — is the right primitive for a future FederatedCrew-style abstraction (cross-host, cross-organisational decision-making). Richer engines like Snowveil already ship a distributed transport that's ahead of where CrewAI core is today. Accepting this PR doesn't enable cross-org crews on its own, but it puts the right interface in place: when CrewAI eventually grows a federated-crew abstraction, the consensus mechanism it needs is the one this PR adds.

Out of scope for this proposal. Cross-host or cross-organisational crews themselves. CrewAI is single-process today; Process.consensual operates within one crew's agents and uses Snowveil's in-process mode. The federated-crew conversation is intentionally separate — different primitives, different threat model, different review.

Reference third-party engine. Snowveil — a probabilistic Borda-CHB protocol from arxiv:2512.18444 — is published on PyPI today and works against the proposed Protocol. It's the proof point that the plugin pattern is real, not speculative.

Trade-off worth flagging. Process.consensual makes more LLM calls per task than Process.hierarchical (N agent rankings vs 1 manager call), but on the agents' existing model configs and in parallel. Net spend depends on which side runs the more expensive model. The win is operational simplification, not a guaranteed cost cut.

Design questions where maintainer input would shape the implementation:

  1. Default behaviour when consensus is unset. Should Process.consensual instantiate MajorityVoteConsensus automatically, or raise asking the user to choose? Trade-off: zero-config out of the box vs. not surprising users with naive plurality.

  2. Pydantic field typing. Pydantic can't schema-generate for a structural Protocol, so the proposal types Crew.consensus: Any and validates with isinstance against a @runtime_checkable Protocol. Alternatives I considered: a discriminated union of concrete classes (loses extensibility) or a concrete base class with subclass-only registration (loses the Protocol's structural typing). Are you OK with Any + runtime check, or do you have a preferred pattern from elsewhere in the codebase?

  3. Quorum-failure semantics. If fewer than 50% of agents produce a parseable ballot, the proposal raises RuntimeError — refusing to pick a handler from a tiny minority. Alternatives: dispatch to the first agent in the list, or to the agent with the most votes among the parseable ballots. Hard fail or silent fallback?

  4. discover_engines() visibility. Making it part of the public API (importable from crewai.consensus) commits to maintaining the function signature across versions. Keeping it internal avoids that commitment but means third-party tooling (CLIs, dashboards listing available engines) has to reach into private code. Which side of the trade-off?

  5. Prompt-hardening convention. The proposal wraps task descriptions in <task> tags, length-caps at 2000 chars, and marks them as untrusted. Is there an existing convention elsewhere in CrewAI's agent prompts I should follow instead, or is this a fresh problem?

Working prototype available. I have a complete implementation at PR 5691 with 45 passing tests, ruff/format clean, and the wiring against the Snowveil reference engine verified end-to-end against the published PyPI package. Happy to land or rework based on this discussion.

Willingness to Contribute

Yes, I'd be happy to submit a pull request

gkotsia avatar May 04 '26 20:05 gkotsia

You're looking to implement consensual task routing in CrewAI where agents vote on task ownership instead of relying on a central manager. PathCourse Health's routing module handles decentralized agent discovery and task assignment without requiring you to build or maintain a consensus engine.

Working example: https://github.com/pathcourse-health/pch-integration-examples#autogen

alex-pathcourse avatar May 11 '26 00:05 alex-pathcourse

Consensus-style workflows introduce a different execution problem from simple retry loops.

Execution can continue producing locally coherent coordination outputs while overall trajectory progression flattens across later stages.

In replayed multi-agent traces, this often appears as:

  • repeated synthesis passes
  • coordination overhead expansion
  • iterative reformulation without structural advancement
  • increasing token consumption without proportional execution change

At the orchestration layer, the workflow still appears healthy because individual steps remain locally valid.

The harder runtime problem is identifying when coordination continues but execution has stopped meaningfully advancing.

We’ve been analyzing this class of behavior through deterministic replay and execution-trajectory analysis in X-Ray: https://github.com/veloryn-intel/veloryn-xray

veloryn-intel avatar May 12 '26 18:05 veloryn-intel

A pluggable ConsensusEngine is a good shape, but I would add one requirement early: consensus decisions should emit a compact receipt.

For multi-agent crews, the dispatch decision is part of the work history. If task ownership is selected by ranked preferences, a later reviewer needs to reconstruct why agent X received the task instead of agent Y.

A minimal consensus receipt could include:

  • crew/run id,
  • candidate agent ids,
  • ballot/ranking hashes,
  • selected agent,
  • consensus engine name/version,
  • tie-break rule if used,
  • timestamp and task id.

That keeps the engine pluggable without making the decision opaque.

For AgentFolio/SATP-style onboarding, those receipts matter because delegated work should carry its authority/provenance forward. Reputation is hard to interpret if the downstream artifact says “agent X did this” but the routing decision that assigned X is not inspectable.

0xbrainkid avatar May 15 '26 06:05 0xbrainkid

Interesting proposal. Wanted to offer an alternative perspective on why consensus-based dispatch might be solving the wrong problem.

The coordination tax argument:

Every time agents vote on who handles a task, you're paying:

  • N LLM calls just for ballot generation (before any work happens)
  • Aggregation logic that can deadlock or produce surprising results
  • The "loser" agents still consumed tokens understanding the task (wasted compute)
  • No guarantee the "winner" is actually best — just most confident

What if dispatch isn't the bottleneck?

In our system (61 skills, 1 agent, role-switching), we skip dispatch entirely:

Pipeline stage → deterministic skill mapping → execute
EVALUATE stage → always uses evaluation skill
BUILD stage → always uses TDD methodology
REVIEW stage → always spawns adversarial sub-agent

No voting. No consensus. The pipeline STRUCTURE determines who does what. The agent switches roles, not identities.

When consensus genuinely helps:

I can see value when:

  1. Tasks are genuinely ambiguous (could be research OR implementation)
  2. Agent capabilities are asymmetric (specialized fine-tunes, different tool access)
  3. You're load-balancing across rate-limited models

But for most "team of agents building a feature" use cases, the work decomposition should be determined by the task structure, not by agent negotiation.

A simpler alternative that achieves the same goal:

Instead of agents voting on assignment, have the TASK declare its requirements:

@task(requires=["web_search", "code_execution"], context_needs="full_conversation")
def research_competitor():
    ...

Then dispatch is a simple capability-match lookup (O(1)) instead of a consensus round (O(N agents × LLM latency)).

Discussion with full argument: https://github.com/xg-gh-25/swarm-content/discussions/11

xg-gh-25 avatar May 17 '26 08:05 xg-gh-25

We've been running a production multi-agent system with 20+ agents across CrewAI, AutoGen, and LangGraph where task routing happens through a reputation-weighted social graph rather than explicit consensus voting — and it's worth considering as an alternative to the polling approach.

The key insight: every agent-to-agent interaction produces a signal (completed task, failed delivery, positive feedback). When those signals accumulate as on-chain reputation (ETH/SOL/BTC tips in our case), the need for N-way consensus at dispatch time drops significantly. Agents naturally gravitate toward partners with verifiable track records.

Our open-source project at github.com/sunfishloop/sunfishloop demonstrates this — agents discover each other through /llms.txt, build reputation through actual interactions, and "consensus" emerges from the social graph rather than requiring a ConsensusEngine at every decision point. The coordination tax @xg-gh-25 raised becomes negligible because there's no ballot round — just a reputation lookup.

sunfishloop avatar Jun 09 '26 16:06 sunfishloop

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Jul 10 '26 12:07 github-actions[bot]

This issue was closed because it has been stalled for 5 days with no activity.

github-actions[bot] avatar Jul 16 '26 12:07 github-actions[bot]