"""
Pattern 005: Self-Consistency
Description:
Samples multiple reasoning paths for the same question and selects
the most consistent answer through majority voting or consistency scoring.
This approach improves reliability by generating diverse solutions and
aggregating them.
Key Concepts:
- Multiple Sampling: Generate several independent reasoning chains
- Diverse Reasoning: Use temperature or prompt variations
- Aggregation: Majority voting or consistency analysis
- Answer Selection: Choose most frequent or highest confidence answer
Use Cases:
- Math problems with multiple solution methods
- Questions with ambiguous reasoning paths
- Improving reliability of complex reasoning
- Reducing model hallucinations
LangChain Implementation:
Multiple chain invocations with temperature variation and result aggregation.
"""
import os
from typing import List, Dict, Any, Tuple
from collections import Counter
import re
from dotenv import load_dotenv
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
# Load environment variables
load_dotenv()
class SelfConsistencyAgent:
"""Agent that uses self-consistency for reliable reasoning."""
def __init__(self, model_name: str = "gpt-3.5-turbo", num_samples: int = 5):
"""
Initialize the Self-Consistency agent.
Args:
model_name: Name of the OpenAI model to use
num_samples: Number of reasoning paths to sample
"""
self.model_name = model_name
self.num_samples = num_samples
self.base_temperature = 0.7
def _create_llm(self, temperature: float) -> ChatOpenAI:
"""Create an LLM instance with specified temperature."""
return ChatOpenAI(
model=self.model_name,
temperature=temperature,
api_key=os.getenv("OPENAI_API_KEY")
)
def generate_reasoning_paths(self, question: str, context: str = "") -> List[Dict[str, str]]:
"""
Generate multiple diverse reasoning paths for a question.
Args:
question: The question to answer
context: Optional context information
Returns:
List of dictionaries with 'reasoning' and 'answer' keys
"""
# Base prompt for chain-of-thought reasoning
prompt = ChatPromptTemplate.from_messages([
("system", """Answer the question with clear step-by-step reasoning.
Show your work and explain each step.
At the end, clearly state your final answer."""),
("human", "{context}\n\nQuestion: {question}\n\nLet's think step by step:")
])
reasoning_paths = []
# Generate multiple samples with varying temperatures
for i in range(self.num_samples):
# Vary temperature for diversity
temperature = self.base_temperature + (i - self.num_samples // 2) * 0.1
temperature = max(0.1, min(1.0, temperature))
llm = self._create_llm(temperature)
chain = prompt | llm | StrOutputParser()
try:
response = chain.invoke({
"question": question,
"context": context if context else "No additional context."
})
# Extract answer from response
answer = self._extract_answer(response)
reasoning_paths.append({
"reasoning": response,
"answer": answer,
"temperature": temperature
})
except Exception as e:
print(f"Warning: Sample {i+1} failed: {str(e)}")
continue
return reasoning_paths
def _extract_answer(self, reasoning: str) -> str:
"""Extract the final answer from reasoning text."""
# Look for common answer patterns
patterns = [
r"final answer is:?\s*(.+?)(?:\n|$)",
r"answer is:?\s*(.+?)(?:\n|$)",
r"therefore,?\s+(?:the answer is )?\s*(.+?)(?:\n|$)",
r"thus,?\s+(.+?)(?:\n|$)",
r"so,?\s+(?:the answer is )?\s*(.+?)(?:\n|$)",
]
reasoning_lower = reasoning.lower()
for pattern in patterns:
match = re.search(pattern, reasoning_lower, re.IGNORECASE)
if match:
answer = match.group(1).strip()
# Clean up the answer
answer = re.sub(r'[*_]', '', answer) # Remove markdown
return answer
# If no pattern matches, take last non-empty line
lines = [line.strip() for line in reasoning.split('\n') if line.strip()]
return lines[-1] if lines else reasoning[:100]
def aggregate_by_majority_vote(self, reasoning_paths: List[Dict[str, str]]) -> Dict[str, Any]:
"""
Aggregate answers using majority voting.
Args:
reasoning_paths: List of reasoning paths with answers
Returns:
Dictionary with final answer and aggregation statistics
"""
answers = [path['answer'] for path in reasoning_paths]
# Normalize answers for comparison (lowercase, strip punctuation)
normalized_answers = []
for ans in answers:
normalized = ans.lower().strip().rstrip('.')
normalized_answers.append(normalized)
# Count occurrences
answer_counts = Counter(normalized_answers)
most_common_answer, count = answer_counts.most_common(1)[0]
# Find original form of the answer
original_answer = next(
(answers[i] for i, norm in enumerate(normalized_answers)
if norm == most_common_answer),
most_common_answer
)
return {
"final_answer": original_answer,
"confidence": count / len(answers),
"vote_count": count,
"total_samples": len(answers),
"all_answers": answer_counts,
"agreement_rate": count / len(answers)
}
def aggregate_by_consistency_score(self, reasoning_paths: List[Dict[str, str]],
question: str) -> Dict[str, Any]:
"""
Aggregate answers using consistency scoring via LLM.
Args:
reasoning_paths: List of reasoning paths with answers
question: Original question
Returns:
Dictionary with final answer and consistency scores
"""
# Use LLM to evaluate consistency of each answer with others
answers_text = "\n".join([
f"{i+1}. {path['answer']}"
for i, path in enumerate(reasoning_paths)
])
prompt = ChatPromptTemplate.from_messages([
("system", """You are evaluating multiple answers to the same question.
Identify which answer is most consistent with the majority of other answers.
Consider semantic similarity, not just exact matches.
Respond with the number (1, 2, 3, etc.) of the most consistent answer."""),
("human", """Question: {question}
Answers:
{answers}
Most consistent answer number:""")
])
llm = self._create_llm(0.3) # Low temperature for consistent evaluation
chain = prompt | llm | StrOutputParser()
try:
response = chain.invoke({
"question": question,
"answers": answers_text
})
# Extract number
match = re.search(r'\d+', response)
if match:
index = int(match.group()) - 1
if 0 <= index Dict[str, Any]:
"""
Solve a question using self-consistency.
Args:
question: The question to answer
context: Optional context
method: Aggregation method ('majority_vote' or 'consistency_score')
Returns:
Dictionary with solution and metadata
"""
print(f"\nQuestion: {question}\n")
print(f"Generating {self.num_samples} reasoning paths...\n")
# Generate multiple reasoning paths
reasoning_paths = self.generate_reasoning_paths(question, context)
if not reasoning_paths:
return {
"question": question,
"final_answer": "Unable to generate reasoning paths",
"error": "All samples failed"
}
print(f"Generated {len(reasoning_paths)} paths\n")
# Show individual reasoning paths
for i, path in enumerate(reasoning_paths, 1):
print(f"Path {i} (temp={path['temperature']:.2f}):")
print(f" Answer: {path['answer']}")
print()
# Aggregate results
if method == "majority_vote":
result = self.aggregate_by_majority_vote(reasoning_paths)
else:
result = self.aggregate_by_consistency_score(reasoning_paths, question)
result["question"] = question
result["reasoning_paths"] = len(reasoning_paths)
return result
def demonstrate_self_consistency():
"""Demonstrates the Self-Consistency pattern."""
print("=" * 80)
print("PATTERN 005: Self-Consistency")
print("=" * 80)
print()
print("Self-Consistency improves answer reliability by:")
print("1. Generating multiple independent reasoning paths")
print("2. Sampling with different temperatures for diversity")
print("3. Aggregating answers via majority voting or consistency scoring")
print()
# Create agent
agent = SelfConsistencyAgent(num_samples=5)
# Test cases
test_cases = [
{
"question": "If a train travels 120 miles in 2 hours, then travels 180 miles in 3 hours, what is its average speed for the entire journey?",
"context": "",
"method": "majority_vote"
},
{
"question": "A bat and ball cost $1.10 together. The bat costs $1.00 more than the ball. How much does the ball cost?",
"context": "",
"method": "majority_vote"
},
{
"question": "Is it ethical for AI to make medical diagnoses?",
"context": "Consider patient safety, accuracy, and doctor-patient relationships.",
"method": "consistency_score"
}
]
for i, test_case in enumerate(test_cases, 1):
print(f"\n{'=' * 80}")
print(f"Example {i}: {test_case['method'].replace('_', ' ').title()}")
print('=' * 80)
try:
result = agent.solve_with_self_consistency(
question=test_case['question'],
context=test_case['context'],
method=test_case['method']
)
print(f"\n{'=' * 80}")
print("FINAL RESULT")
print('=' * 80)
print(f"\nFinal Answer: {result['final_answer']}")
if 'confidence' in result:
print(f"Confidence: {result['confidence']:.1%}")
print(f"Agreement Rate: {result['agreement_rate']:.1%}")
print(f"Vote Distribution: {dict(result['all_answers'])}")
print(f"Reasoning Paths: {result['reasoning_paths']}/{agent.num_samples}")
except Exception as e:
print(f"\n✗ Error: {str(e)}")
import traceback
traceback.print_exc()
# Summary
print("\n\n" + "=" * 80)
print("SELF-CONSISTENCY PATTERN DEMONSTRATION COMPLETE")
print("=" * 80)
print()
print("Key Techniques Demonstrated:")
print("1. Multiple Sampling: Generated 5 diverse reasoning paths")
print("2. Temperature Variation: Used different temperatures for diversity")
print("3. Majority Voting: Aggregated answers by frequency")
print("4. Consistency Scoring: LLM-based semantic consistency evaluation")
print("5. Confidence Metrics: Agreement rate and vote distribution")
print()
print("Benefits:")
print("- Improved reliability through multiple reasoning paths")
print("- Reduced impact of outlier/hallucinated answers")
print("- Confidence estimation via agreement metrics")
print("- Works with any reasoning task")
print()
print("LangChain Components Used:")
print("- ChatPromptTemplate: Structures reasoning prompts")
print("- StrOutputParser: Parses LLM outputs")
print("- Temperature variation: Creates diverse samples")
print("- Multiple chain invocations: Parallel reasoning paths")
print()
if __name__ == "__main__":
# Check for API key
if not os.getenv("OPENAI_API_KEY"):
print("Error: OPENAI_API_KEY not found in environment variables.")
print("Please set it in your .env file or environment.")
exit(1)
demonstrate_self_consistency()
Agentic Design Pattern: Self Consistency
Pattern 005: Self Consistency – Line-by-Line Explanation
Overview
This document provides a detailed line-by-line explanation of the Self Consistency pattern implementation.
Pattern Description
Pattern 005: Self-Consistency
Description: Samples multiple reasoning paths for the same question and selects the most consistent answer through majority voting or consistency scoring. This approach improves reliability by generating diverse solutions and aggregating them.
Key Concepts: – Multiple Sampling: Generate several independent reasoning chains – Diverse Reasoning: Use temperature or prompt variations – Aggregation: Majority voting or consistency analysis – Answer Selection: Choose most frequent or highest confidence answer
Use Cases: – Math problems with multiple solution methods – Questions with ambiguous reasoning paths – Improving reliability of complex reasoning – Reducing model hallucinations
LangChain Implementation: Multiple chain invocations with temperature variation and result aggregation.
File Statistics
- Total Lines: 384
- Classes: 1
- Functions: 1
- Constants: 0
Module Documentation
"""
Pattern 005: Self-Consistency
Description:
Samples multiple reasoning paths for the same question and selects
the most consistent answer through majority voting or consistency scoring.
This approach improves reliability by generating diverse solutions and
aggregating them.
Key Concepts:
- Multiple Sampling: Generate several independent reasoning chains
- Diverse Reasoning: Use temperature or prompt variations
- Aggregation: Majority voting or consistency analysis
- Answer Selection: Choose most frequent or highest confidence answer
Use Cases:
- Math problems with multiple solution methods
- Questions with ambiguous reasoning paths
- Improving reliability of complex reasoning
- Reducing model hallucinations
LangChain Implementation:
Multiple chain invocations with temperature variation and result aggregation.
"""
Purpose: This module implements the Self Consistency pattern, providing a structured approach to agent design and implementation.
Import Statements
Standard Library Imports
import collections.Counter
import langchain_core.output_parsers.StrOutputParser
import langchain_core.prompts.ChatPromptTemplate
import os
import re
import typing.Any
import typing.Dict
import typing.List
import typing.Tuple
Purpose: Core Python functionality:
– collections.Counter: Specialized container datatypes
– langchain_core.output_parsers.StrOutputParser: Regular expression operations
– langchain_core.prompts.ChatPromptTemplate: Regular expression operations
– os: Environment variable access and system operations
– re: Regular expression operations
– typing.Any: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.Dict: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.List: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.Tuple: Type hints for better code documentation (List, Dict, Any, Optional)
LangChain Imports
from langchain_openai.ChatOpenAI
Purpose: LangChain framework components: – LLM Interface: Wrapper for OpenAI models – Chains: Composable building blocks for complex workflows
Other Imports
from dotenv.load_dotenv
from traceback
Purpose: Additional dependencies for specialized functionality.
Classes
Class: SelfConsistencyAgent
Lines 40-283
Purpose:
Agent that uses self-consistency for reliable reasoning.
Methods:
__init__(self, model_name, num_samples)
Lines 43-53
Purpose:
Initialize the Self-Consistency agent.
Args:
model_name: Name of the OpenAI model to use
num_samples: Number of reasoning paths to sample
Parameters:
– model_name: Language model instance
– num_samples: Num samples
_create_llm(self, temperature)
Lines 55-61
Purpose:
Create an LLM instance with specified temperature.
Parameters:
– temperature: Sampling temperature (0-1)
Returns: ChatOpenAI
generate_reasoning_paths(self, question, context)
Lines 63-112
Purpose:
Generate multiple diverse reasoning paths for a question.
Args:
question: The question to answer
context: Optional context information
Returns:
List of dictionaries with 'reasoning' and 'answer' keys
Parameters:
– question: Question to answer
– context: Context
Returns: <ast.Subscript object at 0x000001A06D696050>
_extract_answer(self, reasoning)
Lines 114-136
Purpose:
Extract the final answer from reasoning text.
Parameters:
– reasoning: Reasoning
Returns: str
aggregate_by_majority_vote(self, reasoning_paths)
Lines 138-174
Purpose:
Aggregate answers using majority voting.
Args:
reasoning_paths: List of reasoning paths with answers
Returns:
Dictionary with final answer and aggregation statistics
Parameters:
– reasoning_paths: Reasoning paths
Returns: <ast.Subscript object at 0x000001A06D168F10>
aggregate_by_consistency_score(self, reasoning_paths, question)
Lines 176-238
Purpose:
Aggregate answers using consistency scoring via LLM.
Args:
reasoning_paths: List of reasoning paths with answers
question: Original question
Returns:
Dictionary with final answer and consistency scores
Parameters:
– reasoning_paths: Reasoning paths
– question: Question to answer
Returns: <ast.Subscript object at 0x000001A06D158310>
solve_with_self_consistency(self, question, context, method)
Lines 240-283
Purpose:
Solve a question using self-consistency.
Args:
question: The question to answer
context: Optional context
method: Aggregation method ('majority_vote' or 'consistency_score')
Returns:
Dictionary with solution and metadata
Parameters:
– question: Question to answer
– context: Context
– method: Method
Returns: <ast.Subscript object at 0x000001A06D156DD0>
Functions
demonstrate_self_consistency()
Lines 286-373
Purpose:
Demonstrates the Self-Consistency pattern.
Key Concepts Summary
Pattern Overview
The Self Consistency pattern provides a structured approach to building AI agents with specific capabilities and behaviors. This implementation leverages LangChain’s composable components to create a robust and maintainable solution.
Core Components
- Agent Class: Main implementation of the pattern logic
- Prompt Engineering: Carefully crafted prompts to guide LLM behavior
- Tool Integration: Optional tools for extended functionality
- Memory Management: State handling across interactions
- Output Parsing: Structured response processing
When to Use
✅ Good for: – Scenarios requiring this specific pattern’s strengths – Applications needing structured agent behavior – Systems where explainability is important – Production environments requiring reliability
❌ Not ideal for: – Simple single-prompt tasks – Scenarios requiring different pattern characteristics – Resource-constrained environments (if computationally intensive)
Best Practices Demonstrated
1. Environment Configuration
- ✅ Use
.envfiles for API keys - ✅ Never hardcode credentials
- ✅ Validate environment variables on startup
2. Error Handling
- ✅ Graceful degradation on failures
- ✅ Informative error messages
- ✅ Logging for debugging
3. Prompt Engineering
- ✅ Clear, specific instructions
- ✅ Structured output formats
- ✅ Few-shot examples when beneficial
4. Code Organization
- ✅ Separation of concerns (class-based design)
- ✅ Type hints for clarity
- ✅ Docstrings for documentation
5. Performance Optimization
- ✅ Appropriate temperature settings
- ✅ Token budget management
- ✅ Caching where applicable
LangChain Components Used
- ChatOpenAI: OpenAI model interface
- Chains: Sequential component composition
Why LangChain? – Composable abstractions for LLM applications – Rich ecosystem of integrations – Production-ready patterns – Active community and development
Execution Flow
1. Initialize agent with configuration
↓
2. Load environment and dependencies
↓
3. Prepare prompt with input data
↓
4. Invoke LLM through LangChain
↓
5. Parse and validate response
↓
6. Return formatted result
Key Decision Points: – Model selection (temperature, model type) – Prompt structure (few-shot vs zero-shot) – Error handling strategy – Output format validation
Performance Considerations
Computational Cost
- LLM Calls: Primary cost factor (based on tokens)
- Latency: Depends on model and input size
- Memory: Minimal for most patterns
Optimization Strategies
- Prompt Optimization: Minimize tokens while maintaining clarity
- Caching: Cache repeated queries/responses
- Model Selection: Use smaller models when appropriate
- Batch Processing: Group similar requests
- Streaming: For long responses, stream tokens
Cost Estimates (Approximate)
- GPT-3.5-turbo: ~$0.002 per request
- GPT-4: ~$0.03 per request
- GPT-4-turbo: ~$0.01 per request
Actual costs vary based on input/output token counts
Common Pitfalls to Avoid
1. Prompt Design Issues
❌ Vague or ambiguous instructions
✅ Clear, specific, testable prompts
2. Error Handling
❌ Ignoring API errors or rate limits
✅ Implement retry logic and graceful degradation
3. Token Management
❌ Exceeding model token limits
✅ Truncate inputs, chunk processing
4. Security
❌ Exposing API keys in code
✅ Use environment variables
5. Testing
❌ Only testing happy paths
✅ Test edge cases, failures, malformed inputs
6. Cost Management
❌ Unmonitored API usage
✅ Implement budgets, alerts, and monitoring
Further Improvements
Production Enhancements
- Monitoring: Add logging, metrics, tracing
- Validation: Input/output schema validation
- Rate Limiting: Implement request throttling
- Caching: Redis or in-memory cache for responses
- Async Support: Non-blocking operations for scalability
Feature Extensions
- Multi-Model Support: Switch between providers
- Fallback Models: Graceful degradation strategy
- Custom Tools: Domain-specific function calling
- Advanced Memory: Vector stores for long-term memory
- Evaluation: Automated testing and benchmarking
Code Quality
- Testing: Unit tests, integration tests
- Documentation: API docs, usage examples
- Type Safety: Stricter type hints
- Configuration: Externalized config files
Related Patterns
- Pattern 004
- Pattern 006
- Other Reasoning Patterns (001-011)
Pattern Families: – Reasoning Patterns (001-011) – Multi-Agent Patterns (012-019) – Tool Use Patterns (020-025) – Memory Patterns (026-031) – And many more…
Summary
The Self Consistency pattern provides a powerful approach to building AI agents with specific capabilities. This implementation demonstrates:
✅ Key Strengths: – Clean, maintainable code structure – LangChain integration for composability – Type hints and documentation – Production-ready patterns
🎯 Best Use Cases: – Applications requiring this pattern’s characteristics – Systems needing structured agent behavior – Production environments requiring reliability
📚 Learning Resources: – LangChain Documentation: https://python.langchain.com/ – Pattern Documentation: See related patterns – OpenAI API Reference: https://platform.openai.com/docs/
File: 005_self_consistency.py
Total Lines: 384
Pattern Category: AI Agent Design Pattern #005
Generated from actual implementation code
For educational and reference purposes
Leave a Reply