dpaul93 commited on
Commit
713c265
·
verified ·
1 Parent(s): b5d2d69

Update agents.py

Browse files
Files changed (1) hide show
  1. agents.py +77 -96
agents.py CHANGED
@@ -1,100 +1,81 @@
1
- import os, json, requests
2
-
3
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
4
- LLAMA_MODEL = "llama3-8b-8192"
5
- SLM_MODEL = "slm-1b"
6
-
7
- def call_groq(prompt, model=LLAMA_MODEL):
8
- response = requests.post(
9
- "https://api.groq.com/openai/v1/chat/completions",
10
- headers={"Authorization": f"Bearer {GROQ_API_KEY}"},
11
- json={
12
- "model": model,
13
- "messages": [{"role": "user", "content": prompt}],
14
- "temperature": 0.7
15
- }
16
- )
17
- if response.status_code != 200:
18
- return f"[Groq API Error {response.status_code}]: {response.text}"
19
- data = response.json()
20
- return data.get("choices", [{}])[0].get("message", {}).get("content", "[No valid response]")
21
-
22
- # --- Empathetic Chat Agent ---
23
- def run_first_aider(message, mood):
24
- prompt = f"""
25
- You're a warm and respectful AI listener. Respond to this user's message kindly and briefly, in 1-2 sentences.
26
- Do not give advice. Use supportive, non-clinical tone.
27
-
28
- Mood: {mood}
29
- Message: "{message}"
30
- """
31
- return call_groq(prompt, model=SLM_MODEL)
32
-
33
- # --- Introspect Agent (with chat/journal memory) ---
34
- def get_user_context():
35
- context = ""
36
- if os.path.exists("chat_log.json"):
37
- with open("chat_log.json") as f:
38
- chats = json.load(f)[-3:]
39
- context += "\nRecent Conversations:\n"
40
- for c in chats:
41
- context += f"User: {c['user']}\nAI: {c['ai']}\n"
42
- if os.path.exists("journal_log.json"):
43
- with open("journal_log.json") as f:
44
- logs = json.load(f)[-2:]
45
- context += "\nJournal Entries:\n"
46
- for j in logs:
47
- context += f"{j['entry']} → {j['response']}\n"
48
- return context if context.strip() else None
49
-
50
- def run_introspect(message, mood):
51
- context = get_user_context()
52
- if not context:
53
- return "Let's first talk a bit or write a few journal entries."
54
-
55
- prompt = f"""
56
- Based on this context:
57
- {context}
58
-
59
- The user says: "{message}"
60
- Their mood is: {mood}
61
-
62
- Offer a kind and short reflection. Suggest something gentle like a shift in perspective, or a small action.
63
- Never use words like therapy, CBT, mental health, or psychology.
64
- """
65
- return call_groq(prompt, model=LLAMA_MODEL)
66
 
67
- # --- Journal Agent with mood context ---
68
- def get_mood_context():
69
- if not os.path.exists("journal_log.json"): return []
70
  with open("journal_log.json") as f:
71
  logs = json.load(f)
72
- return [x["mood"] for x in logs[-3:]]
73
-
74
- def run_journaling_pipeline(mood, entry, mode):
75
- recent_moods = get_mood_context()
76
- context_line = f"Recent moods: {', '.join(recent_moods)}." if recent_moods else "No recent mood history."
77
- question = "What emotional patterns do you notice in your life recently?" if recent_moods else "What stood out to you emotionally today?"
78
-
79
- prompt = f"""
80
- You are a calm, non-judgmental journaling assistant.
81
-
82
- User mode: {mode}
83
- Mood: {mood}
84
- User wrote: "{entry}"
85
- {context_line}
86
- Question: {question}
87
-
88
- Reflect back to the user with kind interpretation, help them notice something they may have missed.
89
- End with a gentle affirmation or reflective nudge.
90
-
91
- Avoid therapy talk.
92
- """
93
-
94
- response = call_groq(prompt, model=LLAMA_MODEL)
95
- return {
96
- "entry": entry,
97
- "mood": mood,
98
- "mode": mode,
99
- "response": response
100
  }
 
 
