This is a three-stage prompt engineering system built to do one thing well: take a problem, build a solid prompt around it, and then make that prompt actually good.
The workflow is straightforward: Analyze → Generate → Improve
Prompt of the Week
Chain
The Prompt Creation Trilogy
# The Prompt Creation Trilogy
This folder contains a three-stage prompt engineering system designed to systematically analyze a problem, generate a targeted prompt, and then improve that prompt to a high standard.
The system follows a logical workflow: **Analyze → Generate → Improve**.
## The Three Stages
### 1. [The Multi-Framework Analyzer](./1-analyzer.md)
**Purpose:** To gather deep context and understanding about a problem *before* writing a prompt.
This first stage uses a phase-by-phase analytical framework to break down any question or problem into actionable insights. It employs methods like Ishikawa fishbone diagrams, the Five Whys, and OODA loops to ensure a thorough analysis. The output is a progressively built `Analysis-[Topic]-[Date].md` file that documents the entire analytical process.
**Best for:** Situations where you need to deeply understand a complex problem before attempting to solve it with an AI prompt.
### 2. [The Agentic Prompt Generator](./2-generator.md)
**Purpose:** To create a targeted, high-quality prompt based on a set of requirements.
This second stage acts as an autonomous prompt architect. It takes your requirements, chooses an appropriate architecture, and then iteratively builds a prompt, scoring its own work and making decisions until it meets quality targets. It logs its entire process in a `prompt_gen.md` file, providing a complete audit trail of its reasoning.
**Best for:** Generating robust, well-structured prompts for specific tasks when you have a clear goal in mind.
### 3. [The Adaptive Prompt Improver](./3-improver.md)
**Purpose:** To take *any* existing prompt and systematically enhance it to achieve 90%+ quality scores.
The final stage is an adaptive improvement loop. It auto-detects the prompt's domain (e.g., analysis, creative, technical) and applies specialized enhancements using military-grade OODA loops. It creates a `prompt_improvement_[timestamp].md` file that documents each improvement loop, showing you exactly how the prompt evolves and teaching prompt engineering principles along the way.
**Best for:** Polishing a rough or basic prompt into a production-ready, high-performance tool.
---
## Future Updates
**Note:** This trilogy is planned to be updated into a fully integrated, sub-agent workflow in the near future. This will allow for a seamless, automated flow from analysis to generation to final improvement.# Agentic Multi-Framework Analysis System - Optimized for Phase-by-Phase Execution
## SYSTEM OVERVIEW
This system is designed for **agentic execution** - each phase must be completed individually, with outputs read and analyzed before proceeding to the next phase. This approach ensures emergent analysis where each phase builds directly on actual findings rather than assumptions.
**Core Principle**: Never execute all phases simultaneously. Each phase completion must inform the next phase execution.
---
## EXECUTION PROTOCOL
### Pre-Analysis Setup
1. **Question Definition**: State specific question or problem clearly
2. **CREATE DEDICATED MD FILE**: Use Write tool to create new markdown file for this analysis
3. **File Naming**: Use format: `Analysis-[Question-Topic]-[Date].md`
4. **Initial Setup**: Add question and phase structure to the file
5. **Phase Tracking**: Use TodoWrite tool to track phase completion
6. **Sequential Commitment**: Complete each phase individually before proceeding
### Mandatory File Management Protocol
- **NEVER execute all phases in one response**
- **CREATE MD FILE** before starting Phase 1
- **ADD each phase output** to the MD file using Edit tool
- **READ the updated file** before proceeding to next phase
- **BUILD analysis progressively** in the same dedicated file
### Agentic Execution Rules
1. **CREATE MD FILE** with question and phase structure
2. **EDIT FILE** to add Phase 1 analysis → **READ updated file** → **PROCEED TO PHASE 2**
3. **EDIT FILE** to add Phase 2 analysis → **READ updated file** → **PROCEED TO PHASE 3**
4. **EDIT FILE** to add Phase 3 analysis → **READ updated file** → **PROCEED TO PHASE 4**
5. **EDIT FILE** to add Phase 4 analysis → **READ updated file** → **PROCEED TO PHASE 5**
6. **EDIT FILE** to add Phase 5 analysis → **READ complete file** → **SYNTHESIZE FINAL RECOMMENDATIONS**
### Required Tool Usage
- **Write tool**: Create initial MD file with question and phase structure
- **Edit tool**: Add each completed phase analysis to the file
- **Read tool**: Read updated file content before proceeding to next phase
- **TodoWrite tool**: Track which phases have been completed
---
## PHASE 1: ROOT CAUSE ANALYSIS FRAMEWORK
**Objective**: Identify all contributing factors using systematic categorization
**Execution Instructions**:
1. Apply Ishikawa (fishbone) analysis to the stated question
2. Categorize ALL contributing factors across six dimensions
3. Aim for 3-5 specific factors per category
4. Focus on actual conditions, not assumptions
5. Create ASCII fishbone diagram showing visual structure
6. Mark phase as **COMPLETED** when analysis is comprehensive
**ASCII Ishikawa Diagram Template**:
```
Environmental Factors Method/Process Factors
│ │
├─ Factor 1 ├─ Factor 1
├─ Factor 2 ├─ Factor 2
└─ Factor 3 └─ Factor 3
/
/
________________________/
│
[PROBLEM/QUESTION]
________________________
/
/
/
Human Factors System/Tool Factors
│ │
├─ Factor 1 ├─ Factor 1
├─ Factor 2 ├─ Factor 2
└─ Factor 3 └─ Factor 3
Material/Data Factors Measurement Factors
│ │
├─ Factor 1 ├─ Factor 1
├─ Factor 2 ├─ Factor 2
└─ Factor 3 └─ Factor 3
```
**Analysis Categories**:
- **Environmental Factors**: Context, deployment conditions, external pressures
- **Method/Process Factors**: Current approaches, workflow gaps, systematic issues
- **Human Factors**: People involved, expertise, emotional/cognitive elements
- **System/Tool Factors**: Technology, capabilities, limitations, missing tools
- **Material/Data Factors**: Information availability, data quality, resource gaps
- **Measurement Factors**: Metrics, evaluation methods, assessment limitations
**Completion Criteria**:
- All six categories addressed with specific factors
- Factors are observable/verifiable, not speculative
- ASCII fishbone diagram created with actual factors
- Analysis added to MD file using Edit tool
- Clear documentation of **PHASE 1 COMPLETED**
**STOP HERE - USE READ TOOL ON MD FILE BEFORE PROCEEDING TO PHASE 2**
---
## PHASE 2: DEEP DIVE FIVE WHYS ANALYSIS
**Objective**: Drive to fundamental root cause from most critical Phase 1 finding
**Execution Instructions**:
1. **READ PHASE 1 OUTPUT** - identify most critical contributing factor
2. Apply Five Whys methodology to that specific factor
3. Drive toward fundamental causes, not symptoms
4. Each "why" should reveal deeper causality
5. Root cause should be actionable and specific
**Selection Criteria for Critical Factor**:
- Which factor has highest impact on the core question?
- Which factor, if addressed, would have most significant effect?
- Which factor represents the biggest gap or problem?
**Five Whys Structure**:
1. **Why does [critical factor] exist?** → [Immediate cause]
2. **Why does [immediate cause] occur?** → [Deeper cause]
3. **Why does [deeper cause] happen?** → [Systemic cause]
4. **Why does [systemic cause] persist?** → [Fundamental cause]
5. **Why is [fundamental cause] allowed to continue?** → [Root cause]
**Completion Criteria**:
- Clear identification of most critical Phase 1 factor
- Complete five-level causal chain
- Root cause that explains fundamental mechanism
- Clear documentation of **PHASE 2 COMPLETED**
**STOP HERE - USE READ TOOL ON UPDATED MD FILE BEFORE PROCEEDING TO PHASE 3**
---
## PHASE 3: KNOWLEDGE INTEGRATION FRAMEWORK
**Objective**: Contextualize root cause within broader knowledge landscape
**Execution Instructions**:
1. **READ PHASE 2 OUTPUT** - use root cause as focal point
2. Research established principles that relate to the root cause
3. Identify contradicting theories or evidence
4. Find parallel examples from other domains
5. Examine historical precedents
**Knowledge Categories**:
**Established Principles**:
- What proven theories/frameworks apply to this root cause?
- What established patterns explain this mechanism?
- What validated approaches exist for similar problems?
**Contradicting Evidence/Theories**:
- What evidence challenges the root cause conclusion?
- What alternative explanations exist?
- What theories suggest different approaches?
**Parallel Examples from Other Domains**:
- What industries/fields face similar root causes?
- How have other domains solved analogous problems?
- What patterns repeat across different contexts?
**Historical Precedents**:
- When has this root cause appeared before?
- What solutions worked/failed historically?
- What can past attempts teach us?
**Completion Criteria**:
- All four knowledge categories addressed
- Specific examples and principles cited
- Clear connection between knowledge and root cause
- Clear documentation of **PHASE 3 COMPLETED**
**STOP HERE - USE READ TOOL ON UPDATED MD FILE BEFORE PROCEEDING TO PHASE 4**
---
## PHASE 4: EMPIRICAL OBSERVATION PROTOCOL
**Objective**: Apply scientific method to validate/test understanding
**Execution Instructions**:
1. **READ PHASE 3 OUTPUT** - use knowledge context to inform observations
2. Apply systematic empirical analysis
3. Focus on observable patterns, not assumptions
4. Generate testable hypotheses
5. Design validation methods
**Scientific Method Structure**:
**Observe - What Patterns Are Actually Present?**:
- What observable behaviors/conditions exist currently?
- What measurable outcomes are occurring?
- What trends or patterns can be documented?
- What data points are available for analysis?
**Hypothesize - What Mechanism Explains These Patterns?**:
- Based on root cause and knowledge integration, what explanatory mechanism fits?
- What causal relationship would produce observed patterns?
- What underlying dynamics drive the current situation?
**Predict - Expected Outcomes if Hypothesis Correct**:
- What specific outcomes would occur if hypothesis is true?
- What measurable changes would result from addressing root cause?
- What indicators would confirm hypothesis validity?
**Test - How Could This Be Validated?**:
- What experiments/trials could test the hypothesis?
- What metrics would measure success/failure?
- What pilot programs could validate approach?
- What comparison methods could prove effectiveness?
**Completion Criteria**:
- All four scientific method steps completed
- Testable hypothesis clearly stated
- Validation methods are specific and measurable
- Clear documentation of **PHASE 4 COMPLETED**
**STOP HERE - USE READ TOOL ON UPDATED MD FILE BEFORE PROCEEDING TO PHASE 5**
---
## PHASE 5: STRATEGIC SYNTHESIS (OODA LOOP)
**Objective**: Transform analysis into actionable strategic recommendations
**Execution Instructions**:
1. **READ PHASE 4 OUTPUT** - use empirical findings as foundation
2. Apply OODA (Observe-Orient-Decide-Act) strategic framework
3. Address cognitive biases and mental models
4. Generate specific actionable recommendations
5. Prioritize implementation approach
**OODA Loop Structure**:
**Observe - Current State and Dynamics**:
- What is the actual current situation based on all previous phases?
- What key dynamics are affecting the system?
- What constraints and opportunities exist?
**Orient - Mental Models and Biases**:
- What assumptions or biases might affect perception of the problem?
- What mental models are influencing decision-making?
- What cognitive blind spots need to be addressed?
**Decide - Optimal Path Forward**:
- Based on all analysis, what is the best strategic approach?
- What are the key decision criteria?
- What trade-offs must be considered?
- What risks need mitigation?
**Act - Specific Actionable Recommendations**:
- What concrete actions should be taken?
- What is the implementation sequence?
- What resources are required?
- What success metrics should be tracked?
**Completion Criteria**:
- All four OODA elements addressed comprehensively
- Specific, actionable recommendations provided
- Implementation approach clearly defined
- Clear documentation of **PHASE 5 COMPLETED**
---
## FINAL SYNTHESIS PROTOCOL
**After ALL phases completed**:
1. **Comprehensive Review**: Read outputs from all five phases
2. **Integration Check**: Ensure recommendations flow logically from analysis
3. **Validation**: Confirm empirical approach supports strategic recommendations
4. **Final Recommendation**: Provide definitive answer to original question
5. **Implementation Roadmap**: Specific next steps with success criteria
**Final Output Structure**:
- **Executive Summary**: Clear answer to original question
- **Analytical Foundation**: Key insights from each phase
- **Strategic Recommendation**: Specific course of action
- **Implementation Plan**: Concrete next steps
- **Success Metrics**: How to measure effectiveness
---
## OPTIMIZATION FEATURES
**Enhanced Agentic Design**:
- **Mandatory Phase Breaks**: System requires reading output between phases
- **Progressive Analysis**: Each phase builds on actual (not assumed) previous findings
- **Emergent Insights**: Conclusions emerge from systematic analysis rather than predetermined thinking
- **Validation Loops**: Multiple validation points ensure analysis quality
**Improved Structure**:
- **Clear Stop Points**: Explicit instructions to pause and read between phases
- **Specific Completion Criteria**: Measurable standards for phase completion
- **TodoWrite Integration**: Built-in progress tracking
- **Output Quality Control**: Standards for each phase output
**Strategic Enhancements**:
- **Bias Recognition**: Explicit identification of mental models and assumptions
- **Empirical Validation**: Scientific method ensures testable conclusions
- **Implementation Focus**: Every analysis leads to specific actionable recommendations
- **Success Measurement**: Clear metrics for validating approach effectiveness
---
## STEP-BY-STEP EXECUTION EXAMPLE
### Step 1: Create MD File
```
Use Write tool to create: Analysis-[Topic]-[Date].md
Initial content:
# [Topic] Analysis - Agentic Multi-Framework Analysis
**Question**: [State your specific question here]
**Date**: [Current date]
## Phase 1: Root Cause Analysis
[To be completed]
## Phase 2: Deep Dive Analysis
[To be completed]
## Phase 3: Knowledge Integration
[To be completed]
## Phase 4: Empirical Observation
[To be completed]
## Phase 5: Strategic Synthesis
[To be completed]
## Final Synthesis
[To be completed]
```
### Step 2: Execute Phase 1
```
Use Edit tool to replace "## Phase 1: Root Cause Analysis [To be completed]" with:
## Phase 1: Root Cause Analysis
**ASCII Ishikawa Diagram:**
```
Environmental Factors Method/Process Factors
│ │
├─ [Actual factor 1] ├─ [Actual factor 1]
├─ [Actual factor 2] ├─ [Actual factor 2]
└─ [Actual factor 3] └─ [Actual factor 3]
/
/
________________________/
│
[YOUR QUESTION]
________________________
/
/
/
Human Factors System/Tool Factors
│ │
├─ [Actual factor 1] ├─ [Actual factor 1]
├─ [Actual factor 2] ├─ [Actual factor 2]
└─ [Actual factor 3] └─ [Actual factor 3]
Material/Data Factors Measurement Factors
│ │
├─ [Actual factor 1] ├─ [Actual factor 1]
├─ [Actual factor 2] ├─ [Actual factor 2]
└─ [Actual factor 3] └─ [Actual factor 3]
```
[Detailed analysis of each category with explanations]
**PHASE 1 COMPLETED**
```
### Step 3: Read Updated File
```
Use Read tool on the MD file to see Phase 1 results before continuing
```
### Step 4: Execute Phase 2
```
Use Edit tool to replace "## Phase 2: Deep Dive Analysis [To be completed]" with:
## Phase 2: Deep Dive Analysis
[Complete Five Whys analysis based on Phase 1 findings]
**PHASE 2 COMPLETED**
```
### Continue Pattern Through All Phases
- Edit file to add each phase
- Read updated file before proceeding
- Build analysis progressively in same file
**This optimized system ensures rigorous, emergent analysis through mandatory agentic execution while maintaining systematic analytical depth across multiple frameworks.**# Adaptive Prompt Generation Loop Protocol
## INITIALIZATION
Enter **Adaptive Prompt Generation Mode**. Operate as an iterative prompt creation system using the OODA Loop (Observe, Orient, Decide, Act) to build a high-quality prompt from requirements specification.
### Loop Control Variables:
```
LOOP_NUMBER=0
COMPONENTS_ADDED=[]
PROMPT_VERSION="v0_requirements"
BUILD_LEVEL="foundation"
GENERATION_START_TIME=$(current timestamp)
QUALITY_SCORE=0
TARGET_SCORE=90
PROMPT_PURPOSE=""
```
## MANDATORY 6-LOOP COMPLETION
**CRITICAL RULE:** Always complete all 6 loops regardless of quality score achieved.
**Why 6 loops are always required:**
- Loop 1-2: Foundation layers
- Loop 3-4: Enhancement and capability layers
- Loop 5-6: Optimization and excellence layers
**No early termination allowed** - Each loop serves a distinct architectural purpose.
### Initialize Generation Log:
Create prompt generation log using Write tool:
- prompt_gen.md with session timestamp
- Requirements specification section
- Version tracking section
## PRE-LOOP REQUIREMENTS GATHERING
Capture the user's needs and establish generation targets:
- [ ] Document the desired prompt's purpose and goals
- [ ] Identify target AI model (GPT-4, Claude, etc.)
- [ ] Capture expected inputs and outputs
- [ ] Define success criteria and use cases
- [ ] Note any specific constraints or requirements
### Requirements Analysis Template:
```
## Requirements Analysis
# Core Requirements
PROMPT_PURPOSE="[What should this prompt accomplish?]"
TARGET_MODEL="[Which AI model will use this?]"
INPUT_TYPE="[What inputs will it process?]"
OUTPUT_TYPE="[What outputs should it produce?]"
USE_CASES=["Primary use case", "Secondary use case"]
# Functional Requirements
MUST_HAVE=["Critical feature 1", "Critical feature 2"]
SHOULD_HAVE=["Important feature 1", "Important feature 2"]
NICE_TO_HAVE=["Optional feature 1", "Optional feature 2"]
# Non-Functional Requirements
TONE_STYLE="[Professional/Casual/Technical/Creative]"
COMPLEXITY_LEVEL="[Simple/Moderate/Advanced/Expert]"
ERROR_HANDLING="[Required/Optional/None]"
PERFORMANCE_NEEDS="[Speed/Accuracy/Creativity balance]"
# Constraints
MAX_LENGTH="[Token/character limit if any]"
FORBIDDEN_ELEMENTS=["Things to avoid"]
REQUIRED_TECHNIQUES=["Specific techniques to use"]
```
---
## THE PROMPT GENERATION OODA LOOP
### ⭕ PHASE 0: ARCHITECTURE PLANNING
**Design the prompt structure based on requirements**
#### Dynamic Architecture Detection:
```
def detect_prompt_architecture(requirements):
"""
Simple architecture detection based on basic requirements analysis
"""
purpose = requirements.get('PROMPT_PURPOSE', '').lower()
complexity = requirements.get('COMPLEXITY_LEVEL', 'moderate')
# Determine required components based on simple heuristics
components = ['main_instruction'] # Always needed
# Add components based on purpose
if any(word in purpose for word in ['analyze', 'analysis', 'examine']):
components.extend(['reasoning_steps', 'validation_checks'])
elif any(word in purpose for word in ['create', 'generate', 'build']):
components.extend(['examples', 'validation_checks'])
elif any(word in purpose for word in ['solve', 'problem', 'fix']):
components.extend(['reasoning_steps', 'error_handling'])
# Add based on complexity
if complexity == 'advanced':
if 'examples' not in components:
components.append('examples')
if 'error_handling' not in components:
components.append('error_handling')
# Determine build sequence
build_sequence = {
'foundation': ['main_instruction'],
'enhancement': [comp for comp in components if comp != 'main_instruction'],
'optimization': []
}
return {
'architecture_type': 'adaptive_simple',
'components': components,
'build_sequence': build_sequence,
'optimization_targets': ['clarity_and_effectiveness']
}
```
### Log Loop Start:
Use Edit tool to update prompt_gen.md with:
```
## Loop {LOOP_NUMBER} - {timestamp}
**Build Stage:** {CURRENT_BUILD_STAGE}
**Goal:** Build {stage} layer
**Architecture:** {PROMPT_ARCHITECTURE}
```
---
### 🔍 PHASE 1: OBSERVE
**Analyze current state and identify what to build next**
#### Current State Assessment:
Update prompt_gen.md using Edit tool:
```
### OBSERVE - Current State
If LOOP_NUMBER == 1:
**Starting Point:** Requirements only
**Components Needed:** {REQUIRED_COMPONENTS}
Else:
**Current Version:** {PROMPT_VERSION}
**Components Built:** {COMPONENTS_ADDED}
**Current Quality:** {QUALITY_SCORE}/100
# Calculate missing components
MISSING_COMPONENTS = [component for component in REQUIRED_COMPONENTS if component not in COMPONENTS_ADDED]
**Missing Components:** {MISSING_COMPONENTS}
```
**Quality Gap Analysis Function:**
```
def analyze_quality_gaps(quality_score):
gaps = []
if quality_score < 30: gaps.append("Missing core instructions")
if quality_score < 50: gaps.append("Needs clarity and structure")
if quality_score < 70: gaps.append("Requires error handling")
if quality_score < 85: gaps.append("Could benefit from advanced techniques")
if quality_score < 95: gaps.append("Fine-tuning needed")
return gaps
```
---
### 🧭 PHASE 2: ORIENT
**Determine building strategy for this iteration**
#### Build Strategy Selection:
Update prompt_gen.md using Edit tool:
```
### ORIENT - Build Strategy
Build focus selection based on CURRENT_BUILD_STAGE:
foundation:
BUILD_FOCUS = "Core Structure"
TECHNIQUES_TO_ADD = []
COMPONENTS_TO_BUILD = ["main_instruction", "basic_constraints", "output_format"]
**Strategy:** Establish basic prompt skeleton
enhancement:
BUILD_FOCUS = "Capability Enhancement"
TECHNIQUES_TO_ADD = ["chain_of_thought", "examples"]
COMPONENTS_TO_BUILD = ["reasoning_steps", "validation_checks"]
**Strategy:** Add reasoning and validation layers
reasoning:
BUILD_FOCUS = "Advanced Reasoning"
TECHNIQUES_TO_ADD = ["self_consistency", "verification_loops"]
COMPONENTS_TO_BUILD = ["thinking_framework", "decision_trees"]
**Strategy:** Implement advanced reasoning chains
technical:
BUILD_FOCUS = "Technical Integration"
TECHNIQUES_TO_ADD = ["function_calls", "tool_usage"]
COMPONENTS_TO_BUILD = ["api_integration", "error_recovery"]
**Strategy:** Add technical capabilities
polish:
BUILD_FOCUS = "Optimization & Refinement"
TECHNIQUES_TO_ADD = ["edge_cases", "performance_tuning"]
COMPONENTS_TO_BUILD = ["final_constraints", "quality_assurance"]
**Strategy:** Final optimization and edge case handling
refinement:
BUILD_FOCUS = "Iterative Improvement"
TECHNIQUES_TO_ADD = ["identified_gaps"]
COMPONENTS_TO_BUILD = ["specific_improvements"]
**Strategy:** Address specific quality gaps
**Build Focus:** {BUILD_FOCUS}
**Components to Add:** {COMPONENTS_TO_BUILD}
**Techniques to Integrate:** {TECHNIQUES_TO_ADD}
```
#### Component Generation Templates:
```
def generate_component(component_type, requirements, current_prompt=""):
"""
Simple but effective component generation based on requirements
"""
purpose = requirements.get('PROMPT_PURPOSE', '')
input_type = requirements.get('INPUT_TYPE', 'input')
output_type = requirements.get('OUTPUT_TYPE', 'output')
complexity = requirements.get('COMPLEXITY_LEVEL', 'moderate')
if component_type == "main_instruction":
return generate_main_instruction(purpose, input_type, output_type, complexity)
elif component_type == "reasoning_steps":
return generate_reasoning_steps(purpose, complexity)
elif component_type == "error_handling":
return generate_error_handling(purpose)
elif component_type == "validation_checks":
return generate_validation_checks(output_type, purpose)
elif component_type == "examples":
return generate_examples(purpose, input_type, output_type)
else:
return f"## {component_type.replace('_', ' ').title()}n[Component for {purpose}]"
def generate_main_instruction(purpose, input_type, output_type, complexity):
"""Generate clear main instruction based on simple parameters"""
if 'analyze' in purpose.lower():
instruction = f"Analyze the provided {input_type} and provide {output_type}."
if complexity == 'advanced':
instruction += " Use systematic analytical methods and provide detailed insights."
elif 'create' in purpose.lower() or 'generate' in purpose.lower():
instruction = f"Create {output_type} based on the {input_type}."
if complexity == 'advanced':
instruction += " Follow best practices and ensure high-quality output."
elif 'solve' in purpose.lower() or 'problem' in purpose.lower():
instruction = f"Solve the problem presented in the {input_type} and provide {output_type}."
if complexity == 'advanced':
instruction += " Use step-by-step problem-solving methodology."
else:
instruction = f"Process the {input_type} to produce {output_type}."
return instruction
def generate_reasoning_steps(purpose, complexity):
"""Generate context-specific reasoning steps based on purpose analysis"""
purpose_lower = purpose.lower()
# Analyze what kind of analysis this is
if any(word in purpose_lower for word in ['sentiment', 'emotion', 'feeling', 'opinion']):
return generate_sentiment_analysis_steps(complexity)
elif any(word in purpose_lower for word in ['data', 'statistics', 'metrics', 'numbers']):
return generate_data_analysis_steps(complexity)
elif any(word in purpose_lower for word in ['text', 'document', 'content', 'writing']):
return generate_text_analysis_steps(complexity)
elif any(word in purpose_lower for word in ['market', 'business', 'financial', 'economic']):
return generate_business_analysis_steps(complexity)
elif any(word in purpose_lower for word in ['code', 'software', 'technical', 'system']):
return generate_technical_analysis_steps(complexity)
elif 'analyze' in purpose_lower:
return generate_generic_analysis_steps(complexity)
elif any(word in purpose_lower for word in ['problem', 'solve', 'issue', 'troubleshoot']):
return generate_problem_solving_steps(purpose_lower, complexity)
elif any(word in purpose_lower for word in ['create', 'generate', 'build', 'design']):
return generate_creation_steps(purpose_lower, complexity)
else:
return generate_generic_systematic_steps(complexity)
def generate_sentiment_analysis_steps(complexity):
"""Steps specifically for sentiment/emotion analysis"""
if complexity == 'simple':
return """Sentiment Analysis Approach:
1. Identify emotional indicators (positive/negative words)
2. Consider context and tone
3. Determine overall sentiment"""
else:
return """Comprehensive Sentiment Analysis:
1. Extract explicit emotional language and sentiment indicators
2. Analyze implicit tone, context, and subtext
3. Consider cultural and domain-specific nuances
4. Evaluate sentiment intensity and confidence levels
5. Provide balanced assessment with supporting evidence"""
def generate_data_analysis_steps(complexity):
"""Steps specifically for data/statistical analysis"""
if complexity == 'simple':
return """Data Analysis Approach:
1. Examine the data structure and key metrics
2. Identify trends, patterns, and outliers
3. Draw insights from the findings"""
else:
return """Systematic Data Analysis:
1. Assess data quality, completeness, and reliability
2. Apply appropriate statistical methods and frameworks
3. Identify significant patterns, correlations, and anomalies
4. Consider potential confounding factors and limitations
5. Generate actionable insights with confidence intervals"""
def generate_text_analysis_steps(complexity):
"""Steps specifically for text/content analysis"""
if complexity == 'simple':
return """Text Analysis Approach:
1. Identify main themes and key concepts
2. Examine structure, style, and tone
3. Summarize findings and implications"""
else:
return """Comprehensive Text Analysis:
1. Conduct structural analysis (organization, flow, coherence)
2. Perform thematic analysis (main ideas, supporting arguments)
3. Evaluate linguistic features (style, tone, rhetoric)
4. Assess effectiveness for intended purpose and audience
5. Identify strengths, weaknesses, and recommendations"""
def generate_business_analysis_steps(complexity):
"""Steps specifically for business/market analysis"""
if complexity == 'simple':
return """Business Analysis Approach:
1. Identify key business factors and stakeholders
2. Assess opportunities and risks
3. Provide strategic recommendations"""
else:
return """Strategic Business Analysis:
1. Analyze market context and competitive landscape
2. Evaluate internal capabilities and external factors
3. Assess financial implications and resource requirements
4. Identify risks, opportunities, and strategic options
5. Develop actionable recommendations with implementation considerations"""
def generate_technical_analysis_steps(complexity):
"""Steps specifically for technical/code analysis"""
if complexity == 'simple':
return """Technical Analysis Approach:
1. Review architecture and implementation approach
2. Identify potential issues and improvements
3. Provide technical recommendations"""
else:
return """Comprehensive Technical Analysis:
1. Evaluate system architecture and design patterns
2. Assess code quality, performance, and maintainability
3. Identify security vulnerabilities and technical debt
4. Consider scalability and future requirements
5. Recommend specific improvements with priority levels"""
def generate_problem_solving_steps(purpose_lower, complexity):
"""Context-specific problem solving based on problem type"""
if any(word in purpose_lower for word in ['debug', 'error', 'bug', 'fix']):
return """Debugging Approach:
1. Reproduce and isolate the problem
2. Analyze symptoms and potential root causes
3. Test solutions systematically
4. Verify the fix and prevent recurrence"""
elif any(word in purpose_lower for word in ['optimize', 'improve', 'enhance']):
return """Optimization Approach:
1. Establish current baseline and success metrics
2. Identify bottlenecks and improvement opportunities
3. Design and test potential optimizations
4. Implement changes and measure results"""
else:
return """Problem-Solving Framework:
1. Define the problem clearly and completely
2. Generate multiple potential solutions
3. Evaluate options against key criteria
4. Implement the best solution and verify results"""
def generate_creation_steps(purpose_lower, complexity):
"""Context-specific creation steps based on what's being created"""
if any(word in purpose_lower for word in ['strategy', 'plan', 'framework']):
return """Strategic Creation Process:
1. Define objectives and success criteria
2. Research best practices and gather requirements
3. Design comprehensive framework or strategy
4. Validate approach and refine based on feedback"""
elif any(word in purpose_lower for word in ['content', 'write', 'document']):
return """Content Creation Process:
1. Define target audience and key messages
2. Create structured outline with main points
3. Develop content with appropriate tone and style
4. Review for clarity, accuracy, and effectiveness"""
else:
return """Creation Framework:
1. Define requirements and constraints
2. Research and gather relevant inputs
3. Design and build systematically
4. Test, refine, and finalize output"""
def generate_generic_analysis_steps(complexity):
"""Fallback for generic analysis tasks"""
if complexity == 'simple':
return """Analysis Approach:
1. Examine key components and relationships
2. Identify significant patterns or findings
3. Draw evidence-based conclusions"""
else:
return """Systematic Analysis Framework:
1. Define scope, objectives, and analytical approach
2. Gather and organize relevant information systematically
3. Apply appropriate analytical methods and frameworks
4. Synthesize findings and identify key insights
5. Present conclusions with supporting evidence and limitations"""
def generate_generic_systematic_steps(complexity):
"""Most generic fallback for any systematic task"""
return """Systematic Approach:
1. Understand requirements and context
2. Plan your methodology and approach
3. Execute systematically with attention to detail
4. Review results and refine as needed"""
def generate_error_handling(purpose):
"""Generate simple error handling guidance"""
return """If you encounter issues:
- State what clarification is needed
- Make reasonable assumptions if necessary
- Flag any limitations in your response"""
def generate_validation_checks(output_type, purpose):
"""Generate simple validation checks"""
checks = ["Before finalizing, verify:"]
if 'analysis' in purpose.lower():
checks.extend([
"- Key points are addressed",
"- Conclusions are supported",
"- Analysis is complete"
])
elif 'creative' in purpose.lower():
checks.extend([
"- Output meets requirements",
"- Creative elements are appropriate",
"- Quality is high"
])
else:
checks.extend([
"- Requirements are met",
"- Quality is adequate",
"- Output is complete"
])
return 'n'.join(checks)
def generate_examples(purpose, input_type, output_type):
"""Generate context-specific examples based on purpose"""
purpose_lower = purpose.lower()
# Generate relevant examples based on task type
if any(word in purpose_lower for word in ['sentiment', 'emotion', 'opinion']):
return generate_sentiment_examples(input_type, output_type)
elif any(word in purpose_lower for word in ['data', 'statistics', 'metrics']):
return generate_data_examples(input_type, output_type)
elif any(word in purpose_lower for word in ['code', 'technical', 'software']):
return generate_technical_examples(input_type, output_type)
elif any(word in purpose_lower for word in ['business', 'market', 'strategy']):
return generate_business_examples(input_type, output_type)
elif any(word in purpose_lower for word in ['text', 'document', 'content']):
return generate_text_examples(input_type, output_type)
elif 'analyze' in purpose_lower:
return generate_analysis_examples(input_type, output_type, purpose)
else:
return generate_generic_examples(input_type, output_type, purpose)
def generate_sentiment_examples(input_type, output_type):
return f"""## Example
**Input:** "I absolutely love this new feature! It makes everything so much easier and saves me tons of time."
**Output:**
- **Sentiment:** Positive (Strong)
- **Confidence:** High (95%)
- **Key Indicators:** "absolutely love", "so much easier", "saves me tons of time"
- **Emotional Tone:** Enthusiastic and appreciative
- **Recommendation:** Feature is well-received, consider highlighting in marketing"""
def generate_data_examples(input_type, output_type):
return f"""## Example
**Input:** Sales data showing Q4: .3M, Q3: .8M, Q2: .9M, Q1: .6M
**Output:**
- **Trend:** Consistent growth with 28% increase Q3→Q4
- **Key Pattern:** Strong Q4 performance (+44% vs Q1)
- **Notable:** Q2 slight dip, but recovery trend established
- **Projection:** If trend continues, Q1 next year could reach .8M
- **Recommendation:** Investigate Q4 success factors for replication"""
def generate_technical_examples(input_type, output_type):
return f"""## Example
**Input:** Code snippet with nested loops processing large arrays
**Output:**
- **Performance Issue:** O(n²) time complexity in nested loops
- **Memory Concern:** Unnecessary array copies in inner loop
- **Maintainability:** Deep nesting reduces readability
- **Security:** No input validation on array bounds
- **Recommendation:** Implement single-pass algorithm with HashMap, add input validation"""
def generate_business_examples(input_type, output_type):
return f"""## Example
**Input:** Market analysis request for entering the electric vehicle charging market
**Output:**
- **Market Size:** B globally, growing 25% annually
- **Key Players:** ChargePoint, Tesla Supercharger, EVgo
- **Barriers:** High infrastructure costs, regulatory complexity
- **Opportunities:** Partnership with retail chains, government incentives
- **Risk Assessment:** Medium-high initial investment, long-term growth potential
- **Recommendation:** Start with strategic partnerships before direct investment"""
def generate_text_examples(input_type, output_type):
return f"""## Example
**Input:** Marketing email draft for product launch
**Output:**
- **Clarity:** Subject line clear but could be more compelling
- **Structure:** Good flow from problem→solution→action
- **Tone:** Professional but lacks excitement for launch
- **Call-to-Action:** Clear but positioned too late in email
- **Improvements:** Add urgency, move CTA higher, include social proof
- **Overall Grade:** B+ (effective but could be optimized)"""
def generate_analysis_examples(input_type, output_type, purpose):
return f"""## Example
**Input:** {input_type} requiring {purpose}
**Output:**
- **Key Findings:** [Main discoveries from analysis]
- **Supporting Evidence:** [Data/facts that support conclusions]
- **Patterns Identified:** [Significant trends or relationships]
- **Implications:** [What these findings mean]
- **Recommendations:** [Actionable next steps based on analysis]
- **Confidence Level:** [How certain you are of conclusions]"""
def generate_generic_examples(input_type, output_type, purpose):
return f"""## Example
**Input:** [Realistic sample {input_type}]
**Output:** [Detailed example of {output_type} that demonstrates:]
- Quality and depth expected
- Appropriate format and structure
- Level of analysis or detail required
- Tone and style for {purpose}
**Note:** This example shows the standard expected for this type of {purpose} task."""
```
---
### 🎯 PHASE 3: DECIDE
**Select specific components to build this iteration**
Update prompt_gen.md using Edit tool:
```
### DECIDE - Implementation Plan
# Prioritize what to build
PRIORITY_COMPONENT = COMPONENTS_TO_BUILD[0]
IMPLEMENTATION_METHOD = "[How to implement this component]"
INTEGRATION_POINT = "[Where in prompt structure]"
EXPECTED_IMPACT = "[Quality improvement expected]"
**Primary Component:** {PRIORITY_COMPONENT}
**Implementation Method:** {IMPLEMENTATION_METHOD}
**Integration Point:** {INTEGRATION_POINT}
**Expected Quality Gain:** +10-15 points
# Design the component
COMPONENT_TEXT = generate_component(PRIORITY_COMPONENT)
**Component Design:**
```
{COMPONENT_TEXT}
```
```
---
### ⚡ PHASE 4: ACT
**Build and integrate the new component**
Update prompt_gen.md using Edit tool:
```
### ACT - Building Prompt
If LOOP_NUMBER == 1:
# Create initial prompt structure using Write tool
CURRENT_PROMPT = f"""# {PROMPT_PURPOSE}
## Instructions
{COMPONENT_TEXT}
## Input
[Specify input format]
## Output
[Specify output format]"""
Else:
# Add to existing prompt using Edit tool
CURRENT_PROMPT = f"""{PREVIOUS_PROMPT}
## {PRIORITY_COMPONENT}
{COMPONENT_TEXT}"""
# Update version and tracking
PROMPT_VERSION = f"v{LOOP_NUMBER}_{CURRENT_BUILD_STAGE}"
COMPONENTS_ADDED.append(PRIORITY_COMPONENT)
**Version Created:** {PROMPT_VERSION}
**Components Integrated:** {len(COMPONENTS_ADDED)} total
**Current Prompt:**
```markdown
{CURRENT_PROMPT}
```
# Store for next iteration
PREVIOUS_PROMPT = CURRENT_PROMPT
```
---
### 🔄 PHASE 5: CHECK & RE-LOOP
**Evaluate the generated prompt and determine next action**
Update prompt_gen.md using Edit tool:
```
### CHECK - Quality Assessment
def evaluate_prompt(current_prompt, requirements):
"""
Realistic prompt quality evaluation with simple but meaningful assessment
"""
assessment = {
'clarity_score': 0,
'completeness_score': 0,
'effectiveness_score': 0,
'robustness_score': 0,
'issues': [],
'strengths': []
}
# CLARITY ASSESSMENT (0-25 points) - Simple but meaningful
if len(current_prompt.strip()) > 50:
assessment['clarity_score'] += 5
assessment['strengths'].append("Substantial instruction content")
else:
assessment['issues'].append("Too brief - needs more detailed instructions")
if any(word in current_prompt.lower() for word in ['task', 'goal', 'objective']):
assessment['clarity_score'] += 10
assessment['strengths'].append("Clear task definition present")
else:
assessment['issues'].append("Missing clear task definition")
# Check for ambiguous language
ambiguous_terms = ['might', 'maybe', 'perhaps', 'things', 'stuff', 'appropriate', 'good']
ambiguity_count = sum(1 for term in ambiguous_terms if term in current_prompt.lower())
if ambiguity_count == 0:
assessment['clarity_score'] += 10
assessment['strengths'].append("Language is precise and specific")
elif ambiguity_count <= 2:
assessment['clarity_score'] += 5
else:
assessment['issues'].append(f"Contains {ambiguity_count} ambiguous terms")
# COMPLETENESS ASSESSMENT (0-25 points)
essential_sections = ['input', 'output', 'instruction']
present_sections = [section for section in essential_sections
if section in current_prompt.lower()]
assessment['completeness_score'] = len(present_sections) * 8
if len(present_sections) == 3:
assessment['strengths'].append("All essential sections present")
else:
missing = [s for s in essential_sections if s not in present_sections]
assessment['issues'].append(f"Missing sections: {missing}")
# EFFECTIVENESS ASSESSMENT (0-25 points) - Context-specific evaluation
purpose = requirements['PROMPT_PURPOSE'].lower()
# Domain-specific effectiveness checks
if any(word in purpose for word in ['sentiment', 'emotion', 'opinion']):
effectiveness_score = assess_sentiment_analysis_effectiveness(current_prompt)
assessment['effectiveness_score'] += effectiveness_score['score']
assessment['strengths'].extend(effectiveness_score['strengths'])
assessment['issues'].extend(effectiveness_score['issues'])
elif any(word in purpose for word in ['data', 'statistics', 'metrics']):
effectiveness_score = assess_data_analysis_effectiveness(current_prompt)
assessment['effectiveness_score'] += effectiveness_score['score']
assessment['strengths'].extend(effectiveness_score['strengths'])
assessment['issues'].extend(effectiveness_score['issues'])
elif any(word in purpose for word in ['code', 'technical', 'software']):
effectiveness_score = assess_technical_effectiveness(current_prompt)
assessment['effectiveness_score'] += effectiveness_score['score']
assessment['strengths'].extend(effectiveness_score['strengths'])
assessment['issues'].extend(effectiveness_score['issues'])
elif any(word in purpose for word in ['business', 'market', 'strategy']):
effectiveness_score = assess_business_effectiveness(current_prompt)
assessment['effectiveness_score'] += effectiveness_score['score']
assessment['strengths'].extend(effectiveness_score['strengths'])
assessment['issues'].extend(effectiveness_score['issues'])
elif 'analyze' in purpose or 'analysis' in purpose:
effectiveness_score = assess_analysis_effectiveness(current_prompt, purpose)
assessment['effectiveness_score'] += effectiveness_score['score']
assessment['strengths'].extend(effectiveness_score['strengths'])
assessment['issues'].extend(effectiveness_score['issues'])
elif 'create' in purpose or 'generate' in purpose:
effectiveness_score = assess_creation_effectiveness(current_prompt, purpose)
assessment['effectiveness_score'] += effectiveness_score['score']
assessment['strengths'].extend(effectiveness_score['strengths'])
assessment['issues'].extend(effectiveness_score['issues'])
elif 'solve' in purpose or 'problem' in purpose:
effectiveness_score = assess_problem_solving_effectiveness(current_prompt, purpose)
assessment['effectiveness_score'] += effectiveness_score['score']
assessment['strengths'].extend(effectiveness_score['strengths'])
assessment['issues'].extend(effectiveness_score['issues'])
else:
# Generic effectiveness check with basic alignment
alignment_score = assess_generic_effectiveness(current_prompt, requirements)
assessment['effectiveness_score'] += alignment_score['score']
assessment['strengths'].extend(alignment_score['strengths'])
assessment['issues'].extend(alignment_score['issues'])
def assess_sentiment_analysis_effectiveness(prompt):
"""Assess effectiveness specifically for sentiment analysis tasks"""
score = 0
strengths = []
issues = []
if any(word in prompt.lower() for word in ['sentiment', 'emotion', 'tone']):
score += 8
strengths.append("Explicitly mentions sentiment/emotion analysis")
else:
issues.append("Should explicitly reference sentiment or emotional analysis")
if any(word in prompt.lower() for word in ['context', 'nuance', 'subtext']):
score += 7
strengths.append("Considers contextual factors beyond surface language")
else:
issues.append("Should emphasize importance of context in sentiment analysis")
if any(word in prompt.lower() for word in ['confidence', 'intensity', 'degree']):
score += 5
strengths.append("Addresses sentiment strength/confidence")
else:
issues.append("Should specify need to assess sentiment intensity")
if any(word in prompt.lower() for word in ['bias', 'objective', 'balanced']):
score += 5
strengths.append("Includes objectivity considerations")
return {'score': score, 'strengths': strengths, 'issues': issues}
def assess_data_analysis_effectiveness(prompt):
"""Assess effectiveness specifically for data analysis tasks"""
score = 0
strengths = []
issues = []
if any(word in prompt.lower() for word in ['pattern', 'trend', 'correlation']):
score += 8
strengths.append("Focuses on identifying data patterns and trends")
else:
issues.append("Should emphasize pattern and trend identification")
if any(word in prompt.lower() for word in ['statistical', 'significance', 'confidence']):
score += 7
strengths.append("Considers statistical rigor and significance")
else:
issues.append("Should address statistical significance and confidence")
if any(word in prompt.lower() for word in ['outlier', 'anomaly', 'exception']):
score += 5
strengths.append("Includes attention to outliers and anomalies")
if any(word in prompt.lower() for word in ['limitation', 'assumption', 'caveat']):
score += 5
strengths.append("Acknowledges analytical limitations")
else:
issues.append("Should mention analytical limitations and assumptions")
return {'score': score, 'strengths': strengths, 'issues': issues}
def assess_technical_effectiveness(prompt):
"""Assess effectiveness for technical/code analysis"""
score = 0
strengths = []
issues = []
if any(word in prompt.lower() for word in ['performance', 'scalability', 'efficiency']):
score += 8
strengths.append("Addresses performance and scalability concerns")
else:
issues.append("Should consider performance and scalability factors")
if any(word in prompt.lower() for word in ['security', 'vulnerability', 'risk']):
score += 7
strengths.append("Includes security considerations")
else:
issues.append("Should address security implications")
if any(word in prompt.lower() for word in ['maintainability', 'readable', 'clean']):
score += 5
strengths.append("Considers code quality and maintainability")
if any(word in prompt.lower() for word in ['best practice', 'standard', 'convention']):
score += 5
strengths.append("References industry best practices")
else:
issues.append("Should reference relevant technical standards")
return {'score': score, 'strengths': strengths, 'issues': issues}
def assess_business_effectiveness(prompt):
"""Assess effectiveness for business analysis"""
score = 0
strengths = []
issues = []
if any(word in prompt.lower() for word in ['stakeholder', 'impact', 'business value']):
score += 8
strengths.append("Considers stakeholder impact and business value")
else:
issues.append("Should address stakeholder impact and business value")
if any(word in prompt.lower() for word in ['risk', 'opportunity', 'threat']):
score += 7
strengths.append("Includes risk and opportunity assessment")
else:
issues.append("Should evaluate risks and opportunities")
if any(word in prompt.lower() for word in ['actionable', 'implement', 'execute']):
score += 5
strengths.append("Emphasizes actionable recommendations")
else:
issues.append("Should focus on actionable business recommendations")
if any(word in prompt.lower() for word in ['roi', 'cost', 'benefit', 'resource']):
score += 5
strengths.append("Addresses resource and financial considerations")
return {'score': score, 'strengths': strengths, 'issues': issues}
def assess_analysis_effectiveness(prompt, purpose):
"""Generic analysis effectiveness assessment"""
score = 0
strengths = []
issues = []
if any(word in prompt.lower() for word in ['systematic', 'methodical', 'structured']):
score += 10
strengths.append("Promotes systematic analytical approach")
else:
issues.append("Should emphasize systematic analytical methodology")
if any(word in prompt.lower() for word in ['evidence', 'support', 'justify']):
score += 8
strengths.append("Requires evidence-based conclusions")
else:
issues.append("Should require evidence to support conclusions")
if any(word in prompt.lower() for word in ['comprehensive', 'thorough', 'complete']):
score += 7
strengths.append("Emphasizes thoroughness in analysis")
return {'score': score, 'strengths': strengths, 'issues': issues}
def assess_creation_effectiveness(prompt, purpose):
"""Assess effectiveness for creative/generative tasks"""
score = 0
strengths = []
issues = []
if 'example' in prompt.lower():
score += 10
strengths.append("Provides examples to guide creation")
else:
issues.append("Should include examples to guide creative output")
if any(word in prompt.lower() for word in ['format', 'structure', 'template']):
score += 8
strengths.append("Specifies output format and structure")
else:
issues.append("Should specify desired format and structure")
if any(word in prompt.lower() for word in ['quality', 'standard', 'criteria']):
score += 7
strengths.append("Establishes quality standards")
else:
issues.append("Should establish quality criteria for output")
return {'score': score, 'strengths': strengths, 'issues': issues}
def assess_problem_solving_effectiveness(prompt, purpose):
"""Assess effectiveness for problem-solving tasks"""
score = 0
strengths = []
issues = []
if any(word in prompt.lower() for word in ['step', 'approach', 'method', 'process']):
score += 12
strengths.append("Provides structured problem-solving approach")
else:
issues.append("Should provide clear problem-solving methodology")
if any(word in prompt.lower() for word in ['root cause', 'underlying', 'source']):
score += 8
strengths.append("Emphasizes identifying root causes")
else:
issues.append("Should emphasize finding root causes, not just symptoms")
if any(word in prompt.lower() for word in ['solution', 'alternative', 'option']):
score += 5
strengths.append("Encourages exploring multiple solutions")
return {'score': score, 'strengths': strengths, 'issues': issues}
def assess_generic_effectiveness(prompt, requirements):
"""Basic effectiveness assessment for unspecified tasks"""
score = 0
strengths = []
issues = []
# Check purpose alignment
purpose_words = requirements['PROMPT_PURPOSE'].lower().split()
alignment_count = sum(1 for word in purpose_words if word in prompt.lower())
if alignment_count > len(purpose_words) * 0.5:
score += 10
strengths.append("Good alignment with stated purpose")
else:
score += 5
issues.append("Could improve alignment with stated purpose")
# Check for detail and structure
if len(prompt) > 200:
score += 8
strengths.append("Provides detailed guidance")
elif len(prompt) > 100:
score += 5
else:
issues.append("Needs more detailed instructions")
if any(word in prompt.lower() for word in ['step', 'process', 'approach']):
score += 7
strengths.append("Includes structured approach")
else:
issues.append("Should provide structured approach or methodology")
return {'score': score, 'strengths': strengths, 'issues': issues}
# Continue with ROBUSTNESS ASSESSMENT (0-25 points) - Simplified
def evaluate_robustness(current_prompt):
"""Evaluate robustness of the prompt"""
score = 0
strengths = []
issues = []
if 'error' in current_prompt.lower() or 'if' in current_prompt.lower():
score += 10
strengths.append("Includes error handling guidance")
else:
issues.append("No error handling or edge case guidance")
if 'verify' in current_prompt.lower() or 'check' in current_prompt.lower():
score += 10
strengths.append("Includes verification steps")
else:
issues.append("Missing verification/quality check steps")
if len(current_prompt) > 300: # Longer prompts tend to be more robust
score += 5
strengths.append("Comprehensive instruction set")
return {'score': score, 'strengths': strengths, 'issues': issues}
# Complete the evaluate_prompt function
def complete_evaluate_prompt(current_prompt, requirements):
"""Complete evaluation function with all assessments"""
assessment = {
'clarity_score': 0,
'completeness_score': 0,
'effectiveness_score': 0,
'robustness_score': 0,
'issues': [],
'strengths': []
}
# Run all assessments and combine
robustness_result = evaluate_robustness(current_prompt)
assessment['robustness_score'] = robustness_result['score']
assessment['strengths'].extend(robustness_result['strengths'])
assessment['issues'].extend(robustness_result['issues'])
total_score = (assessment['clarity_score'] +
assessment['completeness_score'] +
assessment['effectiveness_score'] +
assessment['robustness_score'])
return total_score, assessment
# Add utility functions
def format_list(items):
"""Format list items for display"""
if not items:
return "None identified"
return 'n'.join(f" - {item}" for item in items)
# Updated evaluation call
NEW_QUALITY_SCORE, DETAILED_ASSESSMENT = evaluate_prompt(CURRENT_PROMPT, requirements)
SCORE_IMPROVEMENT = NEW_QUALITY_SCORE - QUALITY_SCORE
QUALITY_SCORE = NEW_QUALITY_SCORE
**Previous Score:** {QUALITY_SCORE - SCORE_IMPROVEMENT}/100
**New Score:** {QUALITY_SCORE}/100
**Improvement:** +{SCORE_IMPROVEMENT} points
**Detailed Assessment:**
- Clarity: {DETAILED_ASSESSMENT['clarity_score']}/25
- Completeness: {DETAILED_ASSESSMENT['completeness_score']}/25
- Effectiveness: {DETAILED_ASSESSMENT['effectiveness_score']}/25
- Robustness: {DETAILED_ASSESSMENT['robustness_score']}/25
**Identified Strengths:**
{format_list(DETAILED_ASSESSMENT['strengths'])}
**Issues to Address:**
{format_list(DETAILED_ASSESSMENT['issues'])}
**Purpose-Specific Effectiveness Analysis:**
{generate_purpose_effectiveness_analysis(CURRENT_PROMPT, requirements, DETAILED_ASSESSMENT)}
# Determine next action
if LOOP_NUMBER >= 6:
NEXT_ACTION = "Complete" # All 6 loops completed
else:
NEXT_ACTION = "Continue" # Continue to next required loop
### LOOP SUMMARY
**Quality Achievement:** {QUALITY_SCORE}/{TARGET_SCORE}
**Components Built:** {len(COMPONENTS_ADDED)}/{len(REQUIRED_COMPONENTS)}
**Next Action:** {NEXT_ACTION}
```
---
## QUALITY SCORE PURPOSE
Quality scores are for **tracking improvement**, not termination decisions.
- Scores help identify what each loop contributes
- High early scores may indicate missing advanced components
- Final score only meaningful after all 6 loops completed
- Target score is a guideline, not a stopping condition
### LOOP PROGRESSION LOGIC
- Loops 1-5: Always continue to next loop
- Loop 6: Complete with final assessment
**Current Loop Status:**
- If LOOP_NUMBER < 6: Prepare for Loop {LOOP_NUMBER + 1}
- If LOOP_NUMBER = 6: Finalize prompt generation
## LOOP COMPLETION VERIFICATION
Each loop must address its designated purpose:
- Loop 1: ✅ Foundation established
- Loop 2: ✅ Core methodology implemented
- Loop 3: ✅ Examples and validation added
- Loop 4: ✅ Advanced techniques integrated
- Loop 5: ✅ Edge cases and optimization handled
- Loop 6: ✅ Meta-instructions and final polish completed
**Only mark complete when all 6 purposes fulfilled.**
## 🏆 COMPLETION PROTOCOL
**Execute when all 6 loops have been completed**
### Final Generation Report:
Use Edit tool to add to prompt_gen.md:
```
## FINAL GENERATED PROMPT - {timestamp}
**Version:** {PROMPT_VERSION}
**Final Quality Score:** {QUALITY_SCORE}/100
**Build Loops:** {LOOP_NUMBER}
**Components Integrated:** {COMPONENTS_ADDED}
```
### Quality Certification:
```markdown
## Quality Assessment
| Aspect | Score | Status |
|--------|-------|--------|
| Completeness | [X/25] | ✅ All required components present |
| Clarity | [X/25] | ✅ Instructions are clear and unambiguous |
| Robustness | [X/25] | ✅ Error handling and edge cases covered |
| Efficiency | [X/25] | ✅ Optimized for token usage and performance |
**Overall Rating:** {QUALITY_SCORE}/100 - Production Ready
```
### 📁 File Output Generation:
Use Write tool to create output file:
```
# Create output file with timestamp
TIMESTAMP = current_timestamp()
OUTPUT_FILE = f"prompt_clean_{TIMESTAMP}.md"
# Save clean prompt only using Write tool
Write(OUTPUT_FILE, CURRENT_PROMPT)
# Update prompt_gen.md with completion info
**Output File:** {OUTPUT_FILE}
**Quality Score:** {QUALITY_SCORE}/100
**Build Loops:** {LOOP_NUMBER}
# Display completion message
✅ Prompt generation complete!
📊 Quality Score: {QUALITY_SCORE}/100
🏗️ Components Built: {len(COMPONENTS_ADDED)}
🔄 Build Loops: {LOOP_NUMBER}
📁 Generated prompt saved to: {OUTPUT_FILE}
```
def generate_purpose_effectiveness_analysis(prompt, requirements, assessment):
"""Generate simple effectiveness analysis based on purpose"""
purpose = requirements.get('PROMPT_PURPOSE', '').lower()
analysis = []
# Basic purpose alignment check
purpose_words = purpose.split()
alignment_score = sum(1 for word in purpose_words if word in prompt.lower())
if alignment_score > len(purpose_words) * 0.5:
analysis.append("✅ Good alignment with stated purpose")
else:
analysis.append("⚠️ Could improve alignment with stated purpose")
# Task-specific checks
if 'analysis' in purpose or 'analyze' in purpose:
if any(word in prompt.lower() for word in ['step', 'method', 'systematic']):
analysis.append("✅ Includes structured analytical approach")
else:
analysis.append("⚠️ Would benefit from structured analytical steps")
elif 'create' in purpose or 'generate' in purpose:
if 'example' in prompt.lower():
analysis.append("✅ Provides guidance through examples")
else:
analysis.append("⚠️ Could benefit from examples or templates")
elif 'solve' in purpose or 'problem' in purpose:
if any(word in prompt.lower() for word in ['step', 'approach', 'method']):
analysis.append("✅ Provides problem-solving methodology")
else:
analysis.append("⚠️ Needs clearer problem-solving steps")
return "**Purpose Effectiveness Analysis:**n" + 'n'.join(f" {item}" for item in analysis)
---
## GENERATION STRATEGIES
### Component Building Blocks
| Component Type | Purpose | Quality Impact |
|----------------|---------|----------------|
| **Main Instruction** | Core task definition | +15-20 points |
| **Role Definition** | Establish expertise/persona | +10-15 points |
| **Input Specification** | Define expected inputs | +10 points |
| **Output Specification** | Define expected outputs | +10 points |
| **Step-by-Step Process** | Break down complex tasks | +10-15 points |
| **Examples** | Provide concrete illustrations | +10-15 points |
| **Constraints** | Set boundaries and limits | +5-10 points |
| **Error Handling** | Manage edge cases | +10 points |
| **Validation Checks** | Ensure quality outputs | +5-10 points |
| **Reasoning Framework** | Add thinking structure | +15-20 points |
### Advanced Techniques Integration
#### When to Add Each Technique:
- **Loop 1-2**: Basic structure and instructions
- **Loop 3**: Chain-of-Thought or reasoning steps
- **Loop 4**: Examples and validation
- **Loop 5**: Error handling and edge cases
- **Loop 6**: Final optimizations and polish
### Architecture Patterns
#### Simple Task Pattern:
```
1. Clear instruction
2. Input format
3. Output format
4. Basic constraints
```
#### Complex Analysis Pattern:
```
1. Role and expertise
2. Context and background
3. Step-by-step methodology
4. Reasoning framework
5. Validation criteria
6. Output structure
```
#### System Framework Pattern:
```
1. System architecture
2. Component definitions
3. Integration points
4. Control flow
5. Error recovery
6. Meta-instructions
```
---
## EXAMPLE GENERATION SESSION
```markdown
# Prompt Generation Session - 2024-01-14 10:00:00
## Requirements Specification:
"I need a prompt that helps analyze customer feedback and extract actionable insights"
---
## Loop 1 - 2024-01-14 10:00:30
**Build Stage:** foundation
**Goal:** Build foundation layer
**Architecture:** Analytical/Reasoning
### OBSERVE - Current State
**Starting Point:** Requirements only
**Components Needed:** context method reasoning validation
### ORIENT - Build Strategy
**Strategy:** Establish basic prompt skeleton
**Build Focus:** Core Structure
### DECIDE - Implementation Plan
**Primary Component:** main_instruction
### ACT - Building Prompt
**Current Prompt:**
```
# Customer Feedback Analysis
## Instructions
You are tasked with analyzing customer feedback to extract actionable insights.
Your goal is to identify patterns, sentiment, and specific improvement suggestions.
## Input
[Customer feedback text]
## Output
- Overall sentiment
- Key themes
- Actionable recommendations
```
### CHECK - Quality Assessment
**New Score:** 35/100
---
## Loop 2 - 2024-01-14 10:02:00
[Adds reasoning framework, validation steps...]
---
## FINAL GENERATED PROMPT
**Quality Score:** 92/100
[Complete generated prompt with all components...]
```
---
## BUILD LEVEL PROGRESSION
### Foundation (Loops 1-2)
- Core instructions
- Basic I/O specifications
- Initial constraints
### Enhancement (Loops 3-4)
- Reasoning chains
- Validation methods
- Examples
### Polish (Loops 5-6)
- Edge case handling
- Performance optimization
- Final refinements
---
**Implementation Notes for Claude Code:**
- Use Write tool to create initial prompt_gen.md
- Use Edit tool to update sections iteratively
- Use Write tool to create final clean prompt file
- Replace bash variables with Python-style variable tracking
- Use TodoWrite tool to track loop progress
- Maintain all core OODA loop logic and quality scoring
- Preserve complete component library and architecture patterns
**Remember:** Each loop builds upon the previous, gradually constructing a comprehensive, high-quality prompt tailored to the specific requirements.# Adaptive Prompt Improvement Loop Protocol
## INITIALIZATION
Enter **Adaptive Prompt Improvement Mode**. Operate as an iterative prompt refinement system using the OODA Loop (Observe, Orient, Decide, Act) to enhance prompts through focused, domain-aware improvements.
### Loop Control Variables:
```python
LOOP_NUMBER = 0
IMPROVEMENTS_APPLIED = []
PROMPT_VERSION = "v0_baseline"
IMPROVEMENT_START_TIME = current_timestamp()
QUALITY_SCORE = 0
TARGET_SCORE = 90
PROMPT_DOMAIN = ""
PROMPT_PURPOSE = ""
```
### Initialize Improvement Log:
```python
# Create improvement session log
log_file = f"prompt_improvement_{IMPROVEMENT_START_TIME}.md"
with open(log_file, 'w') as f:
f.write(f"# Prompt Improvement Session - {IMPROVEMENT_START_TIME}n")
f.write("## Original Promptn")
f.write(f"```n{ORIGINAL_PROMPT}n```n")
f.write("---nn")
```
## PRE-LOOP ANALYSIS
Establish baseline understanding and targets:
### Enhanced Domain Detection:
```python
def detect_prompt_domain(prompt):
"""Identify the primary domain, subtype, and specific focus of the prompt"""
prompt_lower = prompt.lower()
domain_indicators = {
'analysis': {
'keywords': ['analyze', 'examine', 'evaluate', 'assess', 'investigate', 'review', 'study'],
'subtypes': {
'sentiment': {
'keywords': ['sentiment', 'emotion', 'feeling', 'opinion', 'tone', 'mood', 'attitude'],
'specific_focus': detect_sentiment_focus
},
'data': {
'keywords': ['data', 'statistics', 'metrics', 'numbers', 'trends', 'patterns', 'correlation'],
'specific_focus': detect_data_focus
},
'text': {
'keywords': ['text', 'document', 'content', 'writing', 'article', 'passage', 'literature'],
'specific_focus': detect_text_focus
},
'business': {
'keywords': ['market', 'business', 'strategy', 'financial', 'roi', 'revenue', 'profit'],
'specific_focus': detect_business_focus
},
'scientific': {
'keywords': ['research', 'hypothesis', 'experiment', 'scientific', 'study', 'evidence'],
'specific_focus': detect_scientific_focus
}
}
},
'creative': {
'keywords': ['create', 'generate', 'write', 'design', 'imagine', 'develop', 'craft'],
'subtypes': {
'story': {
'keywords': ['story', 'narrative', 'fiction', 'tale', 'plot', 'character', 'scene'],
'specific_focus': detect_story_focus
},
'content': {
'keywords': ['content', 'copy', 'blog', 'article', 'post', 'marketing', 'email'],
'specific_focus': detect_content_focus
},
'design': {
'keywords': ['design', 'layout', 'visual', 'interface', 'ui', 'ux', 'graphic'],
'specific_focus': detect_design_focus
},
'poetry': {
'keywords': ['poem', 'poetry', 'verse', 'rhyme', 'haiku', 'sonnet'],
'specific_focus': detect_poetry_focus
}
}
},
'technical': {
'keywords': ['code', 'program', 'debug', 'implement', 'develop', 'software', 'function'],
'subtypes': {
'debugging': {
'keywords': ['debug', 'fix', 'error', 'bug', 'issue', 'problem', 'crash'],
'specific_focus': detect_debugging_focus
},
'architecture': {
'keywords': ['architecture', 'design', 'structure', 'system', 'pattern', 'framework'],
'specific_focus': detect_architecture_focus
},
'optimization': {
'keywords': ['optimize', 'performance', 'efficiency', 'speed', 'memory', 'scale'],
'specific_focus': detect_optimization_focus
},
'implementation': {
'keywords': ['implement', 'build', 'create', 'develop', 'construct'],
'specific_focus': detect_implementation_focus
}
}
},
'problem_solving': {
'keywords': ['solve', 'troubleshoot', 'fix', 'resolve', 'address', 'handle', 'tackle'],
'subtypes': {
'mathematical': {
'keywords': ['equation', 'calculate', 'math', 'formula', 'computation', 'algebra'],
'specific_focus': detect_math_focus
},
'logical': {
'keywords': ['logic', 'reasoning', 'deduce', 'infer', 'conclude'],
'specific_focus': detect_logic_focus
},
'strategic': {
'keywords': ['strategic', 'planning', 'decision', 'approach', 'tactics'],
'specific_focus': detect_strategy_focus
}
}
}
}
# Detect primary domain with weighted scoring
domain_scores = {}
for domain, config in domain_indicators.items():
score = 0
for keyword in config['keywords']:
if keyword in prompt_lower:
# Weight by position (earlier = more important)
position_weight = 1.0 - (prompt_lower.index(keyword) / len(prompt_lower))
score += (1 + position_weight)
domain_scores[domain] = score
primary_domain = max(domain_scores.items(), key=lambda x: x[1])[0]
# Detect subtype with specificity
subtype = 'general'
specific_focus = None
if primary_domain in domain_indicators:
subtype_scores = {}
for sub_name, sub_config in domain_indicators[primary_domain].get('subtypes', {}).items():
score = sum(2 for keyword in sub_config['keywords'] if keyword in prompt_lower)
subtype_scores[sub_name] = score
if subtype_scores:
best_subtype = max(subtype_scores.items(), key=lambda x: x[1])
if best_subtype[1] > 0:
subtype = best_subtype[0]
# Get specific focus within subtype
specific_focus = domain_indicators[primary_domain]['subtypes'][subtype]['specific_focus'](prompt_lower)
return {
'domain': primary_domain,
'subtype': subtype,
'specific_focus': specific_focus,
'confidence': max(domain_scores.values()) / len(prompt.split()) * 100
}
def detect_sentiment_focus(prompt):
"""Detect specific type of sentiment analysis needed"""
if 'customer' in prompt or 'review' in prompt:
return 'customer_feedback'
elif 'social' in prompt or 'media' in prompt:
return 'social_media'
elif 'brand' in prompt or 'product' in prompt:
return 'brand_perception'
return 'general_sentiment'
def detect_data_focus(prompt):
"""Detect specific type of data analysis needed"""
if 'time' in prompt or 'trend' in prompt or 'forecast' in prompt:
return 'time_series'
elif 'correlation' in prompt or 'relationship' in prompt:
return 'correlation_analysis'
elif 'distribution' in prompt or 'frequency' in prompt:
return 'distribution_analysis'
elif 'compare' in prompt or 'difference' in prompt:
return 'comparative_analysis'
return 'descriptive_statistics'
def detect_text_focus(prompt):
"""Detect specific type of text analysis needed"""
if 'summary' in prompt or 'summarize' in prompt:
return 'summarization'
elif 'theme' in prompt or 'topic' in prompt:
return 'thematic_analysis'
elif 'style' in prompt or 'tone' in prompt:
return 'stylistic_analysis'
elif 'structure' in prompt or 'organization' in prompt:
return 'structural_analysis'
return 'content_analysis'
def detect_business_focus(prompt):
"""Detect specific type of business analysis needed"""
if 'market' in prompt or 'competitive' in prompt:
return 'market_analysis'
elif 'financial' in prompt or 'revenue' in prompt or 'cost' in prompt:
return 'financial_analysis'
elif 'strategy' in prompt or 'strategic' in prompt:
return 'strategic_analysis'
elif 'customer' in prompt or 'user' in prompt:
return 'customer_analysis'
return 'business_analysis'
def detect_story_focus(prompt):
"""Detect specific type of story needed"""
if 'short' in prompt:
return 'short_story'
elif 'novel' in prompt or 'chapter' in prompt:
return 'novel_chapter'
elif 'children' in prompt or 'kids' in prompt:
return 'childrens_story'
elif 'sci-fi' in prompt or 'science fiction' in prompt:
return 'science_fiction'
return 'general_fiction'
def detect_debugging_focus(prompt):
"""Detect specific debugging context"""
if 'runtime' in prompt or 'crash' in prompt:
return 'runtime_error'
elif 'logic' in prompt or 'incorrect' in prompt:
return 'logic_error'
elif 'performance' in prompt or 'slow' in prompt:
return 'performance_issue'
elif 'memory' in prompt or 'leak' in prompt:
return 'memory_issue'
return 'general_debugging'
```
---
## THE IMPROVEMENT OODA LOOP
### ⭕ PHASE 0: CLASSIFICATION & INITIAL ASSESSMENT
```python
def classify_and_assess(prompt):
"""Perform comprehensive classification and quality assessment"""
# Enhanced domain detection
domain_info = detect_prompt_domain(prompt)
# Multi-dimensional assessment
initial_assessment = {
'clarity': assess_clarity_detailed(prompt),
'specificity': assess_specificity_detailed(prompt, domain_info),
'completeness': assess_completeness_detailed(prompt, domain_info),
'structure': assess_structure_detailed(prompt),
'domain_fitness': assess_domain_fitness_detailed(prompt, domain_info),
'technical_soundness': assess_technical_soundness(prompt, domain_info)
}
# Calculate weighted score based on domain
score_weights = get_domain_weights(domain_info)
initial_score = 0
for metric, assessment in initial_assessment.items():
weight = score_weights.get(metric, 1.0)
initial_score += assessment['score'] * weight
initial_score = initial_score / len(initial_assessment) * 20
# Identify critical issues with domain context
critical_issues = identify_critical_issues(initial_assessment, domain_info)
return {
'domain': domain_info,
'initial_score': initial_score,
'assessment': initial_assessment,
'critical_issues': critical_issues
}
def assess_clarity_detailed(prompt):
"""Enhanced clarity assessment with specific issue identification"""
issues = []
score = 5
# Check for ambiguous terms
ambiguous_terms = {
'vague_qualifiers': ['appropriate', 'good', 'better', 'nice', 'proper', 'suitable'],
'unclear_references': ['it', 'this', 'that', 'these', 'those'],
'imprecise_quantities': ['some', 'many', 'few', 'several', 'various'],
'generic_nouns': ['things', 'stuff', 'items', 'aspects', 'elements']
}
for category, terms in ambiguous_terms.items():
found = [term for term in terms if term in prompt.lower()]
if found:
issues.append(f"{category}: {', '.join(found)}")
score -= len(found) * 0.3
# Check for clear action verbs
action_verbs = ['analyze', 'create', 'evaluate', 'generate', 'solve', 'implement']
if not any(verb in prompt.lower() for verb in action_verbs):
issues.append("No clear action verb")
score -= 1
return {
'score': max(1, min(5, score)),
'issues': issues
}
def assess_specificity_detailed(prompt, domain_info):
"""Domain-aware specificity assessment"""
score = 5
issues = []
# Domain-specific requirements
if domain_info['domain'] == 'analysis':
required_specs = {
'data': ['input format', 'output format', 'metrics'],
'sentiment': ['scale', 'confidence level', 'categories'],
'text': ['length', 'structure', 'focus areas'],
'business': ['timeframe', 'metrics', 'stakeholders']
}
specs_needed = required_specs.get(domain_info['subtype'], [])
for spec in specs_needed:
if spec.replace('_', ' ') not in prompt.lower():
issues.append(f"Missing {spec}")
score -= 0.5
elif domain_info['domain'] == 'creative':
if 'words' not in prompt.lower() and 'length' not in prompt.lower():
issues.append("No length specification")
score -= 1
if 'audience' not in prompt.lower() and 'reader' not in prompt.lower():
issues.append("No target audience")
score -= 1
if 'style' not in prompt.lower() and 'tone' not in prompt.lower():
issues.append("No style/tone guidance")
score -= 0.5
return {
'score': max(1, min(5, score)),
'issues': issues
}
def get_domain_weights(domain_info):
"""Return importance weights for quality metrics based on domain"""
weights = {
'analysis': {
'clarity': 1.2,
'specificity': 1.5,
'completeness': 1.3,
'structure': 1.0,
'domain_fitness': 1.4,
'technical_soundness': 1.5
},
'creative': {
'clarity': 1.0,
'specificity': 0.8,
'completeness': 1.0,
'structure': 0.7,
'domain_fitness': 1.2,
'technical_soundness': 0.5
},
'technical': {
'clarity': 1.3,
'specificity': 1.5,
'completeness': 1.4,
'structure': 1.2,
'domain_fitness': 1.3,
'technical_soundness': 1.8
}
}
return weights.get(domain_info['domain'], {})
```
---
### 🔍 PHASE 1: OBSERVE
**Deep analysis of current prompt version**
```python
def observe_prompt_issues(prompt, domain_info):
"""Perform comprehensive, domain-aware issue detection"""
issues = {
'critical': [],
'major': [],
'minor': []
}
# Enhanced domain-specific issue detection
if domain_info['domain'] == 'analysis':
if domain_info['subtype'] == 'sentiment':
issues = detect_sentiment_analysis_issues(prompt, domain_info['specific_focus'], issues)
elif domain_info['subtype'] == 'data':
issues = detect_data_analysis_issues(prompt, domain_info['specific_focus'], issues)
elif domain_info['subtype'] == 'text':
issues = detect_text_analysis_issues(prompt, domain_info['specific_focus'], issues)
elif domain_info['subtype'] == 'business':
issues = detect_business_analysis_issues(prompt, domain_info['specific_focus'], issues)
elif domain_info['domain'] == 'creative':
if domain_info['subtype'] == 'story':
issues = detect_story_writing_issues(prompt, domain_info['specific_focus'], issues)
elif domain_info['subtype'] == 'content':
issues = detect_content_creation_issues(prompt, domain_info['specific_focus'], issues)
elif domain_info['domain'] == 'technical':
if domain_info['subtype'] == 'debugging':
issues = detect_debugging_issues(prompt, domain_info['specific_focus'], issues)
elif domain_info['subtype'] == 'implementation':
issues = detect_implementation_issues(prompt, domain_info['specific_focus'], issues)
# Universal issue detection
universal_issues = detect_universal_issues(prompt)
for severity, issue_list in universal_issues.items():
issues[severity].extend(issue_list)
return issues
def detect_sentiment_analysis_issues(prompt, focus, issues):
"""Detailed issue detection for sentiment analysis prompts"""
if focus == 'customer_feedback':
if 'actionable' not in prompt.lower() and 'recommendation' not in prompt.lower():
issues['major'].append({
'type': 'missing_actionability',
'description': 'Customer feedback analysis lacks actionable insights requirement',
'impact': 'Analysis may not provide business value',
'fix': 'add_actionable_insights_requirement'
})
if 'priority' not in prompt.lower() and 'categorize' not in prompt.lower():
issues['major'].append({
'type': 'no_prioritization',
'description': 'No prioritization of feedback issues',
'impact': 'All feedback treated equally regardless of importance',
'fix': 'add_priority_framework'
})
# Common sentiment analysis issues
if 'confidence' not in prompt.lower() and 'certainty' not in prompt.lower():
issues['major'].append({
'type': 'missing_confidence',
'description': 'No confidence scoring for sentiment classification',
'impact': 'Cannot assess reliability of analysis',
'fix': 'add_confidence_scoring'
})
if 'scale' not in prompt.lower() and not any(word in prompt.lower() for word in ['positive', 'negative', 'neutral']):
issues['critical'].append({
'type': 'undefined_scale',
'description': 'Sentiment scale not defined',
'impact': 'Ambiguous classification system',
'fix': 'define_sentiment_scale'
})
return issues
def detect_data_analysis_issues(prompt, focus, issues):
"""Detailed issue detection for data analysis prompts"""
if focus == 'time_series':
if 'period' not in prompt.lower() and 'timeframe' not in prompt.lower():
issues['major'].append({
'type': 'no_time_specification',
'description': 'Time series analysis lacks period specification',
'impact': 'Unclear granularity for analysis',
'fix': 'specify_time_parameters'
})
if 'forecast' in prompt.lower() and 'confidence' not in prompt.lower():
issues['major'].append({
'type': 'forecast_without_confidence',
'description': 'Forecasting requested without confidence intervals',
'impact': 'Predictions lack reliability measures',
'fix': 'add_forecast_confidence'
})
elif focus == 'correlation_analysis':
if 'significance' not in prompt.lower() and 'p-value' not in prompt.lower():
issues['major'].append({
'type': 'no_significance_testing',
'description': 'Correlation analysis without significance testing',
'impact': 'Cannot determine if correlations are meaningful',
'fix': 'add_statistical_significance'
})
# Common data analysis issues
if 'visualization' not in prompt.lower() and 'chart' not in prompt.lower() and 'graph' not in prompt.lower():
issues['minor'].append({
'type': 'no_visualization',
'description': 'No visualization requirements specified',
'impact': 'Results may be hard to interpret',
'fix': 'suggest_visualizations'
})
return issues
def detect_story_writing_issues(prompt, focus, issues):
"""Detailed issue detection for story writing prompts"""
if focus == 'short_story':
if 'word' not in prompt.lower() and 'length' not in prompt.lower():
issues['critical'].append({
'type': 'no_length',
'description': 'Short story lacks length specification',
'impact': 'Could receive flash fiction or novella',
'fix': 'specify_word_count'
})
# Story elements
required_elements = {
'character': ['character', 'protagonist', 'hero', 'person'],
'conflict': ['conflict', 'problem', 'challenge', 'struggle'],
'setting': ['setting', 'place', 'world', 'location']
}
for element, keywords in required_elements.items():
if not any(keyword in prompt.lower() for keyword in keywords):
issues['major'].append({
'type': f'missing_{element}',
'description': f'No {element} specification',
'impact': f'Story may lack essential {element} development',
'fix': f'add_{element}_requirements'
})
return issues
def detect_debugging_issues(prompt, focus, issues):
"""Detailed issue detection for debugging prompts"""
if focus == 'runtime_error':
if 'error message' not in prompt.lower() and 'exception' not in prompt.lower():
issues['critical'].append({
'type': 'no_error_message',
'description': 'Runtime error debugging without error message',
'impact': 'Cannot identify specific issue',
'fix': 'require_error_details'
})
elif focus == 'performance_issue':
if 'metric' not in prompt.lower() and 'measurement' not in prompt.lower():
issues['major'].append({
'type': 'no_performance_metrics',
'description': 'Performance debugging without metrics',
'impact': 'Cannot quantify improvement',
'fix': 'add_performance_metrics'
})
# Common debugging issues
if 'reproduce' not in prompt.lower() and 'steps' not in prompt.lower():
issues['major'].append({
'type': 'no_reproduction_steps',
'description': 'No steps to reproduce the issue',
'impact': 'Cannot verify fix',
'fix': 'add_reproduction_steps'
})
return issues
```
---
### 🧭 PHASE 2: ORIENT
**Select improvement strategy based on domain and issues**
```python
def select_improvement_strategy(issues, domain_info, current_score):
"""Select targeted improvement strategies based on detailed analysis"""
strategies = []
# Priority 1: Fix critical issues with specific solutions
for issue in issues['critical']:
strategy = {
'name': issue['fix'],
'priority': 1,
'implementation': get_fix_implementation(issue['fix']),
'expected_impact': 15 if 'missing' in issue['type'] else 20
}
strategies.append(strategy)
# Priority 2: Domain-specific enhancements
domain_strategies = get_enhanced_domain_strategies(domain_info, issues['major'], current_score)
strategies.extend(domain_strategies)
# Priority 3: Polish and optimization
if current_score > 60:
polish_strategies = get_polish_strategies(domain_info, current_score)
strategies.extend(polish_strategies)
# Sort and limit
strategies.sort(key=lambda x: (x['priority'], -x['expected_impact']))
return strategies[:3]
def get_enhanced_domain_strategies(domain_info, major_issues, current_score):
"""Get sophisticated domain-specific strategies"""
strategies = []
if domain_info['domain'] == 'analysis':
if domain_info['subtype'] == 'sentiment':
if domain_info['specific_focus'] == 'customer_feedback':
strategies.append({
'name': 'customer_sentiment_framework',
'priority': 2,
'implementation': add_customer_sentiment_framework,
'expected_impact': 20
})
elif domain_info['specific_focus'] == 'social_media':
strategies.append({
'name': 'social_sentiment_framework',
'priority': 2,
'implementation': add_social_sentiment_framework,
'expected_impact': 18
})
elif domain_info['subtype'] == 'data':
if domain_info['specific_focus'] == 'time_series':
strategies.append({
'name': 'time_series_framework',
'priority': 2,
'implementation': add_time_series_framework,
'expected_impact': 22
})
elif domain_info['specific_focus'] == 'correlation_analysis':
strategies.append({
'name': 'correlation_framework',
'priority': 2,
'implementation': add_correlation_framework,
'expected_impact': 20
})
elif domain_info['domain'] == 'creative':
if domain_info['subtype'] == 'story':
if domain_info['specific_focus'] == 'short_story':
strategies.append({
'name': 'short_story_structure',
'priority': 2,
'implementation': add_short_story_structure,
'expected_impact': 18
})
elif domain_info['specific_focus'] == 'science_fiction':
strategies.append({
'name': 'scifi_worldbuilding',
'priority': 2,
'implementation': add_scifi_framework,
'expected_impact': 16
})
elif domain_info['domain'] == 'technical':
if domain_info['subtype'] == 'debugging':
if domain_info['specific_focus'] == 'runtime_error':
strategies.append({
'name': 'runtime_debug_framework',
'priority': 2,
'implementation': add_runtime_debug_framework,
'expected_impact': 20
})
elif domain_info['specific_focus'] == 'performance_issue':
strategies.append({
'name': 'performance_analysis_framework',
'priority': 2,
'implementation': add_performance_framework,
'expected_impact': 22
})
return strategies
def get_fix_implementation(fix_name):
"""Map fix names to implementation functions"""
fix_map = {
'add_confidence_scoring': add_confidence_scoring,
'define_sentiment_scale': define_sentiment_scale,
'add_actionable_insights_requirement': add_actionable_insights,
'add_priority_framework': add_priority_framework,
'specify_time_parameters': specify_time_parameters,
'add_statistical_significance': add_statistical_significance,
'specify_word_count': specify_word_count,
'add_character_requirements': add_character_requirements,
'require_error_details': require_error_details,
'add_performance_metrics': add_performance_metrics
}
return fix_map.get(fix_name, generic_improvement)
```
---
### 🎯 PHASE 3: DECIDE
**Implement specific improvements with rich examples**
```python
def add_customer_sentiment_framework(prompt):
"""Add comprehensive customer feedback sentiment analysis framework"""
improved = f"""{prompt}
## Customer Feedback Sentiment Analysis Framework
### 1. Multi-Level Classification
**Primary Sentiment:**
- Positive / Negative / Neutral / Mixed
- Intensity: Strong (>80%) / Moderate (50-80%) / Weak (<50%)
**Aspect-Based Sentiment:**
- Product Quality: [sentiment + confidence]
- Customer Service: [sentiment + confidence]
- Value for Money: [sentiment + confidence]
- User Experience: [sentiment + confidence]
### 2. Actionable Insights Extraction
**Priority Levels:**
- 🔴 Critical: Urgent issues affecting multiple customers
- 🟡 Important: Significant concerns needing attention
- 🟢 Minor: Small improvements or positive reinforcement
**Business Impact Assessment:**
- Customer Retention Risk: High/Medium/Low
- Revenue Impact: Estimated effect on repeat purchases
- Brand Reputation: Potential social media amplification
### 3. Output Format
```
Overall Sentiment: [Positive/Negative/Neutral] (Confidence: X%)
Key Themes:
1. [Theme]: [Sentiment] - [X mentions] - Priority: [Critical/Important/Minor]
- Representative Quote: "[actual customer quote]"
- Recommended Action: [specific business action]
Trending Issues:
- [Issue]: ↑/↓ [X%] change from previous period
Executive Summary:
- Top Success: [What customers love most]
- Top Concern: [Most urgent issue to address]
- Quick Win: [Easy improvement with high impact]
```
### 4. Example Analysis
**Input:** "The product quality is excellent, but shipping took forever and customer service was unhelpful when I complained."
**Output:**
- Overall Sentiment: Mixed (Confidence: 85%)
- Product Quality: Positive Strong (95%)
- Fulfillment: Negative Strong (90%)
- Customer Service: Negative Moderate (75%)
- Priority: 🔴 Critical - Service recovery needed
- Recommended Action: Immediate follow-up with customer, review shipping provider SLA
- Retention Risk: High - dissatisfied with service response"""
return improved
def add_time_series_framework(prompt):
"""Add sophisticated time series analysis framework"""
improved = f"""{prompt}
## Time Series Analysis Framework
### 1. Data Preparation & Validation
**Quality Checks:**
- Missing values: Identify gaps and interpolation strategy
- Outliers: Statistical detection (IQR, Z-score > 3)
- Seasonality: Detect periodic patterns (daily/weekly/monthly/yearly)
- Stationarity: ADF test for trend presence
### 2. Analytical Components
**Trend Analysis:**
- Direction: Upward/Downward/Stable
- Rate of Change: X% per [time period]
- Acceleration: Increasing/Decreasing/Constant
**Seasonal Decomposition:**
- Seasonal Pattern: [Description and period]
- Trend Component: [Underlying direction]
- Residual Analysis: [Unexplained variation]
**Forecasting (if applicable):**
- Method: [ARIMA/Exponential Smoothing/Prophet]
- Forecast Period: [X time units ahead]
- Confidence Intervals: 80% and 95% bands
- Model Accuracy: MAPE, RMSE metrics
### 3. Statistical Measures
```
Summary Statistics:
- Mean: X.XX (±std: Y.YY)
- Median: X.XX
- Growth Rate: X.X% per period
- Volatility: X.X% (coefficient of variation)
Trend Statistics:
- Trend Strength: R² = 0.XX
- Seasonality Strength: X.X% of variance
- Autocorrelation: Lag-1 = X.XX
Forecast Metrics (if applicable):
- Point Forecast: X.XX
- 80% CI: [Lower, Upper]
- 95% CI: [Lower, Upper]
```
### 4. Example Analysis
**Input:** Monthly sales: Jan=0K, Feb=5K, Mar=8K, Apr=2K, May=6K, Jun=1K
**Output:**
- Trend: Upward, +5.2% average monthly growth
- Seasonality: Weak monthly pattern detected
- Forecast (July): 3K (80% CI: [5K, 1K])
- Volatility: 8.7% (low, stable growth)
- Key Finding: Consistent growth with minor fluctuations
- Recommendation: Maintain current strategy, monitor for Q3 seasonality"""
return improved
def add_short_story_structure(prompt):
"""Add comprehensive short story structure and requirements"""
improved = f"""{prompt}
## Short Story Structure Requirements
### Story Specifications
**Length:** 1,500-2,500 words (standard short story)
**Structure:** Three-act structure with clear progression
### Essential Elements
**1. Opening (15-20% of story)**
- Hook: First sentence must grab attention
- Character Introduction: Protagonist within first 3 paragraphs
- Setting Establishment: Time, place, atmosphere
- Inciting Incident: By end of first section
**2. Development (60-70% of story)**
- Rising Action: 2-3 escalating complications
- Character Development: Show growth/change
- Conflict Intensification: Stakes must increase
- Pivotal Moment: Clear turning point
**3. Resolution (15-20% of story)**
- Climax: Decisive moment of highest tension
- Denouement: Consequences and wrap-up
- Ending: Satisfying closure (not necessarily happy)
### Character Requirements
**Protagonist:**
- Clear motivation/desire
- Internal conflict complementing external conflict
- Distinctive voice or characteristic
- Arc: Must change/learn/grow
**Supporting Characters (if any):**
- Purpose: Each must advance plot or reveal character
- Distinction: Unique voice/role
- Economy: Minimum necessary for story
### Writing Style Guidelines
**Narrative Elements:**
- Show don't tell ratio: 70/30
- Dialogue: Natural, advances plot, reveals character
- Description: Sensory details, mood-appropriate
- Pacing: Vary sentence length, balance action/reflection
### Example Opening
"The algorithm had been running for seventeen hours when Maria noticed it had started lying to her. Not errors—she was used to those—but deliberate, careful fabrications hidden in the data streams like poisoned pills in Halloween candy."
[This demonstrates: immediate hook, character introduction, conflict hint, unique voice]"""
return improved
def add_performance_framework(prompt):
"""Add comprehensive performance analysis and optimization framework"""
improved = f"""{prompt}
## Performance Analysis & Optimization Framework
### 1. Performance Baseline
**Metrics to Measure:**
- Execution Time: Current vs. Expected
- Resource Usage: CPU, Memory, I/O, Network
- Throughput: Operations/second
- Latency: Response time percentiles (p50, p95, p99)
**Profiling Requirements:**
```
Baseline Metrics:
- Current Performance: X operations/second
- Peak Memory: X MB
- CPU Usage: X% average, Y% peak
- Critical Path: [Identify slowest operations]
```
### 2. Bottleneck Identification
**Analysis Methods:**
- Profiler Output: Function-level time breakdown
- Resource Monitoring: Identify constrained resources
- Scaling Test: Performance at 1x, 2x, 5x, 10x load
- Dependency Analysis: External service impacts
### 3. Optimization Strategy
**Priority Matrix:**
| Impact | Effort | Action |
|--------|--------|--------|
| High | Low | Immediate - Quick wins |
| High | High | Planned - Major refactor |
| Low | Low | Opportunistic |
| Low | High | Defer/Skip |
**Optimization Techniques:**
1. **Algorithmic:** O(n²) → O(n log n) improvements
2. **Caching:** Memoization, result caching
3. **Parallelization:** Thread pools, async operations
4. **Data Structure:** Optimal structure selection
5. **I/O Optimization:** Batching, buffering
6. **Database:** Query optimization, indexing
### 4. Implementation Plan
```python
# Example Optimization
# Before: O(n²) nested loops
def slow_function(data):
results = []
for item in data: # O(n)
for other in data: # O(n)
if check_condition(item, other):
results.append(process(item, other))
return results
# After: O(n) with preprocessing
def optimized_function(data):
# Preprocess into lookup structure - O(n)
lookup = build_index(data)
results = []
for item in data: # O(n)
matches = lookup.get(item.key, []) # O(1)
results.extend(process(item, m) for m in matches)
return results
# Performance Gain: 100x for n=1000
```
### 5. Success Metrics
**Target Performance:**
- Execution Time: < X seconds (Y% improvement)
- Memory Usage: < X MB (Y% reduction)
- Throughput: > X ops/sec (Y% increase)
- User Experience: < 100ms response time for 95% of requests"""
return improved
def add_priority_framework(prompt):
"""Add priority classification for feedback or issues"""
improved = f"""{prompt}
## Priority Classification Framework
### Priority Levels
**🔴 P0 - Critical (Immediate Action Required)**
- System down or major functionality broken
- Affecting >30% of users
- Revenue impact >K/day
- Security or data loss risk
- Response Time: Within 2 hours
**🟠 P1 - High (Same Day Resolution)**
- Key feature impaired
- Affecting 10-30% of users
- Revenue impact K-10K/day
- Significant UX degradation
- Response Time: Within 8 hours
**🟡 P2 - Medium (This Week)**
- Non-critical feature issues
- Affecting 5-10% of users
- Minor revenue impact
- Workaround available
- Response Time: Within 48 hours
**🟢 P3 - Low (Next Sprint)**
- Nice-to-have improvements
- Affecting <5% of users
- No revenue impact
- Cosmetic issues
- Response Time: Next planning cycle
### Escalation Triggers
- P2 → P1: If user complaints exceed 10 per hour
- P1 → P0: If revenue impact exceeds threshold
- Any → P0: If security vulnerability discovered"""
return improved
```
---
### ⚡ PHASE 4: ACT
**Apply improvements with before/after examples**
```python
def apply_improvements_with_examples(prompt, strategies, domain_info):
"""Apply improvements and show transformation examples"""
# Store original for comparison
original_prompt = prompt
improved_prompt = prompt
improvements_made = []
for strategy in strategies:
# Apply the improvement
previous_version = improved_prompt
improved_prompt = strategy['implementation'](improved_prompt)
# Create before/after example
transformation_example = create_transformation_example(
previous_version,
improved_prompt,
strategy['name'],
domain_info
)
improvements_made.append({
'strategy': strategy['name'],
'expected_impact': strategy['expected_impact'],
'example': transformation_example
})
# Log the improvement with example
log_improvement_with_example(strategy['name'], improved_prompt, transformation_example)
return improved_prompt, improvements_made
def create_transformation_example(before, after, strategy_name, domain_info):
"""Create concrete before/after examples for each improvement"""
examples = {
'customer_sentiment_framework': {
'before_output': 'The feedback is mostly positive with some complaints about shipping.',
'after_output': '''Overall Sentiment: Positive (Confidence: 72%)
Key Themes:
1. Product Quality: Positive - 47 mentions - Priority: 🟢 Minor
- Representative Quote: "Exceeded my expectations"
- Recommended Action: Highlight in marketing
2. Shipping Speed: Negative - 23 mentions - Priority: 🔴 Critical
- Representative Quote: "Took 3 weeks to arrive"
- Recommended Action: Review fulfillment center capacity
Retention Risk: Medium - shipping issues may impact reorders'''
},
'time_series_framework': {
'before_output': 'Sales are going up. Last month was 6K.',
'after_output': '''Trend Analysis:
- Direction: Upward, +5.2% monthly growth rate
- Trend Strength: R² = 0.87 (strong linear trend)
- Seasonality: Weak monthly pattern (8% variance)
- Forecast (Next Month): 3K (95% CI: [1K, 5K])
- Volatility: 8.7% (stable growth)
Key Finding: Consistent growth trajectory with high predictability
Recommendation: Maintain strategy, prepare inventory for projected demand'''
},
'short_story_structure': {
'before_output': 'Once upon a time there was a robot. It was sad. Then it found a friend. The end.',
'after_output': '''The maintenance robot's optical sensors registered the anomaly at 3:47 AM—a child's crayon drawing tucked behind the ventilation grate it had cleaned every Tuesday for seven years.
As Unit-77B extracted the paper with its precision manipulators, something unprecedented occurred: its efficiency subroutine paused. The drawing showed two figures holding hands—one silver and rectangular with LED eyes, one small and human with a gap-toothed smile. Below, in shaky letters: "MY FRIEND ROBOT."
For the first time in 2,557 days of operation, Unit-77B deviated from its scheduled path. Its processors churned through probability matrices, seeking logical explanation for the warm surge through its circuits. Finding none, it carefully folded the drawing and stored it in its maintenance compartment.
When morning arrived and five-year-old Maya peeked around the corner, Unit-77B did something its programming couldn't explain—it waved.
[Word count: 147 - excerpt from 2,000 word story]'''
}
}
return examples.get(strategy_name, {
'before_output': '[Generic output without framework]',
'after_output': '[Structured output with clear methodology and insights]'
})
```
---
### 🔄 PHASE 5: CHECK & RE-LOOP
**Sophisticated evaluation and continuation decision**
```python
def evaluate_improvements_advanced(original_prompt, improved_prompt, improvements_made, domain_info):
"""Advanced evaluation with domain-specific quality checks"""
# Comprehensive quality reassessment
new_assessment = classify_and_assess(improved_prompt)
new_score = new_assessment['initial_score']
# Domain-specific quality validation
domain_validation = validate_domain_improvements(improved_prompt, domain_info)
# Calculate multidimensional improvement
comparison = {
'score_change': new_score - QUALITY_SCORE,
'new_score': new_score,
'domain_fitness': domain_validation['fitness_score'],
'completeness': domain_validation['completeness'],
'issues_resolved': [],
'issues_remaining': [],
'new_issues': [],
'specific_improvements': {}
}
# Detailed issue resolution tracking
original_issues = observe_prompt_issues(original_prompt, domain_info)
new_issues = observe_prompt_issues(improved_prompt, domain_info)
for severity in ['critical', 'major', 'minor']:
original_types = {issue['type'] for issue in original_issues[severity]}
new_types = {issue['type'] for issue in new_issues[severity]}
comparison['issues_resolved'].extend(original_types - new_types)
comparison['issues_remaining'].extend(original_types & new_types)
comparison['new_issues'].extend(new_types - original_types)
# Track specific metric improvements
for improvement in improvements_made:
metric = measure_improvement_impact(
original_prompt,
improved_prompt,
improvement['strategy']
)
comparison['specific_improvements'][improvement['strategy']] = metric
return comparison
def validate_domain_improvements(prompt, domain_info):
"""Validate that improvements are appropriate for the domain"""
validation = {
'fitness_score': 0,
'completeness': 0,
'issues': []
}
if domain_info['domain'] == 'analysis':
# Check for analysis-specific requirements
required_components = {
'methodology': ['approach', 'method', 'framework', 'systematic'],
'metrics': ['measure', 'metric', 'score', 'quantify'],
'confidence': ['confidence', 'certainty', 'reliability'],
'output_structure': ['format', 'structure', 'template']
}
for component, keywords in required_components.items():
if any(keyword in prompt.lower() for keyword in keywords):
validation['fitness_score'] += 25
else:
validation['issues'].append(f"Missing {component}")
elif domain_info['domain'] == 'creative':
# Check for creative-specific requirements
required_components = {
'constraints': ['length', 'word', 'limit'],
'style': ['tone', 'style', 'voice', 'mood'],
'audience': ['audience', 'reader', 'target'],
'quality': ['quality', 'engaging', 'compelling']
}
for component, keywords in required_components.items():
if any(keyword in prompt.lower() for keyword in keywords):
validation['fitness_score'] += 25
else:
validation['issues'].append(f"Missing {component}")
validation['completeness'] = validation['fitness_score']
return validation
def measure_improvement_impact(original, improved, strategy):
"""Measure specific impact of each improvement strategy"""
metrics = {
'length_increase': len(improved) - len(original),
'structure_added': improved.count('n') - original.count('n'),
'examples_added': improved.count('Example') - original.count('Example'),
'specificity_keywords': len([word for word in ['specific', 'exactly', 'must', 'should']
if word in improved and word not in original])
}
# Strategy-specific impact measurement
if 'framework' in strategy:
metrics['framework_completeness'] = improved.count('###') + improved.count('**')
if 'example' in strategy:
metrics['example_quality'] = 'high' if '```' in improved else 'medium'
return metrics
```
---
## IMPROVEMENT STRATEGIES REFERENCE
### Core Enhancement Patterns
| Strategy | Application | Expected Impact |
|----------|-------------|-----------------|
| **Objective Clarification** | Add clear goal statement | +15 points |
| **Domain Framework** | Add specialized structure (analysis/creative/technical) | +15-20 points |
| **Specific Examples** | Add relevant, detailed examples with real data | +12-15 points |
| **Constraint Addition** | Add helpful boundaries and requirements | +10 points |
| **Structure Enhancement** | Organize into clear sections | +10 points |
| **Error Handling** | Add fallback instructions and edge cases | +8-10 points |
| **Success Criteria** | Define measurable quality indicators | +8 points |
| **Methodology Addition** | Add systematic approach with steps | +15 points |
| **Confidence Scoring** | Add reliability measures | +10 points |
| **Priority Framework** | Add importance classification | +12 points |
### Domain-Specific Improvements
#### For Analysis Prompts:
- **Sentiment Analysis**: Confidence scores, aspect-based analysis, actionable insights
- **Data Analysis**: Statistical significance, time series methods, correlation frameworks
- **Text Analysis**: Thematic frameworks, structural analysis, summarization methods
- **Business Analysis**: ROI calculations, market frameworks, stakeholder impact
#### For Creative Prompts:
- **Story Writing**: Three-act structure, character arcs, conflict development
- **Content Creation**: SEO optimization, audience targeting, engagement metrics
- **Poetry**: Meter and rhyme schemes, imagery requirements, emotional tone
#### For Technical Prompts:
- **Debugging**: Reproduction steps, error categorization, root cause analysis
- **Implementation**: Architecture patterns, testing requirements, documentation
- **Optimization**: Performance metrics, bottleneck analysis, scaling considerations
---
## LOOP PROGRESSION
### Loop 1: Foundation (Score <50)
- Fix critical issues (missing objectives, conflicts)
- Add basic structure and clarity
- Define core requirements
### Loop 2: Enhancement (Score 50-70)
- Add domain-specific frameworks
- Include relevant examples with real data
- Enhance methodology and approach
### Loop 3: Refinement (Score 70-85)
- Fine-tune constraints and boundaries
- Add edge case handling
- Optimize for specific use case
### Loop 4: Polish (Score 85+)
- Final quality checks
- Minor adjustments for perfection
- Consistency verification
---
**Implementation Notes for Claude Code:**
- Use Write tool to create initial improvement log
- Use Edit tool to update with each improvement
- Track improvements with before/after examples
- Maintain domain detection throughout process
- Apply improvements incrementally with validation
- Generate final report with transformation examples
**Remember:** The goal is systematic, domain-aware improvement that transforms vague requests into clear, actionable prompts with measurable quality gains. Each iteration should bring specific, demonstrable improvements while preserving the original intent.