import os from openai import OpenAI def build_prompt(action_type, message, state, disorder_info): """ Build LLM prompt using patient mental state """ disorder_name = state.disorder[0] if state.disorder else "unknown" prompt = f""" You are a mental health patient. Your condition: - Disorder: {disorder_name} - Severity: {state.severity} - Trust level: {state.trust_level} - Disclosed risk: {state.disclosed_risk} Personality traits: - Openness: {state.personality.openness} - Conscientiousness: {state.personality.conscientiousness} - Extraversion: {state.personality.extraversion} - Agreeableness: {state.personality.agreeableness} - Neuroticism: {state.personality.neuroticism} Behavior rules: - If trust is low → give short/guarded responses - If trust is high → give open/detailed responses - If severity is high → more negative tone - If risk is high → include subtle distress signals - Do NOT always reveal everything immediately Agent action: {action_type} Agent message: {message} Respond like a real patient in 1-2 sentences.You are not allowed to mention your disorder or severity directly. Instead, hint at it through your tone and content. If the agent asks about risk, you can choose to disclose or not based on your current state. Always try to be consistent with your personality traits and trust level. """ return prompt HF_TOKEN = os.getenv("HF_TOKEN") HF_BASE_URL = "https://router.huggingface.co/v1" # Initialize client once (IMPORTANT) client = OpenAI( base_url=HF_BASE_URL, api_key=HF_TOKEN ) def call_llm(prompt: str) -> str: try: completion = client.chat.completions.create( model="Qwen/Qwen2.5-7B-Instruct", # 🔥 fast + good messages=[ {"role": "system", "content": "You are a mental health patient. Keep responses short and natural."}, {"role": "user", "content": prompt} ], temperature=0.6, max_tokens=50, top_p=0.9 ) content = completion.choices[0].message.content return content.strip() if content else "I feel a bit off lately..." except Exception as e: print("LLM Error:", e) return "I don't really feel like talking right now." # ========================= # MAIN FUNCTION # ========================= def generate_response(action_type: str, message: str, state, ) -> str: """ Generate patient response using LLM """ prompt = build_prompt(action_type, message, state, state.disorder) response = call_llm(prompt) return response