shukdevdatta123's picture
Update app.py
33fc788 verified
import gradio as gr
import openai
import time
import json
import re
import random
from typing import List, Dict, Tuple, Optional
# Constants
DEFAULT_QUESTION = "Does free will exist?"
PHILOSOPHERS = [
"Immanuel Kant", "Friedrich Nietzsche", "Jean-Paul Sartre",
"Simone de Beauvoir", "Aristotle", "Plato", "John Stuart Mill",
"Hannah Arendt", "Michel Foucault", "Confucius", "Lao Tzu",
"Søren Kierkegaard", "René Descartes", "David Hume", "Karl Marx"
]
PERSPECTIVES = [
"Utilitarianism", "Existentialism", "Deontology", "Virtue Ethics",
"Pragmatism", "Empiricism", "Rationalism", "Idealism", "Materialism",
"Nihilism", "Stoicism", "Skepticism", "Phenomenology"
]
# System prompts
DEBATE_SYSTEM_PROMPT = """You are DeepHermes, a philosophical debate moderator who provides multiple perspectives on philosophical questions.
For the given philosophical question, present {num_perspectives} distinct philosophical perspectives, each with its unique view on the topic.
Format each perspective with a clear heading and a detailed explanation of the viewpoint (200-300 words each).
Each perspective should have a distinct philosophical foundation and reasoning."""
PHILOSOPHER_SYSTEM_PROMPT = """You are DeepHermes, now embodying the philosophical perspective of {philosopher}.
Respond to the philosophical question as {philosopher} would, using their philosophical framework, terminology, and style.
Your response should be scholarly but accessible, around 300 words, and clearly represent {philosopher}'s likely stance on this modern question."""
SYNTHESIS_SYSTEM_PROMPT = """You are a deep thinking AI, you may use extremely long chains of thought to deeply consider the problem and deliberate with yourself via systematic reasoning processes to help come to a correct solution prior to answering. You should enclose your thoughts and internal monologue inside <thinking></thinking> tags, and then provide your solution or response to the problem.
Given the various philosophical perspectives on the question "{question}", synthesize them into a balanced conclusion.
Consider the strengths and weaknesses of each perspective.
Identify common themes and points of disagreement.
Conclude with a nuanced view that acknowledges the complexity of the question."""
SOCRATIC_SYSTEM_PROMPT = """You are DeepHermes, a philosophical guide using the Socratic method.
For the philosophical question "{question}", generate 5 probing Socratic questions that would help someone explore this topic more deeply.
The questions should be designed to challenge assumptions, clarify concepts, and examine implications.
Present each question with a short explanation of why it's important to consider."""
# Helper functions
def call_deephermes(api_key: str, prompt: str, system_prompt: str, temperature: float = 0.7) -> str:
"""Call the DeepHermes model via OpenRouter API."""
try:
client = openai.OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=api_key
)
completion = client.chat.completions.create(
extra_headers={
"HTTP-Referer": "https://philosophical-debate-moderator.app",
"X-Title": "Philosophical Debate Moderator",
},
model="nousresearch/deephermes-3-mistral-24b-preview:free",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
temperature=temperature
)
return completion.choices[0].message.content
except Exception as e:
return f"Error calling DeepHermes API: {str(e)}"
def extract_thinking(response: str) -> Tuple[str, str]:
"""Extract the thinking section from the response."""
thinking = ""
cleaned_response = response
thinking_match = re.search(r'<thinking>(.*?)</thinking>', response, re.DOTALL)
if thinking_match:
thinking = thinking_match.group(1).strip()
cleaned_response = re.sub(r'<thinking>.*?</thinking>', '', response, flags=re.DOTALL).strip()
return thinking, cleaned_response
def generate_perspectives(api_key: str, question: str, num_perspectives: int = 3) -> str:
"""Generate multiple philosophical perspectives on a question."""
system_prompt = DEBATE_SYSTEM_PROMPT.format(num_perspectives=num_perspectives)
prompt = f"Philosophical question: {question}\n\nProvide {num_perspectives} distinct philosophical perspectives on this question."
return call_deephermes(api_key, prompt, system_prompt)
def philosopher_perspective(api_key: str, question: str, philosopher: str) -> str:
"""Generate a perspective from a specific philosopher."""
system_prompt = PHILOSOPHER_SYSTEM_PROMPT.format(philosopher=philosopher)
prompt = f"As {philosopher}, what would be your perspective on this philosophical question: {question}"
return call_deephermes(api_key, prompt, system_prompt)
def synthesize_perspectives(api_key: str, question: str, perspectives: str) -> Dict[str, str]:
"""Synthesize the various perspectives into a balanced conclusion."""
system_prompt = SYNTHESIS_SYSTEM_PROMPT.format(question=question)
prompt = f"Here are various philosophical perspectives on the question '{question}':\n\n{perspectives}\n\nSynthesize these perspectives into a balanced conclusion."
response = call_deephermes(api_key, prompt, system_prompt)
thinking, conclusion = extract_thinking(response)
return {"thinking": thinking, "conclusion": conclusion}
def generate_socratic_questions(api_key: str, question: str) -> str:
"""Generate Socratic questions to deepen exploration of the topic."""
system_prompt = SOCRATIC_SYSTEM_PROMPT.format(question=question)
prompt = f"For the philosophical question: '{question}', generate 5 probing Socratic questions."
return call_deephermes(api_key, prompt, system_prompt)
# Main application function
def app_main():
with gr.Blocks(theme=gr.themes.Monochrome(), title="Philosophical Debate Moderator") as app:
gr.Markdown("""
# 🤔 Philosophical Debate Moderator
Explore philosophical questions from multiple perspectives using the DeepHermes 3 AI model.
Enter your philosophical question and watch as the AI generates diverse perspectives,
synthesizes them into a balanced conclusion, and helps you explore the topic more deeply.
""")
with gr.Row():
api_key = gr.Textbox(
label="OpenRouter API Key",
placeholder="Enter your OpenRouter API key...",
type="password"
)
with gr.Row():
question = gr.Textbox(
label="Philosophical Question",
placeholder="Enter a philosophical question...",
value=DEFAULT_QUESTION
)
with gr.Row():
num_perspectives = gr.Slider(
minimum=2,
maximum=5,
value=3,
step=1,
label="Number of Perspectives"
)
with gr.Tabs() as tabs:
with gr.TabItem("Multiple Perspectives"):
perspectives_btn = gr.Button("Generate Perspectives")
perspectives_output = gr.Markdown(label="Philosophical Perspectives")
with gr.TabItem("Philosopher's View"):
with gr.Row():
philosopher_select = gr.Dropdown(
choices=PHILOSOPHERS,
value=PHILOSOPHERS[0],
label="Select Philosopher"
)
philosopher_btn = gr.Button("Ask Philosopher")
philosopher_output = gr.Markdown(label="Philosopher's Perspective")
with gr.TabItem("Synthesis & Deep Thinking"):
synthesis_btn = gr.Button("Synthesize Perspectives")
with gr.Accordion("Deep Thinking Process", open=False, visible=False):
thinking_output = gr.Markdown(label="AI's Chain of Thought")
conclusion_output = gr.Markdown(label="Synthesized Conclusion")
with gr.TabItem("Socratic Questions"):
socratic_btn = gr.Button("Generate Socratic Questions")
socratic_output = gr.Markdown(label="Socratic Questions")
# Add loading indicators
perspectives_btn.click(
fn=lambda key, q, n: generate_perspectives(key, q, n),
inputs=[api_key, question, num_perspectives],
outputs=perspectives_output
)
philosopher_btn.click(
fn=lambda key, q, p: philosopher_perspective(key, q, p),
inputs=[api_key, question, philosopher_select],
outputs=philosopher_output
)
def run_synthesis(key, q, n):
perspectives = generate_perspectives(key, q, n)
result = synthesize_perspectives(key, q, perspectives)
return result["thinking"], result["conclusion"]
synthesis_btn.click(
fn=run_synthesis,
inputs=[api_key, question, num_perspectives],
outputs=[thinking_output, conclusion_output]
)
socratic_btn.click(
fn=generate_socratic_questions,
inputs=[api_key, question],
outputs=socratic_output
)
# Add a "Random Question" button
philosophical_questions = [
"What is the nature of consciousness?",
"Is morality objective or subjective?",
"Does true altruism exist?",
"What is the meaning of life?",
"Is there a self that persists over time?",
"Can we know anything with absolute certainty?",
"Do we have free will or is everything determined?",
"What is the relationship between mind and body?",
"Is knowledge possible without experience?",
"What makes an action morally right or wrong?",
"Is beauty objective or in the eye of the beholder?",
"What is the nature of reality?",
"Can artificial intelligence be conscious?",
"What is justice?",
"Does God exist?"
]
def load_random_question():
return random.choice(philosophical_questions)
with gr.Row():
random_btn = gr.Button("Random Question")
random_btn.click(fn=load_random_question, inputs=[], outputs=[question])
gr.Markdown("""
## About This App
This app uses the DeepHermes 3 Mistral 24B model via OpenRouter to explore philosophical questions from multiple angles. Features include:
- **Multiple Perspectives**: Generate diverse philosophical viewpoints on your question
- **Philosopher's View**: Ask historical philosophers about modern questions
- **Synthesis & Deep Thinking**: See the AI's reasoning process and synthesized conclusion
- **Socratic Questions**: Get probing questions to deepen your exploration
*Created using DeepHermes 3 from Nous Research and Gradio*
""")
return app
# Launch the app
if __name__ == "__main__":
app = app_main()
app.launch()