cd /news/ai-agents/building-a-multi-agent-verification-… · home › topics › ai-agents › article
[ARTICLE · art-177262] src=machinelearningmastery.com ↗ pub= topic=ai-agents verified=true sentiment=· neutral

Building a Multi-Agent Verification Loop in Python with Small Open Models

A Proposer-Critic-Judge verification loop can be built in Python on a single 4-bit quantized Qwen2.5-7B-Instruct model using persona multiplexing, letting one model play all three roles on a Google Colab Nvidia T4 GPU with 16GB of VRAM. The approach avoids the out-of-memory error that loading three separate models would cause, and the article instruments each step to compare the loop's latency and token usage against a single-agent baseline. The stated goal is to measure whether the extra accuracy from the multi-agent loop justifies its added latency and token cost.

recommendation

Use persona multiplexing—one 4-bit quantized model with swapped system prompts—to run Proposer, Critic and Judge roles when VRAM can't hold three models, and instrument each step's latency and tokens against a single-agent baseline.

more in playbook: Designing agent systems
by read9 min views4 publishedNov 27, 2026
Building a Multi-Agent Verification Loop in Python with Small Open Models
Image: source

In this article, you will learn how to build a Proposer-Critic-Judge verification loop in Python with a single small open model, and how to measure what the extra accuracy costs in latency and tokens.

Topics we will cover include:

  • How the Proposer, Critic, and Judge roles divide the work of generating, verifying, and finalizing an answer.
  • How persona multiplexing lets one 4-bit quantized Qwen2.5-7B-Instruct model play all three roles on a Colab T4 GPU.
  • How to instrument each step to compare the loop’s latency and token usage against a single-agent baseline.

Introduction #

The AI landscape is dominated by multi-agent frameworks, with prominent actors such as AutoGen and LangGraph at the center of the stage. This brings the promise of high-accuracy solutions, but sequentially stacking LLMs (large language models) introduces an issue: a “token tax”, in the form of computational cost and compounding latency that worsens with each node added to your framework’s graph.

Thus, the challenge is not only about wiring agents together, but rather proving that the coordination overhead pays off. This article shows the building blocks to construct a multi-agent verification loop, concretely under a Proposer-Critic-Judge approach. We will run a Python notebook aided by a small open-source language model, instrumenting it to measure the extent to which latency losses are worth accuracy wins.

The Proposer, Critic, Judge Architecture #

The Proposer, Critic, Judge architecture is a design pattern that has gained relevance in multi-agent systems. It is characterized by separating three cognitive roles or steps:

  • Proposer: this is the agent that receives the raw user prompt or requested task and acts as the domain expert that generates a preliminary, unverified solution or response.
  • Critic: the rigorous member of the team. It is responsible for verifying the proposer’s solution to the user prompt. The critic is also tasked with calculating the answer independently beforehand, so it can compare it to the proposer’s.
  • Judge: the judge is like a “final executive” that takes the prompt, the proposer’s response, and the subsequent critique to synthesize everything into a final, likely correct answer.

Python Implementation #

Running the three models underlying the agents simultaneously has massive memory requirements, even on Google Colab’s Nvidia T4 GPU environment. To avoid a nearly instant out-of-memory error while the three models, we will use persona multiplexing: this consists of one highly capable baseline model, such as Qwen2.5-7B-Instruct, with 4-bit quantization. After that, its system prompts — infused with each of the three aforesaid roles — are dynamically swapped to switch the model’s behavior.

Before that, you may need to pip install some libraries — if running this on Google Colab, you will only need to explicitly install bitsandbytes, but be sure to switch the runtime to a GPU:

!pip install -q -U transformers accelerate bitsandbytes torch

1

!pip install -q -U transformers accelerate bitsandbytes torch

The first step is to download our target model and shrink it using 4-bit quantization to fit it on Colab’s GPU.

import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

model_id = "Qwen/Qwen2.5-7B-Instruct"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map="auto",
    quantization_config={"load_in_4bit": True, "bnb_4bit_compute_dtype": torch.float16}
)
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)

1234567891011121314

import timeimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, pipeline # 1.  the Model in 4-bit to fit Colab's 16GB T4 VRAMmodel_id = "Qwen/Qwen2.5-7B-Instruct" tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained(    model_id,    device_map="auto",    quantization_config={"load_in_4bit": True, "bnb_4bit_compute_dtype": torch.float16})pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)

We then build a custom function called generate_and_measure(). This function acts as a measuring tape for our use case, interacting with the model while it secretly runs a token counter and a stopwatch behind the scenes. In other words, the exact cost of each prompt will be carefully tracked.

def generate_and_measure(system_prompt, user_content):
    start = time.time()

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_content}
    ]

    prompt_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    in_tokens = len(tokenizer.encode(prompt_text))

    outputs = pipe(prompt_text, max_new_tokens=256, temperature=0.3, do_sample=True)
    response = outputs[0]["generated_text"].split("<|im_start|>assistant\n")[-1].replace("<|im_end|>", "").strip()

    out_tokens = len(tokenizer.encode(response))
    latency = time.time() - start

    return response, {"in_tokens": in_tokens, "out_tokens": out_tokens, "latency": latency}

12345678910111213141516171819

The next step is where we define the three different “hats” to be worn by our single model, i.e. the three system messages for the Proposer-Critic-Judge protocol.


PROPOSER_SYS = "You are a helpful assistant. Solve the user's task directly and concisely."

