Vai al contenuto principaleVai al footer
PatternscriptintermediateEseguibileguided-flow

Self-consistency: sample several paths, take the majority

Ask the same question N times at a temperature high enough to produce genuinely different reasoning, then take the answer the paths converge on. The vote is plain code, not another model call, because asking a model to pick the best of N restores the single point of failure the sampling removed.

Fatti chiave

Livello
intermediate
Runtime
Python • API OpenAI
Pattern
Flusso ispezionabile con confini di sistema visibili
Interazione
Sandbox live • Script
Aggiornato
27 luglio 2026

Naviga questo esempio

Vista rapida del flusso

Come questo esempio si muove tra input, esecuzione e risultato rivedibile

Self-consistency: sample several paths, take… -> Retrieve relevant context -> Load environment keys -> Initialize OpenAI client -> Constrain output schema -> Send message payload

Trigger

Self-consistency: sample several paths, take…

Runtime

Retrieve relevant context

Esito

Load environment keys

Perché esiste questa pagina

Questo esempio è mostrato sia come codice sorgente reale che come pattern di interazione orientato al prodotto, così i discenti possono collegare implementazione, UX e doctrine senza lasciare la libreria.

Flusso visivoCodice realeSandbox o walkthroughAccesso MCP

Relazioni con la doctrine

Queste sono forme di ragionamento: come un agente decide, quando agisce, cosa ricorda. Per comporre l'interfaccia intorno a esso, vedi l'AI Pattern Blueprint. Per trigger, pianificazione, caricamento del contesto e ripristino, vedi Agent runtime architecture.

Strutturale

Questo pattern esprime questi principi direttamente nel codice.

  • P6 · Esporre uno stato operativo significativo, non la complessità interna

    The vote distribution IS the operational state, and returning it is what separates this pattern from an expensive single call. Five of five and three of five are different situations that a bare answer cannot distinguish. This implementation returns the count alongside the answer and escalates explicitly when the majority is thin or absent.

    self_consistency.py:run

Gap predefinito

La forma classica di questo pattern li viola per impostazione predefinita. Ognuno riporta la correzione.

  • P2 · Assicurarsi che il lavoro in background rimanga percepibile

    N samples means N times the latency, and by default nothing is emitted until all of them land. Fix, applied here: emit each sample as it completes so a five-sample run reads as progress rather than as one very slow call.

    self_consistency.py:run

  • P5 · Sostituire la magia implicita con modelli mentali chiari

    The reader sees one answer and has no way to know it was contested, or that four other paths reached something else. That is a false impression of certainty, produced by a technique adopted specifically to handle uncertainty. Fix: carry the agreement count through to wherever the answer is displayed, rather than discarding it at the boundary of this function.

    self_consistency.py:run

Dipende dall'implementazione

Lo decide la tua implementazione, non il pattern. Nessun verdetto.

  • P7 · Stabilire fiducia attraverso l'ispezionabilità

    Each path produces its reasoning, so the derivation exists. Whether the dissenting paths are ever shown, which is where the interesting information usually is, is a wrapper decision. The pattern neither surfaces nor hides them.

    self_consistency.py:Attempt

Le relazioni con la doctrine sono analisi di prima parte, non il risultato di una validazione. Esegui il validatore sul tuo codice per ottenere un verdetto con punteggio.

Come dovrebbe essere usato questo esempio nella piattaforma?

Usa prima la sandbox per comprendere il pattern di esperienza, poi ispeziona il sorgente per vedere come il confine del prodotto, il confine del modello e il confine della doctrine sono effettivamente implementati.

UX pattern: Flusso ispezionabile con confini di sistema visibili
Assicurarsi che il lavoro in background rimanga percepibile
Sostituire la magia implicita con modelli mentali chiari
Esporre uno stato operativo significativo, non la complessità interna

Riferimenti sorgente

Voce di libreria
pattern-self-consistency
Percorso sorgente
content/patterns/sampling-search/self-consistency/self_consistency.py
Librerie
openai, pydantic, python-dotenv
Requisiti di runtime
OPENAI_API_KEY
Principi correlati
Assicurarsi che il lavoro in background rimanga percepibile, Sostituire la magia implicita con modelli mentali chiari, Esporre uno stato operativo significativo, non la complessità interna, Stabilire fiducia attraverso l'ispezionabilità

self_consistency.py

python
"""
Self-consistency: sample several reasoning paths, take the majority

Ask the same question N times at a temperature high enough to get genuinely
different reasoning, then take the answer the paths agree on. Errors tend to
be idiosyncratic and scatter; correct answers tend to converge.

    Question -> N independent paths -> normalise -> majority answer

The vote is plain Python, deliberately. Asking a model to pick the best of N
answers reintroduces exactly the single-point-of-failure the sampling was
meant to remove, and it lets a confidently-worded wrong answer win.

The agreement count is the useful output, not a decoration. Five of five is a
different situation from three of five, and a caller that only reads the
answer has thrown away the reason to have run this at all.

Run: python self_consistency.py
"""

from collections import Counter

from dotenv import load_dotenv
from openai import OpenAI
from pydantic import BaseModel, Field

