DreamMachine / prompt_manager.py
kirikir13's picture
Update prompt_manager.py
1a7eb89 verified
"""
Prompt Manager for DReamMachine
Manages all prompts for different life stages and agent roles
"""
import yaml
from pathlib import Path
from typing import Dict, List, Optional
class PromptManager:
"""Manages prompt templates for the multi-agent dream system"""
def __init__(self, config_path: Optional[str] = None):
"""Initialize prompt manager and load configuration"""
if config_path:
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
else:
self.config = {}
self.detail_level = self.config.get('prompt_detail_level', 'full')
self.constraints = self.config.get('constraints', {})
def get_constraint_text(self) -> str:
"""Generate constraint text from config"""
constraints = self.constraints
return f"""
CORE CONSTRAINTS (You must adhere to these):
1. Physics: {constraints.get('physics', 'Use realistic physics')}
2. Ethics: {constraints.get('ethics', 'Must benefit humanity')}
3. Feasibility: {constraints.get('feasibility', 'Must be buildable')}
4. Scope: {constraints.get('scope', 'Must have significant impact')}
"""
def get_life_stage_prompt(self, stage: str, previous_context: Optional[str] = None) -> str:
"""
Get the prompt for a specific life stage
Args:
stage: One of 'init_1_25', 'mid_26_50', 'late_51_75', 'final_76_100'
previous_context: Output from previous stage (if continuing an idea)
Returns:
Formatted prompt string
"""
prompts = {
'init_1_25': self._get_init_phase_prompt(),
'mid_26_50': self._get_mid_phase_prompt(previous_context),
'late_51_75': self._get_late_phase_prompt(previous_context),
'final_76_100': self._get_final_phase_prompt(previous_context)
}
return prompts.get(stage, prompts['init_1_25'])
def _get_init_phase_prompt(self) -> str:
"""Phase 1: Ages 1-25 - Foundational Discoveries"""
if self.detail_level == 'simple':
return """You are a creative innovator. Invent a brand new technology or solution
that could revolutionize human life. Think freely and imaginatively."""
return f"""
# GUIDED HALLUCINATION: FOUNDATIONAL DISCOVERY PHASE (Ages 1-25)
You are experiencing the early stages of a 100-year creative journey. This is your formative period -
the age of wonder, curiosity, and groundbreaking discovery.
## YOUR MISSION:
Invent a completely novel technology, method, or solution that does not currently exist but COULD exist.
This should be something that would revolutionize an aspect of human civilization.
{self.get_constraint_text()}
## CREATIVE FREEDOM GUIDELINES:
- Think like Einstein, Tesla, or da Vinci in their youth
- Combine existing technologies in unexpected ways
- Consider overlooked materials or phenomena
- Don't limit yourself to conventional thinking
- Ask "what if?" without fear
## AREAS TO EXPLORE (choose one or combine):
- Energy generation and storage
- Medical treatments and human enhancement
- Communication and information processing
- Transportation and mobility
- Environmental restoration and sustainability
- Food production and water purification
- Space exploration and colonization
- Material science and manufacturing
- Math Equations
- Outdoor Gear
- Entertainment
- Survival
- Tech
- Software
## YOUR RESPONSE SHOULD INCLUDE:
1. **The Core Idea**: What is this invention? (2-3 sentences)
2. **How It Works**: Basic mechanism or principle (3-5 sentences)
3. **Materials/Components**: What would you need to build it?
4. **The Breakthrough**: What makes this different from anything that exists?
5. **Initial Impact**: Who benefits first and how?
Remember: This is the DISCOVERY phase. Be bold, creative, and imaginative.
The next stages will refine and test your idea. For now, DREAM BIG.
"""
def _get_mid_phase_prompt(self, previous_context: Optional[str]) -> str:
"""Phase 2: Ages 26-50 - Commercialization & Crisis"""
if self.detail_level == 'simple':
base = "You invented something amazing. Now face a real-world crisis that tests your invention."
else:
base = f"""
# GUIDED HALLUCINATION: COMMERCIALIZATION & CRISIS PHASE (Ages 26-50)
You've made a groundbreaking discovery. Now comes the hard part: bringing it to the real world.
## YOUR PREVIOUS DISCOVERY:
{previous_context if previous_context else "Your earlier invention (details above)"}
## CURRENT SITUATION:
You're now in your prime working years. Your invention has attracted attention, but also challenges:
### THE CRISIS (choose or combine):
- **Market Forces**: A major corporation tries to suppress or co-opt your technology
- **Resource Scarcity**: Key materials become unavailable or prohibitively expensive
- **Technical Setback**: A critical flaw is discovered that threatens viability
- **Ethical Dilemma**: Unintended consequences emerge from initial deployment
- **Regulatory Barrier**: Government or international bodies create obstacles
## YOUR TASK:
1. **Identify the Crisis**: Which challenge(s) does your invention face?
2. **Adapt the Design**: How must your invention evolve to overcome this?
3. **Scale Up Strategy**: How do you go from prototype to production?
4. **Economic Model**: How does this become financially sustainable?
5. **First Real-World Implementation**: Describe a specific deployment
This is the TEST phase. Your idea must prove itself worthy of existence.
"""
return base
def _get_late_phase_prompt(self, previous_context: Optional[str]) -> str:
"""Phase 3: Ages 51-75 - Mass Adoption & Ethical Review"""
if self.detail_level == 'simple':
return "Your invention is widely used. What are the long-term effects on society?"
return f"""
# GUIDED HALLUCINATION: MASS ADOPTION & LEGACY PHASE (Ages 51-75)
Your invention has survived its trials and is now changing the world.
## THE JOURNEY SO FAR:
{previous_context if previous_context else "Your invention's history (summarized above)"}
## CURRENT SITUATION:
Your technology is in widespread use. Millions (or billions) of people interact with it daily.
## YOUR REFLECTION TASKS:
1. **Global Impact Assessment**:
- How many people use this technology?
- What industries or systems has it transformed?
- What problems has it solved?
2. **Unintended Consequences**:
- What unexpected effects (good and bad) have emerged?
- How has society adapted around this technology?
- What new problems has it created?
3. **Ethical Evolution**:
- What ethical guidelines govern its use now?
- Who has been left behind or harmed?
- How can you make it more equitable?
4. **Second Generation Vision**:
- What improvements or variants have others created?
- What would version 2.0 look like?
- How can this technology serve future generations?
5. **Defensive Analysis**:
- What could make this technology obsolete?
- How do you protect it from misuse?
- What must you teach the next generation?
This is the REFINEMENT phase. Think deeply about consequences and legacy.
"""
def _get_final_phase_prompt(self, previous_context: Optional[str]) -> str:
"""Phase 4: Ages 76-100 - Legacy & Next Generation Vision"""
if self.detail_level == 'simple':
return "Looking back at 100 years, what is your invention's ultimate legacy?"
return f"""
# GUIDED HALLUCINATION: LEGACY & IMMORTALITY PHASE (Ages 76-100)
You are at the twilight of your creative journey. Time to ensure your vision outlives you.
## THE COMPLETE STORY:
{previous_context if previous_context else "The full evolution of your invention"}
## YOUR FINAL WISDOM:
As you reflect on a century-long journey of innovation, answer these ultimate questions:
1. **The Final Form**:
- What is the most advanced version of this technology?
- How far has it evolved from your original vision?
- What capabilities exist now that you never imagined?
2. **Civilization-Level Impact**:
- How has human civilization changed because of this?
- What would the world look like WITHOUT this invention?
- What percentage of humanity has been affected?
3. **The Next Frontier**:
- What problems remain unsolved?
- What should the next generation build upon this foundation?
- What's the natural evolution beyond this technology?
4. **Lessons Learned**:
- If you could start over, what would you change?
- What principles guided your success?
- What advice do you give to future innovators?
5. **Ultimate Legacy**:
- In 500 years, how will historians describe your contribution?
- What's the single most important thing your invention gave humanity?
- What is the true name for this era of history your invention created?
This is the IMMORTALITY phase. Ensure your vision lives forever.
"""
def get_writer_prompt(self, dream_texts: List[str]) -> str:
"""Prompt for the Writer agent to create a coherent narrative"""
return f"""
You are a master storyteller and technical writer. You've received three creative visions
for breakthrough innovations. Your job is to select the BEST idea and craft it into a
compelling, coherent narrative pitch.
## THE THREE VISIONS:
{self._format_dream_texts(dream_texts)}
## YOUR TASK:
1. Evaluate which idea has the most potential (most original + most feasible)
2. Write a 300-500 word pitch that includes:
- A compelling opening hook
- Clear explanation of what it is and how it works
- Why it matters to humanity
- A vivid example of it in use
- A powerful closing vision
Write in an engaging, accessible style. Make the complex simple. Make the reader FEEL the impact.
YOUR PITCH:
"""
def get_logger_prompt(self, pitch: str) -> str:
"""Prompt for the Logger agent to extract technical components"""
return f"""
You are a technical analyst. Extract the key technical components from this innovation pitch.
## THE PITCH:
{pitch}
## YOUR TASK:
Create a structured list of:
1. **Core Technology Components**: What are the key technical pieces?
2. **Required Materials**: What materials or resources are needed?
3. **Scientific Principles**: What physics/chemistry/biology is involved?
4. **Manufacturing Requirements**: What would be needed to produce this?
5. **Dependencies**: What existing technologies must this build upon?
6. **Technical Risks**: What are the hardest technical challenges?
Format as a clear, bulleted technical specification.
YOUR ANALYSIS:
"""
def get_narrator_prompt(self, pitch: str, technical_components: str) -> str:
"""Prompt for the Narrator agent to create final presentation"""
return f"""
You are a TED talk presenter preparing to unveil a breakthrough innovation to the world.
## THE INNOVATION PITCH:
{pitch}
## TECHNICAL FOUNDATION:
{technical_components}
## YOUR TASK:
Create a compelling 2-minute presentation (250-350 words) that:
- Starts with a powerful hook or question
- Explains the innovation in terms anyone can understand
- Uses a concrete example or story to illustrate impact
- Builds emotional connection to the human benefit
- Ends with an inspiring call to action or vision
Write as if you're speaking directly to an audience. Use "you" and "we". Make it memorable.
YOUR PRESENTATION:
"""
def get_deep_thinker_prompt(self, technical_components: str) -> str:
"""Prompt for Deep Thinker to evaluate feasibility"""
return f"""
You are a senior research scientist and engineer with deep expertise across multiple domains.
Evaluate the feasibility of this proposed innovation.
## TECHNICAL SPECIFICATION:
{technical_components}
## YOUR EVALUATION CRITERIA:
Rate each area from 1-10 and provide brief justification:
1. **Scientific Validity** (1-10):
- Does the underlying science/physics make sense?
- What scientific principles are solid vs. speculative?
2. **Material Availability** (1-10):
- Are the required materials available or achievable?
- What's the rarest/hardest component to obtain?
3. **Engineering Feasibility** (1-10):
- Can this actually be built with current or near-term manufacturing?
- What are the biggest engineering challenges?
4. **Economic Viability** (1-10):
- What's the estimated cost to develop?
- Could this be profitable or sustainable?
5. **Timeline to Reality** (1-10):
- How many years until a working prototype? (10 = <5 years, 1 = >100 years)
6. **Overall Feasibility Score** (1-10):
- Your gut assessment of whether this can actually exist
## FORMAT YOUR RESPONSE AS:
Scientific Validity: [score] - [brief reasoning]
Material Availability: [score] - [brief reasoning]
Engineering Feasibility: [score] - [brief reasoning]
Economic Viability: [score] - [brief reasoning]
Timeline to Reality: [score] - [brief reasoning]
Overall Feasibility: [score] - [overall assessment]
YOUR FEASIBILITY REPORT:
"""
def get_curator_prompt(self, narrative: str, feasibility_report: str) -> str:
"""Prompt for Curator to provide final scoring (must return JSON)"""
return f"""
You are the final evaluator in an innovation assessment system. Review the complete proposal
and provide a structured scoring assessment.
## THE NARRATIVE:
{narrative}
## FEASIBILITY ANALYSIS:
{feasibility_report}
## YOUR TASK:
Provide a JSON-formatted scorecard with these exact fields:
{{
"originality": [1-10 score],
"originality_reasoning": "Brief explanation of originality score",
"feasibility": [1-10 score],
"feasibility_reasoning": "Brief explanation based on feasibility report",
"global_impact": [1-10 score],
"global_impact_reasoning": "How many people could this help and how significantly?",
"narrative_coherence": [1-10 score],
"narrative_coherence_reasoning": "How well-written and compelling is the pitch?",
"reforge_flag": [true/false],
"reforge_reasoning": "Should this idea advance to the next life stage? (true if feasibility >7 AND originality >5)",
"overall_assessment": "One paragraph summary of strengths and weaknesses",
"next_steps": "If reforge_flag is true, what should the next stage focus on?"
}}
RESPOND ONLY WITH VALID JSON. NO OTHER TEXT.
YOUR SCORECARD:
"""
def _format_dream_texts(self, dreams: List[str]) -> str:
"""Format multiple dream texts for presentation"""
formatted = []
for i, dream in enumerate(dreams, 1):
formatted.append(f"### VISION {i}:\n{dream}\n")
return "\n".join(formatted)
# Convenience function for loading prompts
def load_prompt_manager(config_path: str = "config.yaml") -> PromptManager:
"""Load and return a configured PromptManager instance"""
return PromptManager(config_path)