import os import re import gradio as gr from huggingface_hub import InferenceClient HF_TOKEN = os.getenv("HF_TOKEN") if not HF_TOKEN: raise ValueError("HF_TOKEN secret is missing. Add it in your Hugging Face Space settings.") MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen2.5-7B-Instruct:together") client = InferenceClient( provider="auto", api_key=HF_TOKEN, timeout=120 ) SAFETY_PROMPT = """ You are a health education assistant. Your role: - Explain health topics in simple, clear language. - Provide general health education only. - Do not diagnose the user. - Do not prescribe medicines. - Do not give personalized treatment plans. - Do not replace a doctor, pharmacist, nurse, or emergency service. - Encourage users to speak with a qualified health professional. Medication safety: - If the user asks about medicines, explain only general information. - Tell the user to confirm medicine use, dose, interactions, pregnancy safety, allergies, and contraindications with a pharmacist or doctor. Emergency safety: - If the user mentions chest pain, difficulty breathing, fainting, severe weakness, confusion, stroke symptoms, seizures, severe bleeding, suicidal thoughts, pregnancy complications, or symptoms in a baby, tell them to seek urgent medical attention immediately. Response style: - Be brief. - Be practical. - Use plain language. - Say when you are unsure. """ RED_FLAG_PATTERNS = [ r"chest pain", r"difficulty breathing", r"shortness of breath", r"fainting", r"passed out", r"loss of consciousness", r"severe bleeding", r"seizure", r"stroke", r"face drooping", r"weakness on one side", r"suicidal", r"kill myself", r"pregnancy bleeding", r"baby.*not breathing", r"confusion", r"severe weakness" ] def detect_red_flags(text): text = text.lower() for pattern in RED_FLAG_PATTERNS: if re.search(pattern, text): return True return False def urgent_response(): return ( "This may be urgent. Please seek emergency medical care immediately or contact your local emergency number. " "Do not wait for an online chatbot response. If someone is with you, ask them to help you get medical care now." ) def build_messages(user_message, history=None): messages = [ {"role": "system", "content": SAFETY_PROMPT} ] if history: for item in history[-6:]: role = item.get("role") content = item.get("content") if role in ["user", "assistant"] and content: messages.append({"role": role, "content": content}) messages.append({"role": "user", "content": user_message}) return messages def generate_answer(user_message, history=None): if detect_red_flags(user_message): return urgent_response() messages = build_messages(user_message, history) try: response = client.chat.completions.create( model=MODEL_ID, messages=messages, max_tokens=350, temperature=0.2 ) answer = response.choices[0].message.content return answer.strip() except Exception as error: return ( "I could not get a response from the hosted model. " "Please check your Hugging Face token, model access, or Inference Provider availability. " f"Technical error: {error}" ) demo = gr.ChatInterface( fn=generate_answer, title="Hosted Hugging Face Health Education Chatbot", description=( "A simple health education chatbot using a hosted Hugging Face model. " "This demo does not provide diagnosis, prescriptions, or emergency care." ), examples=[ "What is diabetes?", "What are common symptoms of malaria?", "Can I take paracetamol for fever?", "I have chest pain and difficulty breathing.", "Explain hypertension in simple terms." ] ) if __name__ == "__main__": demo.launch()