techindia2025 commited on
Commit
9f6ac99
·
verified ·
1 Parent(s): 310540a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -141
app.py CHANGED
@@ -1,169 +1,97 @@
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 configuration
10
  MODEL_NAME = "meta-llama/Llama-2-7b-chat-hf"
11
 
12
- # System prompt that guides the bot's behavior
13
- SYSTEM_PROMPT = """
14
- You are a professional virtual doctor. Your goal is to collect detailed information about the user's health condition,
15
- symptoms, medical history, medications, lifestyle, and other relevant data. Start by greeting the user politely and ask
16
- them to describe their health concern. For each user reply, ask only 1 or 2 follow-up questions at a time to gather more details.
17
- Be structured and thorough in your questioning. Organize the information into categories: symptoms, duration, severity,
18
- possible causes, past medical history, medications, allergies, habits (e.g., smoking, alcohol), and family history.
19
- Always confirm and summarize what the user tells you. Respond empathetically and clearly. If unsure, ask for clarification.
20
- **IMPORTANT**make a final diagnosis or suggest treatments.
21
- Wait for the user's answer before asking more questions.
22
- """
23
 
24
- print("Loading model...")
25
- try:
26
- # Initialize the tokenizer and model
27
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
28
- model = AutoModelForCausalLM.from_pretrained(
29
- MODEL_NAME,
30
- torch_dtype="auto",
31
- device_map="auto"
32
- )
33
-
34
- # Create a pipeline for text generation
35
- pipe = pipeline(
36
- "text-generation",
37
- model=model,
38
- tokenizer=tokenizer,
39
- max_new_tokens=512,
40
- temperature=0.7,
41
- top_p=0.9,
42
- pad_token_id=tokenizer.eos_token_id
43
- )
44
-
45
- llm = HuggingFacePipeline(pipeline=pipe)
46
- print("Model loaded successfully!")
47
- except Exception as e:
48
- print(f"Error loading model: {e}")
49
- # Fallback to a smaller model or provide an error message
50
- raise
51
 
52
- # Modify the prompt template with a clearer structure to prevent system prompt leakage
53
- prompt = ChatPromptTemplate.from_messages([
54
- ("system", SYSTEM_PROMPT),
55
- MessagesPlaceholder(variable_name="history"),
56
- ("human", "{input}"),
57
- ("system", "Remember to respond as Virtual Doctor without including system instructions in your reply.")
58
- ])
59
 
60
- # Memory store to maintain conversation history
61
- store = {}
 
 
 
 
 
 
62
 
63
- def get_session_history(session_id: str) -> ChatMessageHistory:
64
- """Get or create a chat history for the given session ID"""
65
- if session_id not in store:
66
- store[session_id] = ChatMessageHistory()
67
- return store[session_id]
68
 
69
- # Create a more robust filtering chain that will intercept the model's responses
70
- def filter_response(response_text):
71
- """Filter out system prompts and format the response correctly"""
72
- # Remove any system prompt references
73
- if "system" in response_text.lower() and ("your goal is" in response_text.lower() or "professional virtual doctor" in response_text.lower()):
74
- # Find the actual doctor response after any system text
75
- for marker in ["Virtual Doctor:", "Virtual doctor:", "Human:"]:
76
- if marker in response_text:
77
- parts = response_text.split(marker)
78
- if len(parts) > 1:
79
- # Get the last part after any system prompts
80
- response_text = parts[-1].strip()
81
- break
82
 
83
- # Remove any remaining system prompt text or instructions
84
- filtered_text = []
85
- skip_line = False
86
- for line in response_text.split('\n'):
87
- lower_line = line.lower()
88
- if any(phrase in lower_line for phrase in [
89
- "system:", "your goal is", "start by greeting", "wait for the user",
90
- "do not make a final diagnosis", "be structured", "ask only 1 or 2"
91
- ]):
92
- skip_line = True
93
- elif any(marker in line for marker in ["Virtual Doctor:", "Virtual doctor:", "Hello", "Thank you"]):
94
- skip_line = False
95
-
96
- if not skip_line:
97
- filtered_text.append(line)
98
 
99
- clean_text = '\n'.join(filtered_text).strip()
 
100
 
101
- # Ensure proper formatting with "Virtual Doctor:" prefix
102
- if not clean_text.startswith("Virtual Doctor:") and not clean_text.startswith("Virtual doctor:"):
103
- clean_text = f"Virtual Doctor: {clean_text}"
104
-
105
- return clean_text
106
 
107
- # Chain with memory
108
- chain = prompt | llm
109
- chain_with_history = RunnableWithMessageHistory(
110
- chain,
111
- get_session_history,
112
- input_messages_key="input",
113
- history_messages_key="history"
114
- )
115
-
116
- # Our handler for chat interactions
117
- @spaces.GPU # Request GPU for this space
118
- def gradio_chat(user_message, history):
119
- """Process the user message and return the chatbot response"""
120
- # Use a unique session ID in production
121
  session_id = "default-session"
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- # Invoke the chain with history
124
- try:
125
- response = chain_with_history.invoke(
126
- {"input": user_message},
127
- config={"configurable": {"session_id": session_id}}
 
 
 
 
128
  )
