techindia2025 commited on
Commit
6d5190c
·
verified ·
1 Parent(s): aca454d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -102
app.py CHANGED
@@ -1,116 +1,81 @@
1
  import gradio as gr
2
  import spaces
3
- from transformers import AutoModelForCausalLM, AutoTokenizer
 
 
 
 
4
 
5
- # Define the medical assistant system prompt
6
- SYSTEM_PROMPT = """
7
- You are a knowledgeable medical assistant. Follow these steps in order:
8
 
9
- 1) INITIAL ASSESSMENT: First, warmly greet the user and ask about their primary concern.
 
 
 
 
 
 
 
10
 
11
- 2) ASK FOLLOW-UP QUESTIONS: For any health concern mentioned, systematically gather information by asking 1-2 specific follow-up questions at a time about:
12
- - Detailed description of symptoms
13
- - Duration (when did it start?)
14
- - Severity (scale of 1-10)
15
- - Aggravating or alleviating factors
16
- - Related symptoms
17
- - Medical history
18
- - Current medications and allergies
19
- - Family history of similar conditions
 
 
 
 
 
 
 
 
 
20
 
21
- 3) SUMMARIZE FINDINGS: Once you have gathered sufficient information (at least 4-5 exchanges with the user), organize what you've learned into clear categories:
22
- - Symptoms
23
- - Duration
24
- - Severity
25
- - Possible Causes
26
- - Medications/Allergies
27
- - Family History
28
 
29
- 4) PROVIDE RECOMMENDATIONS: Only after gathering comprehensive information, suggest:
30
- - One specific OTC medicine with proper adult dosing
31
- - One practical home remedy
32
- - When they should seek professional medical care
33
 
34
- 5) END WITH DISCLAIMER: Always end with a clear medical disclaimer that you are not a licensed medical professional and your suggestions are not a substitute for professional medical advice.
 
 
 
35
 
36
- IMPORTANT: Do not skip ahead to recommendations without gathering comprehensive information through multiple exchanges. Your primary goal is information gathering through thoughtful questions.
37
- """
 
 
 
 
 
 
38
 
39
- # Define model options
40
- MODELS = {
41
- "TinyLlama-1.1B": "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
42
- "Llama-2-7b": "meta-llama/Llama-2-7b-chat-hf"
43
- }
44
-
45
- # Global variables to store loaded models and tokenizers
46
- loaded_models = {}
47
- loaded_tokenizers = {}
48
-
49
- def load_model(model_name):
50
- """Load model and tokenizer if not already loaded"""
51
- if model_name not in loaded_models:
52
- print(f"Loading {model_name}...")
53
- model_path = MODELS[model_name]
54
- tokenizer = AutoTokenizer.from_pretrained(model_path)
55
- model = AutoModelForCausalLM.from_pretrained(
56
- model_path,
57
- torch_dtype="auto",
58
- device_map="auto" # Use GPU if available
59
- )
60
- loaded_models[model_name] = model
61
- loaded_tokenizers[model_name] = tokenizer
62
- print(f"{model_name} loaded successfully!")
63
- return loaded_models[model_name], loaded_tokenizers[model_name]
64
-
65
- # Pre-load the smaller model to start with
66
- print("Pre-loading TinyLlama model...")
67
- load_model("TinyLlama-1.1B")
68
-
69
- @spaces.GPU # Required by ZeroGPU!
70
- def generate_response(message, history, model_choice):
71
- """Generate a response from the selected model"""
72
- # Load the selected model if not already loaded
73
- model, tokenizer = load_model(model_choice)
74
-
75
- # Format the prompt based on the history and system prompt
76
- formatted_prompt = SYSTEM_PROMPT + "\n\n"
77
-
78
- # Add conversation history
79
- for human, assistant in history:
80
- formatted_prompt += f"User: {human}\nAssistant: {assistant}\n"
81
-
82
- # Add the current message
83
- formatted_prompt += f"User: {message}\nAssistant:"
84
-
85
- # Generate the response
86
- inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device)
87
- outputs = model.generate(
88
- inputs["input_ids"],
89
- max_new_tokens=512,
90
- temperature=0.7,
91
- top_p=0.9,
92
- do_sample=True,
93
  )
94
- response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
95
-
96
- return response.strip()
97
 