load_dotenv()

client = OpenAI()

MODEL = "gpt-5.4-mini"
SAMPLES = 5
#: Enough spread to get different reasoning. At 0 every path is the same path
#: and the vote is theatre.
TEMPERATURE = 1.0


class Attempt(BaseModel):
    reasoning: str = Field(description="Work the problem through, step by step.")
    answer: str = Field(
        description="The final answer alone. No units, no restatement, no prose."
    )


def attempt(question: str) -> Attempt:
    completion = client.beta.chat.completions.parse(
        model=MODEL,
        temperature=TEMPERATURE,
        messages=[
            {
                "role": "system",
                "content": (
                    "Work the problem through and give the final answer. Put "
                    "only the answer itself in `answer`, nothing else."
                ),
            },
            {"role": "user", "content": question},
        ],
        response_format=Attempt,
    )
    return completion.choices[0].message.parsed


def normalise(answer: str) -> str:
    """Group answers that are the same fact written differently.

    Without this the vote splits on formatting and everything ties at one
    each, which looks like disagreement when the paths actually agreed.
    """
    return answer.strip().lower().rstrip(".").replace(",", "").replace("$", "")


def run(question: str) -> tuple[str, int, int]:
    attempts: list[Attempt] = []
    for index in range(1, SAMPLES + 1):
        print(f"  [{index}/{SAMPLES}] sampling...")
        current = attempt(question)
        print(f"      answer: {current.answer}")
        attempts.append(current)

    counts = Counter(normalise(a.answer) for a in attempts)
    winner, votes = counts.most_common(1)[0]

    # Surface the spread, not just the winner. Agreement IS the signal.
    print(f"  distribution: {dict(counts)}")
    print(f"  majority    : {winner} ({votes}/{SAMPLES})")
    if votes == 1:
        print("  WARNING: every path disagreed. Treat this as no answer.")
    elif votes <= SAMPLES // 2:
        print("  WARNING: the majority is thin. Escalate rather than rely on it.")

    return winner, votes, SAMPLES


if __name__ == "__main__":
    question = (
        "A team of 4 engineers takes 6 days to migrate 120 services. Two more "
        "engineers join at the same rate. How many days for the next 120?"
    )
    print(f"\n> {question}")
    run(question)

Cosa dovrebbe ispezionare il discente nel codice?

Cerca il punto esatto in cui lo scope del sistema è delimitato: definizioni di schema, impostazione del prompt, configurazione di runtime e il punto di chiamata che trasforma l'intenzione dell'utente in un'azione concreta del modello o del workflow.

Cerca i contratti di output e la validazione
Cerca la chiamata di esecuzione esatta
Cerca cosa il prodotto potrebbe esporre all'utente

Come si relaziona la sandbox al sorgente?

La sandbox dovrebbe rendere leggibile l'UX: cosa vede l'utente, cosa sta decidendo il sistema e come il risultato diventa revisionabile. Il sorgente mostra poi come quel comportamento è effettivamente implementato.

Leggi il riepilogo dell'implementazione.
Esplora gli stati utente e di sistema.
Ispeziona il codice sorgente tenendo a mente le decisioni di doctrine evidenziate.
SandboxFlusso ispezionabile con confini di sistema visibili

Guida all'interazione

Usa la sandbox per esplorare l'esperienza visibile all'utente, il lavoro del sistema e la scelta di doctrine che l'esempio sta facendo.

Spiegazione UX

La sandbox spiega cosa dovrebbe vedere l'utente, cosa sta facendo il sistema e dove il controllo o l'ispezionabilità devono rimanere espliciti.

Spiegazione AI Design

La pagina trasforma il codice sorgente in un pattern orientato al prodotto: cosa può decidere il modello, cosa dovrebbe esporre il prodotto e dove il codice deterministico o la revisione devono subentrare.

Guida all'interazione

  1. 1Leggi il riepilogo dell'implementazione.
  2. 2Esplora gli stati utente e di sistema.
  3. 3Ispeziona il codice sorgente tenendo a mente le decisioni di doctrine evidenziate.

Visibile all'utente

Ask the same question N times at a temperature high enough to produce genuinely different reasoning, then take the answer the paths converge on. The vote is plain code, not another model call, because asking a model to pick the best of N restores the single point of failure the sampling removed.

Lavoro del sistema

Il prodotto prepara un task delimitato per il modello o il workflow.

Perché è importante

L'interfaccia dovrebbe rendere il task delegato leggibile prima che avvenga l'automazione.

Usato in corsi e percorsi

Questo esempio attualmente è indipendente nella libreria, ma si connette comunque al sistema dei principi e alla famiglia di esempi più ampia.

Principi correlati

Runtime architecture

Usa questo esempio nei tuoi agenti

Questo esempio è disponibile anche tramite il layer agent-ready del blueprint. Usa la pagina Per agenti per recuperare MCP pubblico, export deterministici e setup per Claude o Cursor.

Definisci trigger, contesto e confini prima di aumentare l'autonomia
Rendi espliciti controllo, osservabilita e recovery nel runtime
Scegli i pattern operativi giusti prima di delegare ai workflow