1
+ import os, json
2
+ from datetime import datetime
3
+ from collections import Counter
4
+ from fpdf import FPDF
5
+ import matplotlib.pyplot as plt
6
+
7
+ # --- Logging ---
8
+ def log_chat_interaction(user_msg, ai_reply, mood):
9
+ file = "chat_log.json"
10
+ logs = []
11
+ if os.path.exists(file):
12
+ with open(file) as f: logs = json.load(f)
13
+ logs.append({
14
+ "timestamp": datetime.utcnow().isoformat(),
15
+ "mood": mood,
16
+ "user": user_msg,
17
+ "ai": ai_reply
18
+ })
19
+ with open(file, "w") as f: json.dump(logs, f, indent=2)
20
+
21
+ def log_entry(entry_obj):
22
+ file = "journal_log.json"
23
+ logs = []
24
+ if os.path.exists(file):
25
+ with open(file) as f: logs = json.load(f)
26
+ logs.append({
27
+ **entry_obj,
28
+ "timestamp": datetime.utcnow().isoformat()
29
+ })
30
+ with open(file, "w") as f: json.dump(logs, f, indent=2)
31
+
32
+ # --- Export ---
33
+ def export_to_pdf(entry, mood, mode):
34
+ pdf = FPDF()
35
+ pdf.add_page()
36
+ pdf.set_font("Arial", size=12)
37
+ pdf.multi_cell(0, 10, f"Journaling Mode: {mode}\nMood: {mood}\nEntry:\n{entry}")
38
+ path = "journal_export.pdf"
39
+ pdf.output(path)
40
+ return path
41
+
42
+ def export_to_md(entry, mood, mode):
43
+ text = f"### Journal Entry\n**Mode**: {mode}\n**Mood**: {mood}\n\n{entry}"
44
+ path = "journal_export.md"
45
+ with open(path, "w") as f: f.write(text)
46
+ return path
47
+
48
+ # --- Counselor Analytics ---
49
+ def get_weekly_summary():
50
+ if not os.path.exists("journal_log.json"):
51
+ return {"error": "No logs yet."}
52
+ with open("journal_log.json") as f:
53
+ logs = json.load(f)[-7:]
54
+ return {
55
+ "total_entries": len(logs),
56
+ "mood_trend": Counter(x["mood"] for x in logs),
57
+ "frequent_words": Counter(" ".join(x["entry"] for x in logs).split()).most_common(7)
58
+ }
 
 
 
 
 
 
 
59
 
60
+ def generate_emotion_map():
61
+ if not os.path.exists("journal_log.json"): return None
 
62
  with open("journal_log.json") as f:
63
  logs = json.load(f)
64
+ moods = [x["mood"] for x in logs]
65
+ mood_count = Counter(moods)
66
+ plt.bar(mood_count.keys(), mood_count.values())
67
+ plt.title("Mood Trend")
68
+ plt.savefig("assets/emotion_map.png")
69
+ return "assets/emotion_map.png"
70
+
71
+ def get_counselor_view():
72
+ if not os.path.exists("journal_log.json"): return "No logs yet."
73
+ with open("journal_log.json") as f:
74
+ logs = json.load(f)
75
+ insights = {
76
+ "Total Journals": len(logs),
77
+ "Mood Counts": Counter(x["mood"] for x in logs),
78
+ "Flags (e.g., 'hopeless')": sum("hopeless" in x["entry"].lower() for x in logs),
79
+ "Flags (e.g., 'tired')": sum("tired" in x["entry"].lower() for x in logs)
 
 
 
 
 
 
 
 
 
 
 
 
80
  }
81
+ return "\n".join([f"{k}: {v}" for k, v in insights.items()])