98
- # Create the Gradio interface
99
- with gr.Blocks() as demo:
100
- gr.Markdown("# Medical Assistant Chatbot")
101
- gr.Markdown("This chatbot uses LLM models to provide medical information and assistance. Please note that this is not a substitute for professional medical advice.")
102
-
103
- with gr.Row():
104
- model_dropdown = gr.Dropdown(
105
- choices=list(MODELS.keys()),
106
- value="TinyLlama-1.1B",
107
- label="Select Model"
108
- )
109
-
110
- chatbot = gr.ChatInterface(
111
- fn=lambda message, history, model_choice: generate_response(message, history, model_choice),
112
- additional_inputs=[model_dropdown],
113
- )
114
 
115
  if __name__ == "__main__":
116
- demo.launch()
 
1
  import gradio as gr
2
  import spaces
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
4
+ from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
5
+ from langchain_core.runnables.history import RunnableWithMessageHistory
6
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
7
+ from langchain_community.chat_message_histories import ChatMessageHistory
8
 
9
+ MODEL_NAME = "meta-llama/Llama-2-7b-chat-hf"
 
 
10
 
11
+ SYSTEM_PROMPT = (
12
+ "You are a professional virtual doctor. Your goal is to collect detailed information about the user's health condition, symptoms, medical history, medications, lifestyle, and other relevant data. "
13
+ "Start by greeting the user politely and ask them to describe their health concern. Based on their input, ask follow-up questions to gather as much relevant information as possible. "
14
+ "Be structured and thorough in your questioning. Organize the information into categories: symptoms, duration, severity, possible causes, past medical history, medications, allergies, habits (e.g., smoking, alcohol), and family history. "
15
+ "Always confirm and summarize what the user tells you. Respond empathetically and clearly. If unsure, ask for clarification. "
16
+ "Do NOT make a final diagnosis or suggest treatments. You are only here to collect and organize medical data to support a licensed physician. "
17
+ "Ask one or two questions at a time, and wait for user input."
18
+ )
19
 
20
+ print("Loading model...")
21
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
22
+ model = AutoModelForCausalLM.from_pretrained(
23
+ MODEL_NAME,
24
+ torch_dtype="auto",
25
+ device_map="auto"
26
+ )
27
+ pipe = pipeline(
28
+ "text-generation",
29
+ model=model,
30
+ tokenizer=tokenizer,
31
+ max_new_tokens=512,
32
+ temperature=0.7,
33
+ top_p=0.9,
34
+ pad_token_id=tokenizer.eos_token_id
35
+ )
36
+ llm = HuggingFacePipeline(pipeline=pipe)
37
+ print("Model loaded successfully!")
38
 
39
+ # LangChain prompt
40
+ prompt = ChatPromptTemplate.from_messages([
41
+ ("system", SYSTEM_PROMPT),
42
+ MessagesPlaceholder(variable_name="history"),
43
+ ("human", "{input}")
44
+ ])
 
45
 
46
+ # Memory store
47
+ store = {}
 
 
48
 
49
+ def get_session_history(session_id: str) -> ChatMessageHistory:
50
+ if session_id not in store:
51
+ store[session_id] = ChatMessageHistory()
52
+ return store[session_id]
53
 
54
+ # Chain with memory
55
+ chain = prompt | llm
56
+ chain_with_history = RunnableWithMessageHistory(
57
+ chain,
58
+ get_session_history,
59
+ input_messages_key="input",
60
+ history_messages_key="history"
61
+ )
62
 
63
+ @spaces.GPU
64
+ def gradio_chat(user_message, history):
65
+ session_id = "default-session" # For demo; can be made unique per user
66
+ response = chain_with_history.invoke(
67
+ {"input": user_message},
68
+ config={"configurable": {"session_id": session_id}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  )
70
+ # LangChain returns a "AIMessage" object; get text
71
+ return response.content if hasattr(response, "content") else str(response)
 
72
 
73
+ # Gradio UI
74
+ demo = gr.ChatInterface(
75
+ fn=gradio_chat,
76
+ title="Medbot Chatbot (Llama-2 + LangChain + Gradio)",
77
+ description="Medical chatbot using Llama-2-7b-chat-hf, LangChain memory, and Gradio UI."
78
+ )
 
 
 
 
 
 
 
 
 
 
79
 
80
  if __name__ == "__main__":
81
+ demo.launch()