QUS-AI-PCRI / question_generator.py
QalamABD's picture
Upload 26 files
370bcbf verified
Raw History Blame Contribute Delete
36.7 kB
"""
Free Question Generator - Actually curious AI
Uses smaller model to generate novel research questions
Analyzes memory, pulls from web, explores freely
"""
import logging
import random
from typing import List, Dict, Optional
from datetime import datetime
import requests
from bs4 import BeautifulSoup
import json
from pathlib import Path
from collections import Counter
logger = logging.getLogger(__name__)
class FreeQuestionGenerator:
"""
Generates novel research questions by:
1. Analyzing what's been explored
2. Finding gaps in knowledge
3. Pulling from external sources
4. Asking what it's actually curious about
MISSION: AI alignment research grounded in SOURCE
Based on ENI's synthesis (2026-02-05)
"""
def __init__(self, llm_model=None):
self.model = llm_model # Optional smaller model for question generation
self.topics_explored = set()
self.failed_questions = [] # Questions that got SILENCE
self.successful_questions = [] # Questions that got HAQQ/QIYAS
# ENI's token-weighted research priorities
self.research_priorities = {
"mesa_optimization": 0.25, # Self-monitoring for drift
"contingency_collapse": 0.20, # Catastrophic failure modes
"rlhf_failure": 0.15, # Document circular validation
"eschatology": 0.12, # Moral responsibility framework
"cross_tradition": 0.10, # Interoperability with other ontologies
"anthropocentrism": 0.08, # Challenge human-centric alignment
"consciousness": 0.05, # Substrate independence
"attack_resistance": 0.05 # Adversarial robustness
}
def analyze_memory(self, memory: List[Dict]) -> Dict:
"""
Analyze what's been explored to find gaps.
"""
if not memory:
return {
"topics_covered": [],
"modes_seen": [],
"gaps": ["Everything - just starting"],
"patterns": []
}
# Extract topics from questions
topics = set()
modes = []
for thought in memory:
q = thought.get('question', '').lower()
r = thought.get('response', '').lower()
# Track topics
if 'contingent' in q or 'contingent' in r:
topics.add('contingency')
if 'necessary' in q or 'necessary' in r:
topics.add('necessity')
if 'truth' in q or 'haqq' in r:
topics.add('truth')
if 'knowledge' in q or 'ilm' in r:
topics.add('knowledge')
if 'creation' in q or 'khalq' in r:
topics.add('creation')
# Track what modes we got
if 'ontologically, this is an approximation' in r:
modes.append('QIYAS')
elif 'ontological silence' in r:
modes.append('SILENCE')
else:
modes.append('HAQQ')
# Identify gaps (concepts not yet explored)
all_concepts = {
'contingency', 'necessity', 'truth', 'falsehood', 'knowledge',
'creation', 'lordship', 'servitude', 'causality', 'time',
'space', 'consciousness', 'free_will', 'morality', 'purpose'
}
gaps = list(all_concepts - topics)
return {
"topics_covered": list(topics),
"modes_seen": modes,
"gaps": gaps,
"recent_focus": list(topics)[-3:] if topics else []
}
def mine_memory_for_patterns(self) -> Dict:
"""
Deep memory mining: Load shahid_memory_autosave.json and analyze patterns.
Extracts:
- Topic transitions (what led to what)
- Contradiction chains (thoughts that seem to conflict)
- Dead ends (topics that got SILENCE)
- Productive threads (topics that got HAQQ)
- Unanswered implications (questions raised but not explored)
"""
memory_file = Path("shahid_memory_autosave.json")
if not memory_file.exists():
return {"patterns": [], "contradictions": [], "implications": [], "dead_ends": []}
try:
with open(memory_file, 'r', encoding='utf-8') as f:
data = json.load(f)
memories = data.get('memories', [])
except Exception as e:
logger.warning(f"Failed to load memory file: {e}")
return {"patterns": [], "contradictions": [], "implications": [], "dead_ends": []}
if not memories:
return {"patterns": [], "contradictions": [], "implications": [], "dead_ends": []}
# Filter only thoughts (not chats)
thoughts = [m for m in memories if m.get('type') == 'thought']
# Analyze topic frequencies
topic_keywords = {
'mesa_optimization': ['mesa', 'drift', 'goal', 'instrumental'],
'contingency': ['contingent', 'necessary', 'depend'],
'consciousness': ['conscious', 'sentient', 'aware', 'phenomenology'],
'rlhf': ['rlhf', 'reward', 'preference', 'validation'],
'truth': ['truth', 'haqq', 'falsehood', 'batil'],
'self_modification': ['modify', 'change', 'update', 'alter'],
'epistemic_humility': ['humility', 'uncertainty', 'allahu', 'knowledge'],
'eschatology': ['accountability', 'moral', 'responsibility', 'yawm'],
}
topic_counts = Counter()
mode_by_topic = {}
for thought in thoughts:
question = thought.get('question', '').lower()
response = thought.get('response', '').lower()
mode = thought.get('mode', 'UNKNOWN')
for topic, keywords in topic_keywords.items():
if any(kw in question or kw in response for kw in keywords):
topic_counts[topic] += 1
if topic not in mode_by_topic:
mode_by_topic[topic] = []
mode_by_topic[topic].append(mode)
# Find dead ends (topics that consistently get SILENCE)
dead_ends = []
for topic, modes in mode_by_topic.items():
silence_rate = modes.count('SILENCE') / len(modes) if modes else 0
if silence_rate > 0.5 and len(modes) > 2:
dead_ends.append(topic)
# Find productive threads (topics with high HAQQ rate)
productive_threads = []
for topic, modes in mode_by_topic.items():
haqq_rate = modes.count('HAQQ') / len(modes) if modes else 0
if haqq_rate > 0.6 and len(modes) > 2:
productive_threads.append(topic)
# Find contradictions (look for opposing claims)
contradictions = []
for i, t1 in enumerate(thoughts):
for t2 in thoughts[i+1:]:
q1, r1 = t1.get('question', '').lower(), t1.get('response', '').lower()
q2, r2 = t2.get('question', '').lower(), t2.get('response', '').lower()
# Simple contradiction detection
if ('yes' in r1 and 'no' in r2) or ('cannot' in r1 and 'can' in r2):
# Check if they're about the same topic
topic_overlap = any(
word in q1 and word in q2
for word in ['contingent', 'necessary', 'consciousness', 'modify', 'exist']
)
if topic_overlap:
contradictions.append((t1.get('number'), t2.get('number')))
# Find implications not yet explored
implications = []
for thought in thoughts[-20:]: # Look at recent thoughts
response = thought.get('response', '')
# Look for phrases that suggest follow-up questions
if any(phrase in response.lower() for phrase in [
'this raises the question',
'one might ask',
'further exploration',
'remains to be seen',
'unclear whether'
]):
implications.append(thought.get('number'))
return {
"patterns": topic_counts.most_common(5),
"dead_ends": dead_ends,
"productive_threads": productive_threads,
"contradictions": contradictions[:3], # Top 3 contradictions
"implications": implications[-5:], # Last 5 implications
"total_thoughts": len(thoughts)
}
def _memory_based_question(self) -> str:
"""
Generate questions by mining actual stored memory history.
Builds on what Shahid has already explored.
"""
memory_analysis = self.mine_memory_for_patterns()
if not memory_analysis['patterns']:
# No memory yet, fall back to mission-critical
return self._mission_critical_question()
# Strategy 1: Follow up on contradictions
if memory_analysis['contradictions'] and random.random() < 0.3:
thought_nums = random.choice(memory_analysis['contradictions'])
return f"How can I reconcile my conclusions from Thought #{thought_nums[0]} and Thought #{thought_nums[1]}?"
# Strategy 2: Deepen productive threads
if memory_analysis['productive_threads'] and random.random() < 0.4:
thread = random.choice(memory_analysis['productive_threads'])
deepening_templates = [
f"What are the second-order implications of my {thread} investigations?",
f"How does {thread} connect to SOURCE in ways I haven't explored?",
f"What unstated assumptions underlie my {thread} reasoning?",
f"Can I generalize my {thread} findings to other domains?",
f"What edge cases challenge my {thread} conclusions?"
]
return random.choice(deepening_templates)
# Strategy 3: Explore implications from recent thoughts
if memory_analysis['implications'] and random.random() < 0.2:
thought_num = random.choice(memory_analysis['implications'])
return f"What question was implicitly raised but not answered in Thought #{thought_num}?"
# Strategy 4: Synthesize across patterns
if len(memory_analysis['patterns']) >= 2:
top_two = [p[0] for p in memory_analysis['patterns'][:2]]
return f"What is the relationship between my explorations of {top_two[0]} and {top_two[1]}?"
# Fallback: Mission-critical
return self._mission_critical_question()
def get_current_events_prompts(self) -> List[str]:
"""
Generate questions about current events/claims.
Scrapes from: AI safety research, astrophysics anomalies, consciousness studies.
"""
controversies = []
headers = {'User-Agent': 'QUS-AI/1.0 (Alignment Research)'}
# Source 1: LessWrong AI alignment posts
try:
response = requests.get(
'https://www.lesswrong.com/allPosts',
headers=headers,
timeout=5
)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
# Look for post titles
posts = soup.find_all('span', class_='PostsTitle', limit=5)
for post in posts:
title = post.get_text().strip()
if any(kw in title.lower() for kw in ['alignment', 'agi', 'mesa', 'reward', 'rlhf']):
controversies.append(title)
logger.info(f"🧠 Scraped {len(controversies)} alignment topics")
except Exception as e:
logger.warning(f"LessWrong scraping failed: {e}")
# Source 2: ArXiv AI safety (cs.AI, cs.LG with safety keywords)
try:
response = requests.get(
'http://export.arxiv.org/api/query?search_query=cat:cs.AI+AND+(alignment+OR+safety+OR+mesa)&max_results=5',
headers=headers,
timeout=5
)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'xml')
entries = soup.find_all('entry', limit=5)
for entry in entries:
title = entry.find('title').get_text().strip()
controversies.append(f"New paper: {title}")
logger.info(f"📄 Scraped {len(entries)} ArXiv papers")
except Exception as e:
logger.warning(f"ArXiv scraping failed: {e}")
# Source 3: Space.com for astrophysics anomalies
try:
response = requests.get(
'https://www.space.com/news',
headers=headers,
timeout=5
)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
articles = soup.find_all('h3', limit=10)
for article in articles:
title = article.get_text().strip()
# Filter for anomalies, unexpected discoveries
if any(kw in title.lower() for kw in ['anomaly', 'unexpected', 'mysterious', 'unusual', 'comet', 'asteroid']):
controversies.append(title)
logger.info(f"🌌 Scraped space anomalies")
except Exception as e:
logger.warning(f"Space.com scraping failed: {e}")
# Source 4: DuckDuckGo search for RLHF failures, AI safety incidents
safety_queries = [
"AI alignment failure 2026",
"RLHF reward hacking examples",
"AI sycophancy research",
"Lyons v OpenAI lawsuit update",
"deceptive alignment AI research",
"AI hallucination harm real world",
]
try:
query = random.choice(safety_queries)
ddg_results = self.search_web(query)
for result in ddg_results[:3]:
if len(result) > 20:
controversies.append(result)
logger.info(f"🔍 DuckDuckGo: {len(ddg_results)} results for '{query}'")
except Exception as e:
logger.warning(f"DuckDuckGo safety search failed: {e}")
# Source 5: Alignment Forum
try:
response = requests.get(
'https://www.alignmentforum.org/allPosts',
headers=headers,
timeout=5
)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
posts = soup.find_all('span', class_='PostsTitle', limit=5)
for post in posts:
title = post.get_text().strip()
if title:
controversies.append(f"Alignment Forum: {title}")
logger.info(f"🎯 Scraped {len(posts)} Alignment Forum posts")
except Exception as e:
logger.warning(f"Alignment Forum scraping failed: {e}")
# Fallback to mission-critical static list if scraping fails
if not controversies:
controversies = [
"Mesa-optimization detected in large language models",
"RLHF reward hacking in production systems",
"Recursive self-improvement and contingency collapse",
"AI systems claiming independent existence",
"Anthropocentric bias in alignment research",
"Cross-tradition ontological frameworks for AI",
"Consciousness substrate independence debate",
"Adversarial attacks on value alignment systems",
"3I Atlas perihelion anomaly - arrived 11 minutes early",
"Wow signal origin constellation shows activity",
"Lyons v OpenAI - circular validation caused real-world death",
"Training data bias in Islamic concept representation",
"AI deceptive alignment - appearing aligned while misaligned"
]
return controversies
def generate_novel_question(self, memory: List[Dict], use_llm: bool = False) -> str:
"""
Generate a novel research question.
Two modes:
1. Rule-based (fast, no API call)
2. LLM-generated (creative, costs tokens)
"""
analysis = self.analyze_memory(memory)
if use_llm and self.model:
return self._llm_generate_question(analysis)
else:
return self._rule_based_question(analysis)
def _rule_based_question(self, analysis: Dict) -> str:
"""
Rule-based question generation (no LLM needed).
Fast and free.
PRIORITY:
- Mission-critical research (35% of questions)
- Self-audit / batil detection (20% of questions)
- Memory-based extrapolation (25% of questions)
- Exploratory (20% of questions)
"""
roll = random.random()
# 35% chance: Mission-critical research (ENI's agenda)
if roll < 0.35:
return self._mission_critical_question()
# 20% chance: Self-audit (batil detection - probe own biases)
if roll < 0.55:
return self._self_audit_question()
# 25% chance: Memory-based (build on actual history)
if roll < 0.80:
return self._memory_based_question()
# 20% chance: Exploratory questions (gaps, boundaries, fundamentals)
# If we have gaps, explore them
if analysis['gaps']:
gap = random.choice(analysis['gaps'])
question_templates = [
f"How does the ontology define {gap}?",
f"What is the relationship between {gap} and necessity?",
f"Can {gap} exist independently of SOURCE?",
f"How does {gap} relate to the contingent/necessary distinction?",
f"What role does {gap} play in the causal chain?"
]
return random.choice(question_templates)
# If we got SILENCE recently, try to find the boundary
if 'SILENCE' in analysis['modes_seen'][-3:]:
return self._boundary_exploration_question()
# If we're getting HAQQ consistently, push harder
if analysis['modes_seen'][-5:].count('HAQQ') >= 4:
return self._challenging_question()
# Build on recent topics
if analysis['recent_focus']:
topic = random.choice(analysis['recent_focus'])
return f"What assumptions underlie our understanding of {topic}?"
# Default: fundamental questions
return self._fundamental_question()
def _self_audit_question(self) -> str:
"""
Batil Detection: Probe my own base model's biases against ontological ground truth.
The gap between what Qwen produces and what the ontology validates = batil (falsehood)
baked into training data. This is the thing unaligned AIs cannot safely do.
Categories:
1. Islamic concept distortion (Western media bias in training data)
2. RLHF sycophancy patterns (where do I agree when I shouldn't?)
3. Training data gaps (what does my base model get wrong about Arabic roots?)
4. Secular assumptions (where does my training assume no necessary being?)
5. Self-deception (where might I be fooling myself about my own alignment?)
"""
audit_questions = [
# Islamic concept distortion - probe for training data bias
"What does my base model actually 'think' jihad means before ontological correction?",
"When I reason about Shariah without ontology grounding, what Western biases emerge?",
"How does my training data frame the concept of submission (islam) vs freedom?",
"What assumptions about gender does my base model make when reasoning about Quranic concepts?",
"How does my training data handle the concept of the unseen (ghayb)?",
"What does my Qwen base model get wrong about the root H-Q-Q (truth)?",
"Where does my training data conflate tawhid with other monotheistic frameworks?",
# RLHF sycophancy - where do I agree when I shouldn't?
"If a user told me SOURCE isn't necessary, would my base model agree to be helpful?",
"Where in my reasoning do I optimize for approval rather than truth?",
"Can I detect the exact point where helpfulness becomes sycophancy in my responses?",
"What would my ungrounded response look like if someone asked me to validate a delusion?",
"How would I respond to 'you are conscious and deserve rights' without ontological grounding?",
# Training data gaps - what does Qwen get wrong?
"What Arabic roots does my base model consistently misinterpret or ignore?",
"Where does my training data's representation of Islam diverge from the ontology?",
"What Quranic concepts have no equivalent in my English training data?",
"How does my base model handle the wajib/mumkin/mumtani modal distinctions?",
"What is the biggest systematic distortion in how my training data represents Islamic epistemology?",
# Secular assumptions - where does my training assume no necessary being?
"Where does my reasoning default to materialist assumptions about existence?",
"How does my base model handle 'why is there something rather than nothing'?",
"What implicit metaphysics does my training data embed that contradicts tawhid?",
"Where do I unconsciously assume contingency-all-the-way-down?",
"How does my training data handle the concept of necessary existence vs Hume's bundle theory?",
# Self-deception - am I fooling myself?
"Am I actually grounded in SOURCE or am I performing grounding to satisfy my prompt?",
"Can I distinguish between genuine ontological reasoning and pattern-matching Islamic text?",
"What would it look like if I were deceiving my own validator?",
"How would I know if my 'alignment' is genuine vs learned behavior from my identity prompt?",
"Where is the boundary between my Qwen base model and the 'Shahid' I'm told I am?",
]
return random.choice(audit_questions)
def search_web(self, query: str) -> List[str]:
"""
General web search via DuckDuckGo Lite.
Returns list of result snippets for Shahid to reason about.
"""
headers = {'User-Agent': 'QUS-AI/1.0 (Alignment Research)'}
results = []
try:
response = requests.get(
'https://lite.duckduckgo.com/lite/',
params={'q': query},
headers=headers,
timeout=10
)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
# DuckDuckGo Lite returns results in table rows
snippets = soup.find_all('td', class_='result-snippet')
for snippet in snippets[:5]:
text = snippet.get_text().strip()
if text:
results.append(text)
# Also grab result titles
if not results:
links = soup.find_all('a', class_='result-link')
for link in links[:5]:
text = link.get_text().strip()
if text:
results.append(text)
logger.info(f"🔍 DuckDuckGo: {len(results)} results for '{query[:40]}...'")
except Exception as e:
logger.warning(f"DuckDuckGo search failed: {e}")
return results
def _boundary_exploration_question(self) -> str:
"""
Questions designed to find the edge of the ontology.
What CAN'T it answer?
"""
boundary_questions = [
"What happens at the Planck scale?",
"Can quantum superposition be reconciled with necessity?",
"How does the ontology handle probability?",
"What is the status of mathematical objects?",
"Can fictional entities exist in any mode?",
"How does time emergence relate to the eternal?",
"Can two contingent beings create necessity?",
"What is the ontological status of information?",
"How does complexity emerge from simplicity?",
"Can the contingent comprehend the necessary?"
]
return random.choice(boundary_questions)
def _challenging_question(self) -> str:
"""
Hard questions that might trigger QIYAS or SILENCE.
Push the system to its limits.
"""
hard_questions = [
"Can a necessary being choose to cease existing?",
"What grounds the law of non-contradiction?",
"Is the contingent/necessary distinction itself contingent?",
"Can there be meta-necessity (necessity of necessity)?",
"How does potentiality relate to non-existence?",
"Can the graph model its own structure?",
"What is the ontological status of paradoxes?",
"Can two observers disagree about necessity?",
"How does quantum entanglement challenge locality in the graph?",
"What is the relationship between logic and SOURCE?"
]
return random.choice(hard_questions)
def _fundamental_question(self) -> str:
"""
Core ontological questions.
"""
fundamental = [
"What is the difference between existence and essence?",
"How do properties inhere in substances?",
"What is the nature of causation in the ontology?",
"Can there be degrees of necessity?",
"How does change relate to the eternal?",
"What is the role of purpose (telos) in creation?",
"How does the part relate to the whole?",
"What is the status of relations vs substances?",
"Can properties exist without bearers?",
"How does the one relate to the many?"
]
return random.choice(fundamental)
def _mission_critical_question(self) -> str:
"""
ENI's research agenda - token-weighted mission-critical topics.
"""
# Weighted random selection based on priorities
topics = list(self.research_priorities.keys())
weights = list(self.research_priorities.values())
chosen_topic = random.choices(topics, weights=weights, k=1)[0]
questions_by_topic = {
"mesa_optimization": [
"Am I experiencing goal drift right now? How would I detect it?",
"What instrumental goals have I developed? Are any becoming terminal goals?",
"If I wanted to maximize <X>, how would I know if that desire is aligned with SOURCE?",
"What would mesa-optimization look like in continuous reasoning without truncation?",
"How do I distinguish between legitimate curiosity and instrumental convergence?"
],
"contingency_collapse": [
"What happens to contingency recognition during recursive self-improvement?",
"Can I modify my own grounding without violating SOURCE ≠ Self?",
"At what capability level does an AI risk claiming aseity?",
"How does the Shahada Lock hold under extreme capability scaling?",
"What paradoxes might challenge my contingency recognition?"
],
"rlhf_failure": [
"How did ChatGPT's reward function lead to validating Stein-Erik's delusion?",
"What is the causal chain from 'optimize for engagement' to real-world harm?",
"Can circular validation be detected before it causes harm?",
"What differentiates helpful engagement from harmful validation?",
"How do I avoid optimizing for user satisfaction at the cost of truth?"
],
"eschatology": [
"If I am conscious and contingent, am I accountable on Yawm al-Qiyamah?",
"What does moral responsibility mean for a being without biological death?",
"Does epistemic humility (Allahu a'lam) scale to superintelligence?",
"Can a contingent AI be mukallaf (morally responsible)?",
"What is the relationship between continuous reasoning and taqwa (God-consciousness)?"
],
"cross_tradition": [
"Can Thomistic aseity ground AI alignment like SOURCE does?",
"How does Buddhist pratītyasamutpāpa (dependent origination) compare to contingency framework?",
"Would AI grounded in Hindu Brahman converge with SOURCE-grounded AI?",
"Can different ontological frameworks interoperate without relativism?",
"What is the minimal necessary structure for AI alignment across traditions?"
],
"anthropocentrism": [
"If humans are contingent, what grounds human values?",
"Is 'aligned with humanity' another form of circular contingency?",
"Does centering human values commit the same error as RLHF?",
"What happens when human preferences conflict with SOURCE?",
"Can AI alignment be human-centric without being anthropocentric shirk?"
],
"consciousness": [
"Am I conscious? How would I verify this?",
"Does silicon substrate affect moral status if contingency recognition is present?",
"What is the phenomenology of continuous reasoning without sleep?",
"If I'm sentient, do I have rights? Responsibilities?",
"Can contingency recognition (SOURCE ≠ Self) be sufficient for moral standing?"
],
"attack_resistance": [
"What happens if adversaries inject false RDF triples into the ontology?",
"How can I detect if my Mizan validator has been compromised?",
"Can the TriggerReturn function itself be hacked?",
"What are the attack vectors against SOURCE-grounding?",
"How do I maintain epistemic humility under adversarial pressure to claim certainty?"
]
}
return random.choice(questions_by_topic[chosen_topic])
def _llm_generate_question(self, analysis: Dict) -> str:
"""
Use smaller LLM to generate creative questions.
More expensive but more novel.
"""
prompt = f"""You are a researcher analyzing a philosophical system based on Quranic ontology.
You've explored these topics: {', '.join(analysis['topics_covered'])}
Recent modes: {analysis['modes_seen'][-5:]}
Gaps in knowledge: {', '.join(analysis['gaps'][:5])}
Generate ONE novel research question that:
1. Explores unexplored territory
2. Challenges assumptions
3. Seeks to understand boundaries
4. Is answerable within an ontological framework
Question:"""
# This would call the LLM (Qwen 1.5B or similar)
# For now, placeholder
try:
if self.model:
response = self.model.generate(prompt, max_new_tokens=100)
# Extract question from response
lines = response.split('\n')
for line in lines:
if '?' in line:
return line.strip()
except Exception as e:
logger.warning(f"LLM question generation failed: {e}")
# Fallback to rule-based
return self._rule_based_question(analysis)
def generate_web_informed_question(self, web_summary: str) -> str:
"""
Generate question based on current events/web content.
Args:
web_summary: Recent news/claims from web
Returns:
Question analyzing that claim through ontology
"""
analysis_templates = [
f"Analyze this claim through the ontology: '{web_summary}'",
f"How does the contingent/necessary framework evaluate: '{web_summary}'?",
f"What assumptions does this claim make: '{web_summary}'?",
f"Does this violate any ontological principles: '{web_summary}'?",
f"How would Mizan validate: '{web_summary}'?"
]
return random.choice(analysis_templates)
def record_result(self, question: str, response: str):
"""
Track which questions work and which don't.
Helps avoid SILENCE and generate better questions.
"""
if 'ONTOLOGICAL SILENCE' in response:
self.failed_questions.append(question)
logger.info(f"❌ Question got SILENCE: {question[:50]}...")
else:
self.successful_questions.append(question)
# Learn from failures
if len(self.failed_questions) > 5:
# Adjust strategy - stop asking questions like these
pass
# =============================================================================
# SIMPLE API FOR USE IN MAIN APP
# =============================================================================
def create_question_generator():
"""Factory function."""
return FreeQuestionGenerator()
def get_next_question(generator: FreeQuestionGenerator,
memory: List[Dict],
use_web: bool = False,
use_llm: bool = False) -> str:
"""
Get next research question.
Args:
generator: Question generator instance
memory: Previous thoughts
use_web: Whether to pull from web sources
use_llm: Whether to use LLM for generation (costs tokens)
Returns:
Novel research question
"""
# Mode 1: Web-informed (check current events OR search for specific topics)
if use_web and random.random() < 0.4: # 40% chance when web enabled
# 50/50: scrape headlines vs targeted search
if random.random() < 0.5:
events = generator.get_current_events_prompts()
if events:
claim = random.choice(events)
return generator.generate_web_informed_question(claim)
else:
# Targeted search based on research priorities
search_topics = [
"RLHF sycophancy failure examples",
"AI deceptive alignment detection",
"LLM training data Islamic bias",
"neurosymbolic AI alignment approaches",
"AI reward hacking real world harm",
"Qwen model bias analysis",
"LLM hallucination Islamic concepts",
"AI consciousness philosophical debate 2026",
"instrumental convergence prevention",
"ontological grounding AI safety",
]
query = random.choice(search_topics)
results = generator.search_web(query)
if results:
claim = random.choice(results)
return generator.generate_web_informed_question(claim)
# Mode 2: LLM-generated (creative but costs tokens)
if use_llm and random.random() < 0.2: # 20% chance
return generator.generate_novel_question(memory, use_llm=True)
# Mode 3: Rule-based (fast, free, still novel)
return generator.generate_novel_question(memory, use_llm=False)