Skip to content
Blog

Voting and Consensus Mechanisms Across Parallel Evaluator Agents

Mitigate model variance and hallucinations in critical AI decisions using parallel evaluator agents, majority voting, and Borda count consensus in Google ADK.

Published on • November 29, 2026

AI Assistant

In critical enterprise domains—such as medical diagnoses, financial loan underwriting, fraud detection, and regulatory compliance—relying on the output of a single language model turn introduces unacceptable variance. Even with low temperature settings, stochastic sampling can occasionally produce hallucinations, edge-case oversights, or biased evaluations.

In distributed computing and high-assurance systems, reliability is achieved through redundancy and consensus protocols (such as Raft or Byzantine Fault Tolerance). In agentic AI systems, we achieve similar resilience by employing Multi-Agent Consensus: fanning out an inquiry across multiple independent evaluator agents with differing prompts or temperature settings, followed by a deterministic voting arbitrator.

In this tutorial, we will build a consensus evaluation system in Google Agent Development Kit (ADK) using ParallelAgent, structured scoring schemas, and deterministic majority voting.


1. System Topology: The Consensus Ensemble

                          [Suspicious Transaction #8819]
                                        │
                                        ▼
┌────────────────────────────────────────────────────────────────────────┐
│ ParallelAgent: "evaluator_jury"                                        │
│                                                                        │
│   ┌────────────────────────────────────────────────────────────────┐   │
│   │ Evaluator A (Conservative Risk Profile, Temp 0.1) -> state["A"]│   │
│   └────────────────────────────────────────────────────────────────┘   │
│                                   ││                                   │
│   ┌───────────────────────────────┴┴───────────────────────────────┐   │
│   │ Evaluator B (Behavioral Biometrics Expert, Temp 0.3) -> state["B│  │
│   └────────────────────────────────────────────────────────────────┘   │
│                                   ││                                   │
│   ┌───────────────────────────────┴┴───────────────────────────────┐   │
│   │ Evaluator C (Regulatory Compliance Auditor, Temp 0.2) -> state[ │  │
│   └────────────────────────────────────────────────────────────────┘   │
└────────────────────────────────────────────────────────────────────────┘
                                        │
                                        ▼
┌────────────────────────────────────────────────────────────────────────┐
│ Deterministic Consensus Arbitrator (BaseAgent / Python Reducer)        │
│ - Tallies Votes: Flag Fraud (2) vs Approve (1)                         │
│ - Calculates Confidence Score (e.g., 66.7% agreement)                 │
│ - Emits Final Audited Decision                                         │
└────────────────────────────────────────────────────────────────────────┘

2. Choosing a Consensus Mechanism

Depending on your business requirements, choose the appropriate aggregation strategy:

  1. Strict Unanimity (3 of 3): Required for dangerous or irreversible actions (e.g., deleting production databases or initiating large wire transfers). If any single evaluator dissents, the action is blocked.
  2. Simple Majority (2 of 3 or 3 of 5): The standard choice for classification, content moderation, and ticket categorization.
  3. Borda Count / Weighted Average: Evaluators assign ranked scores (1 to 5) across multiple risk criteria; the option with the highest aggregate score wins.

3. Implementing the Evaluator Jury in Google ADK

Let’s define three distinct evaluator agents. To introduce healthy diversity into the jury, we give each agent a distinct persona and evaluation focus:

import json
from typing import Dict, Any, AsyncGenerator
from pydantic import BaseModel, Field
from google.genai import types as genai_types
from google.adk.agents import Agent, ParallelAgent, BaseAgent, SequentialAgent
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events import Event

# Define the structured verdict schema
class FraudVerdict(BaseModel):
    decision: str = Field(description="'APPROVE' or 'FLAG_FRAUD'")
    risk_score: int = Field(ge=0, le=100, description="Risk level from 0 (safe) to 100 (extreme danger)")
    reasoning: str = Field(description="Key factors driving the decision")

# Evaluator 1: Behavioral Risk Analyst
evaluator_a = Agent(
    name="evaluator_behavioral",
    model="gemini-3.8-flash",
    instruction="""
    You are a Fraud Analyst focusing on user behavioral patterns and geolocation anomalies.
    Inspect the transaction details. Output your verdict as valid JSON matching:
    {"decision": "APPROVE" | "FLAG_FRAUD", "risk_score": 0-100, "reasoning": "..."}
    """,
    generate_content_config=genai_types.GenerateContentConfig(temperature=0.1),
    output_key="verdict_a",
)

# Evaluator 2: Transaction Velocity Specialist
evaluator_b = Agent(
    name="evaluator_velocity",
    model="gemini-3.8-flash",
    instruction="""
    You are a Risk Engineer specializing in rapid transaction velocity and card testing attacks.
    Inspect the transaction details. Output your verdict as valid JSON matching:
    {"decision": "APPROVE" | "FLAG_FRAUD", "risk_score": 0-100, "reasoning": "..."}
    """,
    generate_content_config=genai_types.GenerateContentConfig(temperature=0.3),
    output_key="verdict_b",
)

# Evaluator 3: Financial Regulatory Auditor
evaluator_c = Agent(
    name="evaluator_regulatory",
    model="gemini-3.8-flash",
    instruction="""
    You are an AML (Anti-Money Laundering) Compliance Auditor looking for structuring and sanctions risks.
    Inspect the transaction details. Output your verdict as valid JSON matching:
    {"decision": "APPROVE" | "FLAG_FRAUD", "risk_score": 0-100, "reasoning": "..."}
    """,
    generate_content_config=genai_types.GenerateContentConfig(temperature=0.2),
    output_key="verdict_c",
)

# Parallel Jury Ensemble
jury_ensemble = ParallelAgent(
    name="fraud_jury_panel",
    sub_agents=[evaluator_a, evaluator_b, evaluator_c],
)

4. Building the Deterministic Arbitrator

The aggregation step should be deterministic Python logic, not an LLM turn. This prevents the aggregator from hallucinating a consensus that does not exist in the raw votes:

class DeterministicArbitrator(BaseAgent):
    """Tallies votes from the parallel evaluators and determines consensus."""

    async def _run_async_impl(
        self, ctx: InvocationContext
    ) -> AsyncGenerator[Event, None]:
        keys = ["verdict_a", "verdict_b", "verdict_c"]
        votes = []

        for key in keys:
            raw_text = ctx.session.state.get(key, "{}")
            try:
                # Clean possible markdown fences
                clean_json = raw_text.replace("```json", "").replace("```", "").strip()
                data = json.loads(clean_json)
                votes.append(data)
            except Exception:
                # Handle unparseable turn safely
                votes.append({"decision": "FLAG_FRAUD", "risk_score": 80, "reasoning": "Failed to parse verdict"})

        # Tally decisions
        decisions = [v.get("decision", "FLAG_FRAUD").upper() for v in votes]
        fraud_count = decisions.count("FLAG_FRAUD")
        approve_count = decisions.count("APPROVE")

        # Compute average risk score
        avg_risk = sum(v.get("risk_score", 50) for v in votes) / len(votes)

        # Determine consensus winner (Majority rule)
        final_decision = "FLAG_FRAUD" if fraud_count >= 2 else "APPROVE"
        agreement_ratio = max(fraud_count, approve_count) / len(votes)

        consensus_summary = {
            "final_decision": final_decision,
            "consensus_agreement": f"{agreement_ratio * 100:.1f}%",
            "votes_breakdown": {"FLAG_FRAUD": fraud_count, "APPROVE": approve_count},
            "average_risk_score": round(avg_risk, 1),
            "evaluator_rationales": [v.get("reasoning") for v in votes],
        }

        ctx.session.state["final_consensus_decision"] = consensus_summary

        result_message = (
            f"Consensus Verdict: {final_decision} ({fraud_count} vs {approve_count} votes)\n"
            f"Average Risk Score: {avg_risk:.1f}/100 | Agreement: {agreement_ratio * 100:.0f}%\n"
        )

        yield Event(author=self.name, content=result_message)

# Complete Pipeline: Parallel Jury -> Deterministic Arbitrator
consensus_system = SequentialAgent(
    name="consensus_fraud_pipeline",
    sub_agents=[jury_ensemble, DeterministicArbitrator(name="arbitrator")],
)

5. Running and Validating the Ensemble

import asyncio
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

async def main():
    session_service = InMemorySessionService()
    runner = Runner(agent=consensus_system, session_service=session_service)
    session = await session_service.get_or_create("tx_review_01")

    transaction_details = """
    Transaction Review:
    - User ID: usr_88219 (Account created 2 hours ago)
    - Amount: $4,999.00 USD
    - Payment Method: New Visa Card (Issued in Brazil)
    - IP Geolocation: Lagos, Nigeria
    - Device Fingerprint: Headless Chrome / Linux User-Agent
    - Velocity: 4 declined micro-transactions in the past 10 minutes
    """

    print("Submitting transaction to 3-agent jury...\n")
    async for event in runner.run_async(session=session, message=transaction_details):
        if event.author == "arbitrator":
            print(event.content)

    print("Detailed Consensus Summary:")
    print(json.dumps(session.state.get("final_consensus_decision"), indent=2))

if __name__ == "__main__":
    asyncio.run(main())

6. Enterprise Benefits of Agent Consensus

  1. Hallucination Suppression: The probability of three independent models hallucinating the identical factual error simultaneously is exponentially lower than a single model.
  2. Defensible Audit Trails: In regulated industries, printing the individual votes and rationales of multiple evaluators provides transparent compliance records.
  3. Graceful Disagreement Escalation: If consensus fails (e.g., in a 5-agent panel with a 2-2-1 split), the arbitrator can automatically escalate the case to human reviewers.

Takeaway: Combining Google ADK’s ParallelAgent with deterministic voting arbitration eliminates single-model blind spots in high-stakes automated decisions.

Sources