AI Agents & LLMsMedium
What is self-consistency in LLM reasoning?
Learning path, stage 2 of 5: Prompting and model features · question 4 of 10Self-consistency samples several independent reasoning paths for the same question and takes a majority vote on the final answers. Wrong reasoning tends to scatter across different answers, while correct reasoning tends to land on the same one, so the vote is more reliable than any single run.
How it works
- Ask the same CoT prompt N times with some randomness (for example N = 5–20).
- Extract the final answer from each run.
- Return the most common answer. The share of runs that agree is a rough confidence score.
When it's worth it
- Tasks with a checkable, short final answer: maths, multiple choice, classification, SQL that returns a value.
- High-stakes calls where N times the cost is acceptable.
- Low agreement is a useful signal to send the case to a person.
Limits
- N times the tokens and cost (run them in parallel to keep latency down).
- Doesn't directly suit open-ended writing. There you use a judge or a "pick the best" step.
Sources
Code example
tsx
1// Self-consistency: N parallel runs + majority vote + agreement score.2async function selfConsistent(3 ask: () => Promise<string>, // one CoT run that returns the extracted final answer4 n = 7,5) {6 const answers = await Promise.all(Array.from({ length: n }, ask));7 const counts = new Map<string, number>();8 for (const a of answers) {9 const key = a.trim().toLowerCase();10 counts.set(key, (counts.get(key) ?? 0) + 1);11 }12 const [best, votes] = [...counts.entries()].sort((a, b) => b[1] - a[1])[0];13 const agreement = votes / n;14 return { answer: best, agreement, needsReview: agreement < 0.6 };15}1617// usage: selfConsistent(() => solve("What is 17 * 24 - 13?"))
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.