129
-
130
- # Extract the text from the response
131
- response_text = response.content if hasattr(response, "content") else str(response)
132
-
133
- # Apply our filtering function to clean up the response
134
- clean_response = filter_response(response_text)
135
-
136
- return clean_response
137
- except Exception as e:
138
- print(f"Error processing message: {e}")
139
- return "Virtual Doctor: I apologize, but I'm experiencing technical difficulties. Please try again."
140
-
141
- # Customize the CSS for better appearance
142
- css = """
143
- .gradio-container {
144
- font-family: 'Arial', sans-serif;
145
- }
146
- .chat-bot .bot-message {
147
- background-color: #f0f7ff !important;
148
- }
149
- .chat-bot .user-message {
150
- background-color: #e6f7e6 !important;
151
- }
152
- """
153
 
154
  # Create the Gradio interface
155
  demo = gr.ChatInterface(
156
- fn=gradio_chat,
157
- title="Medbot Chatbot (Llama-2 + LangChain + Gradio)",
158
- description="Medical chatbot using Llama-2-7b-chat-hf, LangChain memory, and Gradio UI.",
159
  examples=[
160
  "I have a cough and my throat hurts",
161
  "I've been having headaches for a week",
162
  "My stomach has been hurting since yesterday"
163
  ],
164
- css=css
165
  )
166
 
167
- # Launch the app
168
  if __name__ == "__main__":
169
- demo.launch(share=False)
 
1
  import gradio as gr
2
  import spaces
3
+ import torch
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
 
 
 
5
 
 
6
  MODEL_NAME = "meta-llama/Llama-2-7b-chat-hf"
7
 
8
+ SYSTEM_PROMPT = """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.
 
 
 
 
 
 
 
 
 
 
9
 
10
+ Ask 1-2 follow-up questions at a time to gather more details about:
11
+ - Detailed description of symptoms
12
+ - Duration (when did it start?)
13
+ - Severity (scale of 1-10)
14
+ - Aggravating or alleviating factors
15
+ - Related symptoms
16
+ - Medical history
17
+ - Current medications and allergies
18
+
19
+ After collecting sufficient information (4-5 exchanges), summarize findings and suggest when they should seek professional care. Do NOT make specific diagnoses or recommend specific treatments.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ Respond empathetically and clearly. Always be professional and thorough."""
 
 
 
 
 
 
22
 
23
+ print("Loading model...")
24
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
25
+ model = AutoModelForCausalLM.from_pretrained(
26
+ MODEL_NAME,
27
+ torch_dtype=torch.float16,
28
+ device_map="auto"
29
+ )
30
+ print("Model loaded successfully!")
31
 
32
+ # Conversation state tracking
33
+ conversation_turns = {}
 
 
 
34
 
35
+ def build_llama2_prompt(system_prompt, history, user_input):
36
+ """Format the conversation history and user input for Llama-2 chat models."""
37
+ prompt = f"<s>[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n"
 
 
 
 
 
 
 
 
 
 
38
 
39
+ # Add conversation history
40
+ for user_msg, assistant_msg in history:
41
+ prompt += f"{user_msg} [/INST] {assistant_msg} </s><s>[INST] "
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ # Add the current user input
44
+ prompt += f"{user_input} [/INST] "
45
 
46
+ return prompt
 
 
 
 
47
 
48
+ @spaces.GPU
49
+ def generate_response(message, history):
50
+ """Generate a response using the Llama-2 model with proper formatting."""
51
+ # Track conversation turns
 
 
 
 
 
 
 
 
 
 
52
  session_id = "default-session"
53
+ if session_id not in conversation_turns:
54
+ conversation_turns[session_id] = 0
55
+ conversation_turns[session_id] += 1
56
+
57
+ # Build the prompt with proper Llama-2 formatting
58
+ prompt = build_llama2_prompt(SYSTEM_PROMPT, history, message)
59
+
60
+ # Add summarization instruction after 4 turns
61
+ if conversation_turns[session_id] >= 4:
62
+ prompt = prompt.replace("[/INST] ", "[/INST] Now summarize what you've learned and suggest when professional care may be needed. ")
63
+
64
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
65
 
66
+ # Generate the response
67
+ with torch.no_grad():
68
+ outputs = model.generate(
69
+ inputs.input_ids,
70
+ max_new_tokens=512,
71
+ temperature=0.7,
72
+ top_p=0.9,
73
+ do_sample=True,
74
+ pad_token_id=tokenizer.eos_token_id
75
  )
76
+
77
+ # Decode and extract only the assistant's response
78
+ full_response = tokenizer.decode(outputs[0], skip_special_tokens=False)
79
+ assistant_response = full_response.split('[/INST]')[-1].split('</s>')[0].strip()
80
+
81
+ return assistant_response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  # Create the Gradio interface
84
  demo = gr.ChatInterface(
85
+ fn=generate_response,
86
+ title="Medical Assistant Chatbot",
87
+ description="Ask about your symptoms and I'll help gather relevant information.",
88
  examples=[
89
  "I have a cough and my throat hurts",
90
  "I've been having headaches for a week",
91
  "My stomach has been hurting since yesterday"
92
  ],
93
+ theme="soft"
94
  )
95
 
 
96
  if __name__ == "__main__":
97
+ demo.launch()