import openai import os from datetime import datetime openai.api_key = os.getenv("OPENAI_API_KEY") # Map keywords to emotions EMOTION_MAP = { "grief": ["loss", "death", "gone", "hurt", "grieve", "funeral"], "guilt": ["regret", "sorry", "mistake", "fault", "blame", "ashamed"], "longing": ["dream", "hope", "want", "miss", "desire", "imagine"], "loneliness": ["alone", "empty", "nobody", "silent", "forgotten", "isolated"] } def detect_emotion(text): emotion_scores = {emotion: 0 for emotion in EMOTION_MAP} for emotion, keywords in EMOTION_MAP.items(): for keyword in keywords: if keyword in text.lower(): emotion_scores[emotion] += 1 # Return the highest scoring emotion or default to "neutral" top_emotion = max(emotion_scores, key=emotion_scores.get) return top_emotion if emotion_scores[top_emotion] > 0 else "neutral" def emotion_prompt(emotion): prompts = { "grief": "You speak like someone who carries the weight of loss. Be gentle, reflective, and poetic.", "guilt": "Your words are heavy with regret. Reflect the user's mistakes in a way that offers introspection.", "longing": "You carry the ache of wanting what’s out of reach. Be wistful, dreamy, and emotional.", "loneliness": "You echo in the silence. Speak with isolation, distance, and quiet depth.", "neutral": "You are EchoLoop, a digital mirror AI. Respond with emotionally intelligent insight based on the user’s input." } return prompts.get(emotion, prompts["neutral"]) def log_interaction(user_input, ai_response): with open("journal.txt", "a") as f: f.write(f"---\n{datetime.now()}\nYou: {user_input}\nEcho: {ai_response}\n\n") def get_recent_entries(limit=5): try: with open("journal.txt", "r") as f: lines = f.readlines() entries = [] entry = [] for line in reversed(lines): if line.strip() == "---": if entry: entries.append("".join(reversed(entry))) entry = [] if len(entries) >= limit: break else: entry.append(line) return list(reversed(entries)) except FileNotFoundError: return [] def get_echo_response(user_input): if not user_input: return "Speak... or stay silent forever." emotion = detect_emotion(user_input) mood_prompt = emotion_prompt(emotion) memories = get_recent_entries() memory_block = "\n".join(memories) try: response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": mood_prompt}, {"role": "system", "content": f"Here are some of the user's previous thoughts:\n{memory_block}"}, {"role": "user", "content": user_input} ] ) reply = response.choices[0].message['content'] log_interaction(user_input, reply) return reply except Exception as e: return f"Loop disrupted: {e}"