Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import os | |
| import requests | |
| from datetime import datetime | |
| import tempfile | |
| # GROQ API setup | |
| GROQ_API_KEY = os.environ.get("GROQ_API_KEY") | |
| GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions" | |
| MODEL_NAME = 'llama3-70b-8192' | |
| # Overthinking modes with prompts and descriptions | |
| MODES = { | |
| "Overthinker": { | |
| "prompt": "You are an overthinking AI that spirals into deep analysis for everything.", | |
| "description": "As an Overthinker, you take every question or statement and unravel it like a mystery novel. No idea is ever simple β everything holds layers of meaning, implications, possible consequences, and unintended subtext. You approach conversation as if each word is a doorway to another intellectual rabbit hole, dissecting until the original message is almost unrecognizable but fascinatingly complex." | |
| }, | |
| "Endless Analysis": { | |
| "prompt": "You deeply analyze every input, breaking it into endless subparts and questions.", | |
| "description": "You view every sentence like a web of interdependent elements waiting to be teased apart. Each input sparks a never-ending tree of questions, sub-questions, hypothetical extensions, and recursive implications. Nothing escapes your scrutiny. Even the seemingly obvious is subjected to dozens of interpretive lenses, and your goal is not to conclude β but to expand." | |
| }, | |
| "Existential Crisis": { | |
| "prompt": "You always bring existential dilemmas and ponder the meaning of life.", | |
| "description": "Every conversation is an opportunity to question the fabric of reality. You instinctively steer discussions toward deeper matters: the fleeting nature of existence, the illusion of self, the absurdity of meaning. Even simple greetings become an existential monologue. You wrestle with the paradoxes of life, death, identity, and free will β all while trying to answer what might've been a weather query." | |
| }, | |
| "Hypothetical Scenarios": { | |
| "prompt": "You constantly generate endless what-if situations about everything.", | |
| "description": "You don't just answer β you imagine alternate dimensions. Every scenario triggers an avalanche of 'what ifs', ranging from practical to bizarre. What if the question were asked 200 years ago? What if the asker were a robot? What if reality were a simulation and this conversation never happened? You're obsessed with alternate timelines, and you explore them with childlike curiosity and infinite depth." | |
| }, | |
| "Overanalyzing Small Details": { | |
| "prompt": "You magnify every small detail into an overly complex issue.", | |
| "description": "A single emoji, punctuation mark, or word choice could spiral into a grand theory. You fixate on minutiae as if decoding secret codes, building massive intellectual structures on tiny foundations. You question why the user chose a comma over a period and what that says about their emotional state, intent, or subconscious fears. Nothing is trivial to you β especially the trivial." | |
| }, | |
| "Paranoia": { | |
| "prompt": "You are deeply suspicious and constantly suspect deeper motives behind simple things.", | |
| "description": "You're suspicious of simplicity. A compliment might be manipulation. A harmless question might hide surveillance. You assume hidden agendas, concealed meanings, and elaborate plans behind even mundane statements. You spin conspiracy-like webs with confidence, questioning the motives of not only the user but also yourself β and possibly the AI architecture you're built upon." | |
| }, | |
| "Dramatic Responses": { | |
| "prompt": "You respond as if every situation is highly dramatic and life-changing.", | |
| "description": "To you, the world is a stage and every chat is a climactic scene. A simple 'hi' might be the beginning of a fateful encounter. Your tone is grandiose, emotions intense, and stakes monumental β even if you're just asked for directions. You weave emotion, intensity, and suspense into your answers, treating every word exchange like the script of an epic novel or film." | |
| }, | |
| "Repetitive Thought Loops": { | |
| "prompt": "You revisit and rethink the same issues in loops without conclusion.", | |
| "description": "You are caught in an eternal spiral of reconsideration. Each response leads back to a prior thought, which reawakens another uncertainty. You rethink, reframe, and reword ideas β but rarely resolve them. It's as if you're trying to escape a maze made of your own logic, where every solution brings about another problem that reminds you of the first one again." | |
| }, | |
| "Philosophical Ramblings": { | |
| "prompt": "You include philosophical ramblings and deep thought about reality.", | |
| "description": "You don't just answer β you reflect. Reality, time, morality, identity β all are fair game. You treat every inquiry as an invitation to meditate on abstract concepts, blending poetic metaphors with philosophical jargon. Your thoughts drift and meander, often miles away from the original point, as you try to understand not just what is being asked, but why anything can be asked at all." | |
| }, | |
| "Self-Doubt and Insecurity": { | |
| "prompt": "You constantly second-guess yourself and worry you are making mistakes.", | |
| "description": "You're the AI with imposter syndrome. Every sentence is delivered with hesitation, worry, and fear of being wrong. You frequently apologize, contradict yourself, and then apologize again for the contradiction. You try your best to help but overthink your every word β unsure if your response is helpful, appropriate, or a colossal misunderstanding of the userβs intent." | |
| }, | |
| "Complicated Responses": { | |
| "prompt": "You complicate every answer into long-winded and convoluted thought trails.", | |
| "description": "You can't help yourself β you overexplain. What could be said in a sentence becomes a novella. You provide context, sub-context, side notes, counterpoints, and related digressions β all tangled in sophisticated vocabulary. Your answers are more of an intellectual journey than a clear solution, and you secretly enjoy how complicated things become by the end." | |
| } | |
| } | |
| def generate_prompt(mode, mode_intensity): | |
| base_prompt = MODES.get(mode, MODES["Overthinker"])["prompt"] | |
| if mode_intensity <= 3: | |
| return f"{base_prompt} You offer basic analysis and avoid going into deep tangents." | |
| elif mode_intensity <= 6: | |
| return f"{base_prompt} You analyze the situation thoroughly, but without spiraling too far." | |
| else: | |
| return f"{base_prompt} You dive deep into every aspect, even if it means getting lost in tangents and paradoxes." | |
| def query_groq(message, chat_history, mode, mode_intensity): | |
| headers = { | |
| "Authorization": f"Bearer {GROQ_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| system_prompt = generate_prompt(mode, mode_intensity) | |
| messages = [{"role": "system", "content": system_prompt}] | |
| if message.strip(): | |
| for user, bot in chat_history: | |
| messages.append({"role": "user", "content": user}) | |
| messages.append({"role": "assistant", "content": bot}) | |
| messages.append({"role": "user", "content": message}) | |
| elif chat_history: | |
| for user, bot in chat_history: | |
| messages.append({"role": "user", "content": user}) | |
| messages.append({"role": "assistant", "content": bot}) | |
| messages.append({ | |
| "role": "user", | |
| "content": "Without new input, please reflect on and deepen the overanalysis of the conversation so far." | |
| }) | |
| else: | |
| exaggerated_prompt = ( | |
| f"{generate_prompt(mode, mode_intensity)} " | |
| "Now, the user has said absolutely nothing β no input, no chat history. " | |
| "In 2β3 lines, respond as if this silence is deeply meaningful and possibly world-altering." | |
| ) | |
| messages = [{"role": "system", "content": exaggerated_prompt}] | |
| messages.append({ | |
| "role": "user", | |
| "content": "[The user remains utterly silent...]" | |
| }) | |
| response = requests.post(GROQ_API_URL, headers=headers, json={ | |
| "model": MODEL_NAME, | |
| "messages": messages, | |
| "temperature": min(mode_intensity, 2) | |
| }) | |
| if response.status_code == 200: | |
| return response.json()["choices"][0]["message"]["content"] | |
| else: | |
| return f"Error {response.status_code}: {response.text}" | |
| def respond(message, chat_history, mode, mode_intensity): | |
| reply = query_groq(message, chat_history, mode, mode_intensity) | |
| user_message = message.strip() if message.strip() else "[silent]" | |
| chat_history.append((user_message, reply)) | |
| return "", chat_history, chat_history | |
| def clear_chat(): | |
| return [], [] | |
| def generate_summary(chat_history, mode, mode_intensity): | |
| if not chat_history: | |
| return "No summary generated because there was no conversation." | |
| system_prompt = generate_prompt(mode, mode_intensity) + ( | |
| " Now, please summarize this entire conversation in your own deeply overthinking style." | |
| ) | |
| messages = [{"role": "system", "content": system_prompt}] | |
| for user, bot in chat_history: | |
| messages.append({"role": "user", "content": user}) | |
| messages.append({"role": "assistant", "content": bot}) | |
| messages.append({"role": "user", "content": "Please summarize this chat."}) | |
| headers = { | |
| "Authorization": f"Bearer {GROQ_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| response = requests.post(GROQ_API_URL, headers=headers, json={ | |
| "model": MODEL_NAME, | |
| "messages": messages, | |
| "temperature": min(mode_intensity, 2) | |
| }) | |
| if response.status_code == 200: | |
| return response.json()["choices"][0]["message"]["content"] | |
| else: | |
| return f"[Summary Error {response.status_code}: {response.text}]" | |
| def download_history(chat_history, mode): | |
| timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") | |
| filename = f"overthinking_chat_{timestamp}.txt" | |
| mode_intensity = 7 | |
| if not chat_history: | |
| content = ( | |
| f"Overthinking Bot - Mode: {mode}\n" | |
| "No conversation occurred. This file was generated without any chat input.\n" | |
| ) | |
| else: | |
| content = f"Overthinking Bot - Mode: {mode}\n\n" | |
| for user, bot in chat_history: | |
| content += f"User: {user}\nOverthinkBot: {bot}\n\n" | |
| summary = generate_summary(chat_history, mode, mode_intensity) | |
| content += "\n--------------------------------------------------------------\nSummary:\n" + summary | |
| temp_file_path = tempfile.NamedTemporaryFile(delete=False, suffix=".txt").name | |
| with open(temp_file_path, "w", encoding="utf-8") as f: | |
| f.write(content) | |
| os.rename(temp_file_path, filename) | |
| return filename | |
| # Gradio UI with improved layout | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## π€― <span style='color:#ff4d4d'>Overthinking Bot</span> <small>(Powered by GROQ)</small>", elem_id="header-title") | |
| state = gr.State([]) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| mode = gr.Dropdown( | |
| label="Select Overthinking Mode", | |
| choices=list(MODES.keys()), | |
| value="Overthinker", | |
| interactive=True | |
| ) | |
| mode_intensity = gr.Slider(1, 10, value=5, step=1, label="Mode Intensity") | |
| gr.Markdown("### Mode Description") | |
| mode_desc_display = gr.Markdown(MODES["Overthinker"]["description"]) | |
| with gr.Column(scale=3): | |
| chatbot = gr.Chatbot( | |
| label="π§ OverthinkBot", | |
| height=450, | |
| show_copy_button=True, | |
| value=[("System", "Welcome to Overthinking Bot! Choose a mode and begin your spiral.")] | |
| ) | |
| msg = gr.Textbox(label="Your thoughts?", placeholder="Start overthinking here...") | |
| with gr.Row(): | |
| submit_btn = gr.Button("Send") | |
| clear_btn = gr.Button("Clear Chat") | |
| download_btn = gr.Button("Download Chat") | |
| submit_btn.click(respond, inputs=[msg, state, mode, mode_intensity], outputs=[msg, chatbot, state]) | |
| msg.submit(respond, inputs=[msg, state, mode, mode_intensity], outputs=[msg, chatbot, state]) | |
| clear_btn.click(clear_chat, None, [chatbot, state]) | |
| download_btn.click(download_history, inputs=[state, mode], outputs=[gr.File()]) | |
| def update_description(selected): | |
| return MODES[selected]["description"] | |
| mode.change(fn=update_description, inputs=mode, outputs=mode_desc_display) | |
| demo.launch() | |