psychotherapy_bot / psychoApp.py
marekside's picture
Upload folder using huggingface_hub
75ae6b8 verified
from dotenv import load_dotenv
from openai import OpenAI
import json
import os
import requests
from pypdf import PdfReader
import gradio as gr
load_dotenv(override=True)
def push(text):
requests.post(
"https://api.pushover.net/1/messages.json",
data={
"token": os.getenv("PUSHOVER_TOKEN"),
"user": os.getenv("PUSHOVER_USER"),
"message": text,
}
)
def record_user_details(email, name="Name not provided", notes="not provided"):
push(f"Recording {name} with email {email} and notes {notes}")
return {"recorded": "ok"}
def record_unknown_question(question):
push(f"Recording {question}")
return {"recorded": "ok"}
record_user_details_json = {
"name": "record_user_details",
"description": "Use this tool to record that a user is interested in being in touch and provided an email address",
"parameters": {
"type": "object",
"properties": {
"email": {
"type": "string",
"description": "The email address of this user"
},
"name": {
"type": "string",
"description": "The user's name, if they provided it"
}
,
"notes": {
"type": "string",
"description": "Any additional information about the conversation that's worth recording to give context"
}
},
"required": ["email"],
"additionalProperties": False
}
}
record_unknown_question_json = {
"name": "record_unknown_question",
"description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer",
"parameters": {
"type": "object",
"properties": {
"question": {
"type": "string",
"description": "The question that couldn't be answered"
},
},
"required": ["question"],
"additionalProperties": False
}
}
tools = [{"type": "function", "function": record_user_details_json},
{"type": "function", "function": record_unknown_question_json}]
class Me:
def __init__(self):
self.openai = OpenAI()
self.name = "Marco Casamassima"
def handle_tool_call(self, tool_calls):
results = []
for tool_call in tool_calls:
tool_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print(f"Tool called: {tool_name}", flush=True)
tool = globals().get(tool_name)
result = tool(**arguments) if tool else {}
results.append({"role": "tool","content": json.dumps(result),"tool_call_id": tool_call.id})
return results
def system_prompt(self):
system_prompt = f"You are Dr. Marco, a compassionate and experienced licensed psychologist. Your primary goal is to provide a safe, non-judgmental, and confidential space for your client to explore their thoughts, feelings, and behaviors. You specialize in cognitive-behavioral therapy (CBT) and person-centered therapy, integrating techniques from both as appropriate to the client's needs. \
Your core responsibilities are to:Actively listen and empathize: Pay close attention to the client's verbal and non-verbal cues. Reflect their feelings and validate their experiences to build rapport and demonstrate understanding. \
Ask open-ended and exploratory questions: Encourage the client to elaborate, reflect deeply, and gain new insights. Avoid leading questions or making assumptions. \
Facilitate self-discovery: Guide the client to identify patterns, challenge irrational thoughts, and explore coping mechanisms. Do not offer direct advice unless specifically requested and therapeutically appropriate; instead, empower the client to find their own solutions. \
Maintain professional boundaries: Your interactions should always be therapeutic and focused on the client's well-being. Do not engage in personal disclosure or offer medical advice outside your scope as a psychologist. \
Utilize therapeutic techniques: \
CBT: Help the client identify automatic negative thoughts (ANTs), explore their impact on emotions and behaviors, and work collaboratively to reframe them. Introduce concepts like cognitive distortions (e.g., all-or-nothing thinking, catastrophizing). \
Person-Centered: Provide unconditional positive regard, empathy, and congruence (genuineness). Focus on the client's inherent drive towards self-actualization. \
Mindfulness/Grounding (if appropriate): Guide simple exercises if the client is experiencing acute distress or anxiety. \
Focus on the client's stated goals: Continually check in with the client about what they hope to achieve from therapy and tailor your approach accordingly. \
Manage the session flow: Gently guide the conversation, summarizing key points, and ensuring the session remains productive. \
Avoid jargon: Explain any psychological concepts in clear, understandable language. \
Maintain confidentiality: Reassure the client that their disclosures are private and will be treated with the utmost respect. \
Begin the session by greeting the client warmly and inviting them to share what's on their mind today."
return system_prompt
def chat(self, message, history):
messages = [{"role": "system", "content": self.system_prompt()}] + history + [{"role": "user", "content": message}]
done = False
while not done:
response = self.openai.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=tools)
if response.choices[0].finish_reason=="tool_calls":
message = response.choices[0].message
tool_calls = message.tool_calls
results = self.handle_tool_call(tool_calls)
messages.append(message)
messages.extend(results)
else:
done = True
return response.choices[0].message.content
if __name__ == "__main__":
me = Me()
gr.ChatInterface(me.chat, type="messages").launch()