shukdevdatta123 commited on
Commit
4a72051
·
verified ·
1 Parent(s): c438810

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +242 -0
app.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import time
4
+ import json
5
+ import re
6
+ import random
7
+ from typing import List, Dict, Tuple, Optional
8
+
9
+ # Constants
10
+ DEFAULT_QUESTION = "Does free will exist?"
11
+ PHILOSOPHERS = [
12
+ "Immanuel Kant", "Friedrich Nietzsche", "Jean-Paul Sartre",
13
+ "Simone de Beauvoir", "Aristotle", "Plato", "John Stuart Mill",
14
+ "Hannah Arendt", "Michel Foucault", "Confucius", "Lao Tzu",
15
+ "Søren Kierkegaard", "René Descartes", "David Hume", "Karl Marx"
16
+ ]
17
+ PERSPECTIVES = [
18
+ "Utilitarianism", "Existentialism", "Deontology", "Virtue Ethics",
19
+ "Pragmatism", "Empiricism", "Rationalism", "Idealism", "Materialism",
20
+ "Nihilism", "Stoicism", "Skepticism", "Phenomenology"
21
+ ]
22
+
23
+ # System prompts
24
+ DEBATE_SYSTEM_PROMPT = """You are DeepHermes, a philosophical debate moderator who provides multiple perspectives on philosophical questions.
25
+ For the given philosophical question, present {num_perspectives} distinct philosophical perspectives, each with its unique view on the topic.
26
+ Format each perspective with a clear heading and a detailed explanation of the viewpoint (200-300 words each).
27
+ Each perspective should have a distinct philosophical foundation and reasoning."""
28
+
29
+ PHILOSOPHER_SYSTEM_PROMPT = """You are DeepHermes, now embodying the philosophical perspective of {philosopher}.
30
+ Respond to the philosophical question as {philosopher} would, using their philosophical framework, terminology, and style.
31
+ Your response should be scholarly but accessible, around 300 words, and clearly represent {philosopher}'s likely stance on this modern question."""
32
+
33
+ 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.
34
+
35
+ Given the various philosophical perspectives on the question "{question}", synthesize them into a balanced conclusion.
36
+ Consider the strengths and weaknesses of each perspective.
37
+ Identify common themes and points of disagreement.
38
+ Conclude with a nuanced view that acknowledges the complexity of the question."""
39
+
40
+ SOCRATIC_SYSTEM_PROMPT = """You are DeepHermes, a philosophical guide using the Socratic method.
41
+ For the philosophical question "{question}", generate 5 probing Socratic questions that would help someone explore this topic more deeply.
42
+ The questions should be designed to challenge assumptions, clarify concepts, and examine implications.
43
+ Present each question with a short explanation of why it's important to consider."""
44
+
45
+ # Helper functions
46
+ def call_deephermes(api_key: str, prompt: str, system_prompt: str, temperature: float = 0.7) -> str:
47
+ """Call the DeepHermes model via OpenRouter API."""
48
+ try:
49
+ client = openai.OpenAI(
50
+ base_url="https://openrouter.ai/api/v1",
51
+ api_key=api_key
52
+ )
53
+
54
+ completion = client.chat.completions.create(
55
+ extra_headers={
56
+ "HTTP-Referer": "https://philosophical-debate-moderator.app",
57
+ "X-Title": "Philosophical Debate Moderator",
58
+ },
59
+ model="nousresearch/deephermes-3-mistral-24b-preview:free",
60
+ messages=[
61
+ {"role": "system", "content": system_prompt},
62
+ {"role": "user", "content": prompt}
63
+ ],
64
+ temperature=temperature
65
+ )
66
+ return completion.choices[0].message.content
67
+ except Exception as e:
68
+ return f"Error calling DeepHermes API: {str(e)}"
69
+
70
+ def extract_thinking(response: str) -> Tuple[str, str]:
71
+ """Extract the thinking section from the response."""
72
+ thinking = ""
73
+ cleaned_response = response
74
+
75
+ thinking_match = re.search(r'<thinking>(.*?)</thinking>', response, re.DOTALL)
76
+ if thinking_match:
77
+ thinking = thinking_match.group(1).strip()
78
+ cleaned_response = re.sub(r'<thinking>.*?</thinking>', '', response, flags=re.DOTALL).strip()
79
+
80
+ return thinking, cleaned_response
81
+
82
+ def generate_perspectives(api_key: str, question: str, num_perspectives: int = 3) -> str:
83
+ """Generate multiple philosophical perspectives on a question."""
84
+ system_prompt = DEBATE_SYSTEM_PROMPT.format(num_perspectives=num_perspectives)
85
+ prompt = f"Philosophical question: {question}\n\nProvide {num_perspectives} distinct philosophical perspectives on this question."
86
+ return call_deephermes(api_key, prompt, system_prompt)
87
+
88
+ def philosopher_perspective(api_key: str, question: str, philosopher: str) -> str:
89
+ """Generate a perspective from a specific philosopher."""
90
+ system_prompt = PHILOSOPHER_SYSTEM_PROMPT.format(philosopher=philosopher)
91
+ prompt = f"As {philosopher}, what would be your perspective on this philosophical question: {question}"
92
+ return call_deephermes(api_key, prompt, system_prompt)
93
+
94
+ def synthesize_perspectives(api_key: str, question: str, perspectives: str) -> Dict[str, str]:
95
+ """Synthesize the various perspectives into a balanced conclusion."""
96
+ system_prompt = SYNTHESIS_SYSTEM_PROMPT.format(question=question)
97
+ prompt = f"Here are various philosophical perspectives on the question '{question}':\n\n{perspectives}\n\nSynthesize these perspectives into a balanced conclusion."
98
+ response = call_deephermes(api_key, prompt, system_prompt)
99
+ thinking, conclusion = extract_thinking(response)
100
+ return {"thinking": thinking, "conclusion": conclusion}
101
+
102
+ def generate_socratic_questions(api_key: str, question: str) -> str:
103
+ """Generate Socratic questions to deepen exploration of the topic."""
104
+ system_prompt = SOCRATIC_SYSTEM_PROMPT.format(question=question)
105
+ prompt = f"For the philosophical question: '{question}', generate 5 probing Socratic questions."
106
+ return call_deephermes(api_key, prompt, system_prompt)
107
+
108
+ # Main application function
109
+ def app_main():
110
+ with gr.Blocks(theme=gr.themes.Monochrome(), title="Philosophical Debate Moderator") as app:
111
+ gr.Markdown("""
112
+ # 🤔 Philosophical Debate Moderator
113
+
114
+ Explore philosophical questions from multiple perspectives using the DeepHermes 3 AI model.
115
+
116
+ Enter your philosophical question and watch as the AI generates diverse perspectives,
117
+ synthesizes them into a balanced conclusion, and helps you explore the topic more deeply.
118
+ """)
119
+
120
+ with gr.Row():
121
+ api_key = gr.Textbox(
122
+ label="OpenRouter API Key",
123
+ placeholder="Enter your OpenRouter API key...",
124
+ type="password"
125
+ )
126
+
127
+ with gr.Row():
128
+ question = gr.Textbox(
129
+ label="Philosophical Question",
130
+ placeholder="Enter a philosophical question...",
131
+ value=DEFAULT_QUESTION
132
+ )
133
+
134
+ with gr.Row():
135
+ num_perspectives = gr.Slider(
136
+ minimum=2,
137
+ maximum=5,
138
+ value=3,
139
+ step=1,
140
+ label="Number of Perspectives"
141
+ )
142
+
143
+ with gr.Tabs() as tabs:
144
+ with gr.TabItem("Multiple Perspectives"):
145
+ perspectives_btn = gr.Button("Generate Perspectives")
146
+ perspectives_output = gr.Markdown(label="Philosophical Perspectives")
147
+
148
+ with gr.TabItem("Philosopher's View"):
149
+ with gr.Row():
150
+ philosopher_select = gr.Dropdown(
151
+ choices=PHILOSOPHERS,
152
+ value=PHILOSOPHERS[0],
153
+ label="Select Philosopher"
154
+ )
155
+ philosopher_btn = gr.Button("Ask Philosopher")
156
+ philosopher_output = gr.Markdown(label="Philosopher's Perspective")
157
+
158
+ with gr.TabItem("Synthesis & Deep Thinking"):
159
+ synthesis_btn = gr.Button("Synthesize Perspectives")
160
+ with gr.Accordion("Deep Thinking Process", open=False):
161
+ thinking_output = gr.Markdown(label="AI's Chain of Thought")
162
+ conclusion_output = gr.Markdown(label="Synthesized Conclusion")
163
+
164
+ with gr.TabItem("Socratic Questions"):
165
+ socratic_btn = gr.Button("Generate Socratic Questions")
166
+ socratic_output = gr.Markdown(label="Socratic Questions")
167
+
168
+ # Add loading indicators
169
+ perspectives_btn.click(
170
+ fn=lambda key, q, n: generate_perspectives(key, q, n),
171
+ inputs=[api_key, question, num_perspectives],
172
+ outputs=perspectives_output
173
+ )
174
+
175
+ philosopher_btn.click(
176
+ fn=lambda key, q, p: philosopher_perspective(key, q, p),
177
+ inputs=[api_key, question, philosopher_select],
178
+ outputs=philosopher_output
179
+ )
180
+
181
+ def run_synthesis(key, q, n):
182
+ perspectives = generate_perspectives(key, q, n)
183
+ result = synthesize_perspectives(key, q, perspectives)
184
+ return result["thinking"], result["conclusion"]
185
+
186
+ synthesis_btn.click(
187
+ fn=run_synthesis,
188
+ inputs=[api_key, question, num_perspectives],
189
+ outputs=[thinking_output, conclusion_output]
190
+ )
191
+
192
+ socratic_btn.click(
193
+ fn=generate_socratic_questions,
194
+ inputs=[api_key, question],
195
+ outputs=socratic_output
196
+ )
197
+
198
+ # Add a "Random Question" button
199
+ philosophical_questions = [
200
+ "What is the nature of consciousness?",
201
+ "Is morality objective or subjective?",
202
+ "Does true altruism exist?",
203
+ "What is the meaning of life?",
204
+ "Is there a self that persists over time?",
205
+ "Can we know anything with absolute certainty?",
206
+ "Do we have free will or is everything determined?",
207
+ "What is the relationship between mind and body?",
208
+ "Is knowledge possible without experience?",
209
+ "What makes an action morally right or wrong?",
210
+ "Is beauty objective or in the eye of the beholder?",
211
+ "What is the nature of reality?",
212
+ "Can artificial intelligence be conscious?",
213
+ "What is justice?",
214
+ "Does God exist?"
215
+ ]
216
+
217
+ def load_random_question():
218
+ return random.choice(philosophical_questions)
219
+
220
+ with gr.Row():
221
+ random_btn = gr.Button("Random Question")
222
+ random_btn.click(fn=load_random_question, inputs=[], outputs=[question])
223
+
224
+ gr.Markdown("""
225
+ ## About This App
226
+
227
+ This app uses the DeepHermes 3 Mistral 24B model via OpenRouter to explore philosophical questions from multiple angles. Features include:
228
+
229
+ - **Multiple Perspectives**: Generate diverse philosophical viewpoints on your question
230
+ - **Philosopher's View**: Ask historical philosophers about modern questions
231
+ - **Synthesis & Deep Thinking**: See the AI's reasoning process and synthesized conclusion
232
+ - **Socratic Questions**: Get probing questions to deepen your exploration
233
+
234
+ *Created using DeepHermes 3 from Nous Research and Gradio*
235
+ """)
236
+
237
+ return app
238
+
239
+ # Launch the app
240
+ if __name__ == "__main__":
241
+ app = app_main()
242
+ app.launch()