CRITIC_SYS = """You are a rigorous mathematical verifier.
You must NOT accept the Proposed Solution at face value.
First, independently calculate the answer to the problem step-by-step.
Second, compare your calculated answer to the Proposed Solution.
If the Proposed Solution's math or logic is wrong, explain exactly why it failed based on your math.
If it is perfectly correct, output ONLY 'No flaws found.'"""

JUDGE_SYS = """You are the final output generator. Review the original task, the proposal, and the critique.
If the critique says 'No flaws found', output the original proposal exactly.
If the critique corrects the math, output the corrected answer clearly and concisely."""

123456789101112131415

Now it’s time to wire the three system messages together into an automated assembly workflow. After that, we finalize by performing a targeted test consisting of a tricky question:

def run_verification_loop(task_prompt):
    print(f"--- TASK: {task_prompt} ---\n")

    prop_out, prop_metrics = generate_and_measure(PROPOSER_SYS, task_prompt)
    print(f"PROPOSER (Baseline):\n{prop_out}\n")

    critic_prompt = f"Problem: {task_prompt}\n\nProposed Solution:\n{prop_out}"
    crit_out, crit_metrics = generate_and_measure(CRITIC_SYS, critic_prompt)
    print(f"CRITIQUE:\n{crit_out}\n")

    judge_prompt = f"Problem: {task_prompt}\n\nProposal:\n{prop_out}\n\nCritique:\n{crit_out}"
    judge_out, judge_metrics = generate_and_measure(JUDGE_SYS, judge_prompt)
    print(f"FINAL JUDGMENT:\n{judge_out}\n")

    total_latency = prop_metrics['latency'] + crit_metrics['latency'] + judge_metrics['latency']
    total_tokens = sum(m['in_tokens'] + m['out_tokens'] for m in [prop_metrics, crit_metrics, judge_metrics])

    print("--- METRICS ---")
    print(f"Baseline (1 Agent) -> Latency: {prop_metrics['latency']:.2f}s | Total Tokens: {prop_metrics['in_tokens'] + prop_metrics['out_tokens']}")
    print(f"Multi-Agent Loop   -> Latency: {total_latency:.2f}s | Total Tokens: {total_tokens}")
    print(f"Overhead           -> {total_latency / prop_metrics['latency']:.1f}x slower, {total_tokens / (prop_metrics['in_tokens'] + prop_metrics['out_tokens']):.1f}x token tax")

target_task = "Bob is 20 years old. Alice is half Bob's age. When Bob is 100 years old, how old will Alice be? Answer concisely."

run_verification_loop(target_task)

12345678910111213141516171819202122232425262728293031

Output:

--- TASK: Bob is 20 years old. Alice is half Bob's age. When Bob is 100 years old, how old will Alice be? Answer concisely. ---

PROPOSER (Baseline):
When Bob is 100 years old, Alice will be 50 years old.

CRITIQUE:
No flaws found.

Explanation of the calculation:
- Initially, Bob is 20 years old and Alice is half his age, so Alice is 10 years old.
- The age difference between Bob and Alice is 20 - 10 = 10 years.
- This age difference remains constant over time.
- When Bob is 100 years old, the age difference still applies, so Alice will be 100 - 10 = 90 years old.

The proposed solution incorrectly states that Alice will be 50 years old when Bob is 100, which does not account for the constant age difference between them.

FINAL JUDGMENT:
When Bob is 100 years old, Alice will be 90 years old.

--- METRICS ---
Baseline (1 Agent) -> Latency: 2.63s | Total Tokens: 85
Multi-Agent Loop   -> Latency: 16.67s | Total Tokens: 660
Overhead           -> 6.3x slower, 7.8x token tax

1234567891011121314151617181920212223

--- TASK: Bob is 20 years old. Alice is half Bob's age. When Bob is 100 years old, how old will Alice be? Answer concisely. --- PROPOSER (Baseline):When Bob is 100 years old, Alice will be 50 years old. CRITIQUE:No flaws found. Explanation of the calculation:- Initially, Bob is 20 years old and Alice is half his age, so Alice is 10 years old.- The age difference between Bob and Alice is 20 - 10 = 10 years.- This age difference remains constant over time.- When Bob is 100 years old, the age difference still applies, so Alice will be 100 - 10 = 90 years old. The proposed solution incorrectly states that Alice will be 50 years old when Bob is 100, which does not account for the constant age difference between them. FINAL JUDGMENT:When Bob is 100 years old, Alice will be 90 years old. --- METRICS ---Baseline (1 Agent) -> Latency: 2.63s | Total Tokens: 85Multi-Agent Loop   -> Latency: 16.67s | Total Tokens: 660Overhead           -> 6.3x slower, 7.8x token tax

Analysis of Results and Conclusion #

It seems the initially erroneous response was successfully corrected. In small models, zero-shot scenarios often lead them to connect words like “100” and “half” and lazily assume that the answer requires simple, proportion-based math like 100/2 = 50. Meanwhile, our multiplexed three-tier architecture handled the whole task elegantly and effectively, by emulating a multi-agent verification and correction loop, as shown previously in the code. This is largely thanks to the critic, which is inherently asked to think step-by-step before delivering a judgment.

In terms of the cost of the accuracy gained, there’s an engineering trade-off. Passing a simple factual query through the loop would mean a waste of compute, but for complex-logic scenarios involving reasoning, the Proposer-Critic-Judge loop makes the most sense: not because of efficiency, but because of robustness. We had to pay a much higher token tax and wait extra seconds, but the cognitive gain turned a certain failure into a verified success.

── more in #ai-agents 4 stories · sorted by recency
── more on @qwen2.5-7b-instruct 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/building-a-multi-age…] indexed:0 read:9min 2026-11-27 · —