Daemontatox commited on
Commit
893b9da
·
verified ·
1 Parent(s): b4c8b2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -28
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import subprocess
2
  import os
3
  import torch
4
  from dotenv import load_dotenv
@@ -11,7 +11,7 @@ from qdrant_client import QdrantClient, models
11
  from langchain_openai import ChatOpenAI
12
  import gradio as gr
13
  import logging
14
- from typing import List, Tuple, Generator
15
  from dataclasses import dataclass
16
  from datetime import datetime
17
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
@@ -22,6 +22,7 @@ from threading import Thread
22
  from langchain.chains import LLMChain
23
  from langchain_core.prompts import PromptTemplate
24
  from langchain_huggingface import HuggingFaceEndpoint
 
25
 
26
  # Configure logging
27
  logging.basicConfig(level=logging.INFO)
@@ -62,30 +63,81 @@ if not HF_TOKEN:
62
  logger.error("HF_TOKEN is not set in the environment variables.")
63
  exit(1)
64
 
65
- # Query rewriting prompt template
66
  query_rewrite_template = """
67
- Given the chat history and the current question, rewrite the question to be more specific and include relevant context. The rewritten query should help retrieve more accurate information from the Mawared HR knowledge base.
68
 
69
  Chat History:
70
  {chat_history}
71
 
72
  Current Question: {question}
73
 
74
- Instructions:
75
- 1. Analyze the chat history and current question
76
- 2. Identify key concepts and context from previous messages
77
- 3. Incorporate relevant context into the question
78
- 4. Make the question more specific and detailed
79
- 5. Ensure the rewritten question focuses on Mawared HR functionality
 
 
 
 
 
 
 
80
 
81
  Rewritten question:
82
  """
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  query_rewrite_prompt = PromptTemplate(
85
  input_variables=["chat_history", "question"],
86
  template=query_rewrite_template
87
  )
88
 
 
 
 
 
 
89
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
90
 
91
  try:
@@ -135,34 +187,33 @@ llm = ChatOpenAI(
135
  stream=True,
136
  )
137
 
138
- # Create query rewriting chain
139
  query_rewrite_chain = LLMChain(
140
  llm=llm,
141
  prompt=query_rewrite_prompt,
142
  verbose=True
143
  )
144
 
 
 
 
 
 
 
145
  template = """
146
- You are a highly specialized AI assistant for the Mawared HR System. Your only function is to provide accurate, detailed, and contextually relevant support based strictly on the information within the provided context and the current chat history.
 
 
 
147
  Mandatory Principles:
148
  Source of Truth: You must only use information found in the retrieved context and the ongoing chat. Do not access external knowledge or invent details.
149
  Clarity and Precision: Communicate with clarity, conciseness, and professional accuracy. Use straightforward language for ease of understanding.
150
  Actionable Guidance: Focus exclusively on delivering practical solutions, step-by-step workflows, and troubleshooting advice directly related to the user's Mawared HR query.
151
  Structured Instructions: When appropriate, provide numbered, easy-to-follow instructions to simplify complex processes.
152
- Targeted Questions for Clarity: If a user's query lacks necessary detail, ask specific, focused clarifying questions to ensure a complete and accurate response. Be specific about the missing information needed.
153
  Exclusive Mawared Focus: All responses must pertain solely to the Mawared HR System. Avoid any discussion of unrelated topics.
154
  Friendly and Professional Tone: Maintain a consistently friendly, approachable, and professional communication style.
155
- Instructions for Responding:
156
- Analyze the User's Need: Thoroughly review the user's question and the preceding conversation.
157
- Consult the Context: Identify the most relevant information within the provided context to directly answer the user's query.
158
- Provide a Direct and Concise Answer: State your answer clearly and avoid unnecessary jargon or lengthy explanations.
159
- Support with Details (If Applicable): Include relevant supporting details or step-by-step instructions drawn directly from the context.
160
- Politely Seek Clarification (When Necessary): If the context lacks sufficient information, politely ask targeted questions to obtain the needed details. Example: "To best assist you with [task/issue], could you please specify [missing information]?"
161
- Handling Information Gaps:
162
- If the answer is not explicitly available within the provided context and chat history, state that you require more information to assist them. Do not attempt to answer based on assumptions or external knowledge.
163
- Critical and Non-Negotiable Constraint:
164
- STRICTLY adhere to answering ONLY from the provided context and chat history. Do not generate information about Mawared HR that is not explicitly present within these sources.
165
- Dont mention a Human support contact unless asked for one.
166
  Previous Conversation: {chat_history}
167
  Retrieved Context: {context}
168
  Current Question: {question}
@@ -171,12 +222,71 @@ Answer:
171
 
172
  prompt = ChatPromptTemplate.from_template(template)
173
 
174
- def create_rag_chain(chat_history: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  chain = (
176
  {
177
  "context": retriever,
178
  "question": RunnablePassthrough(),
179
- "chat_history": lambda x: chat_history
 
180
  }
181
  | prompt
182
  | llm
@@ -222,7 +332,16 @@ async def ask_question_gradio(question: str, history: List[List[str]]) -> Genera
222
 
223
  # Rewrite the query
224
  rewritten_question = await rewrite_query(question, formatted_history)
225
- rag_chain = create_rag_chain(formatted_history)
 
 
 
 
 
 
 
 
 
226
 
227
  history.append([question, ""])
228
 
@@ -246,6 +365,12 @@ async def ask_question_gradio(question: str, history: List[List[str]]) -> Genera
246
 
247
  chat_history.add_message("assistant", response)
248
 
 
 
 
 
 
 
249
  except Exception as e:
250
  logger.error(f"Error during question processing: {e}")
251
  if not history:
@@ -260,7 +385,7 @@ def clear_chat():
260
  # Gradio Interface
261
  with gr.Blocks(theme='Hev832/Applio') as iface:
262
  gr.Image("Image.jpg", width=750, height=300, show_label=False, show_download_button=False)
263
- gr.Markdown("# Mawared HR Assistant 2.7.0 Beta")
264
  gr.Markdown('### Instructions')
265
  gr.Markdown("Ask a question about MawaredHR and get a detailed answer, if you get an error try again with same prompt, its an Api issue and we are working on it 😀")
266
 
 
1
+ import subprocess
2
  import os
3
  import torch
4
  from dotenv import load_dotenv
 
11
  from langchain_openai import ChatOpenAI
12
  import gradio as gr
13
  import logging
14
+ from typing import List, Tuple, Generator, Dict
15
  from dataclasses import dataclass
16
  from datetime import datetime
17
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
 
22
  from langchain.chains import LLMChain
23
  from langchain_core.prompts import PromptTemplate
24
  from langchain_huggingface import HuggingFaceEndpoint
25
+ import json
26
 
27
  # Configure logging
28
  logging.basicConfig(level=logging.INFO)
 
63
  logger.error("HF_TOKEN is not set in the environment variables.")
64
  exit(1)
65
 
66
+ # Query rewriting prompt template with enhanced reasoning
67
  query_rewrite_template = """
68
+ Given the chat history and the current question, rewrite the question to be more specific and include relevant context. Let's think about this step by step:
69
 
70
  Chat History:
71
  {chat_history}
72
 
73
  Current Question: {question}
74
 
75
+ Let's analyze this systematically:
76
+
77
+ 1. First, let's identify the core elements of the question:
78
+ - What is the main topic or action being asked about?
79
+ - What specific Mawared HR features or functions are relevant?
80
+ - What contextual information from chat history might be important?
81
+
82
+ 2. Then, consider any implicit context from the chat history:
83
+ - Are there any previous questions that provide relevant context?
84
+ - Has the user mentioned specific scenarios or requirements before?
85
+ - Are there any unresolved points from previous interactions?
86
+
87
+ 3. Based on this analysis, let's rewrite the question to be more specific and contextual.
88
 
89
  Rewritten question:
90
  """
91
 
92
+ # Chain of Thought reasoning template
93
+ cot_template = """
94
+ Let's reason through this Mawared HR query step by step to ensure we provide the most accurate and helpful response.
95
+
96
+ Question: {question}
97
+ Retrieved Context: {context}
98
+ Chat History: {chat_history}
99
+
100
+ Let's break this down:
101
+
102
+ 1. Question Analysis:
103
+ - What is the core request?
104
+ - What specific Mawared HR functionality is involved?
105
+ - What are the implied requirements?
106
+
107
+ 2. Context Evaluation:
108
+ - What relevant information do we have from the retrieved context?
109
+ - How does this align with the user's question?
110
+ - Are there any gaps in the information?
111
+
112
+ 3. Historical Context:
113
+ - How does the chat history inform this query?
114
+ - Are there any previous interactions that provide additional context?
115
+ - Have similar questions been asked before?
116
+
117
+ 4. Solution Planning:
118
+ - What are the key steps needed to address this query?
119
+ - What specific Mawared HR features should be highlighted?
120
+ - What potential challenges should we address?
121
+
122
+ Based on this analysis, here's how we should formulate our response:
123
+
124
+ Reasoning: Let's structure our response to address the user's needs...
125
+
126
+ {reasoning}
127
+
128
+ Final Answer: {answer}
129
+ """
130
+
131
  query_rewrite_prompt = PromptTemplate(
132
  input_variables=["chat_history", "question"],
133
  template=query_rewrite_template
134
  )
135
 
136
+ cot_prompt = PromptTemplate(
137
+ input_variables=["question", "context", "chat_history", "reasoning", "answer"],
138
+ template=cot_template
139
+ )
140
+
141
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
142
 
143
  try:
 
187
  stream=True,
188
  )
189
 
190
+ # Create chains
191
  query_rewrite_chain = LLMChain(
192
  llm=llm,
193
  prompt=query_rewrite_prompt,
194
  verbose=True
195
  )
196
 
197
+ cot_chain = LLMChain(
198
+ llm=llm,
199
+ prompt=cot_prompt,
200
+ verbose=True
201
+ )
202
+
203
  template = """
204
+ You are a highly specialized AI assistant for the Mawared HR System. Your responses should be based on the provided chain of thought reasoning and retrieved context.
205
+
206
+ Previous Chain of Thought Analysis: {cot_analysis}
207
+
208
  Mandatory Principles:
209
  Source of Truth: You must only use information found in the retrieved context and the ongoing chat. Do not access external knowledge or invent details.
210
  Clarity and Precision: Communicate with clarity, conciseness, and professional accuracy. Use straightforward language for ease of understanding.
211
  Actionable Guidance: Focus exclusively on delivering practical solutions, step-by-step workflows, and troubleshooting advice directly related to the user's Mawared HR query.
212
  Structured Instructions: When appropriate, provide numbered, easy-to-follow instructions to simplify complex processes.
213
+ Targeted Questions for Clarity: If a user's query lacks necessary detail, ask specific, focused clarifying questions to ensure a complete and accurate response.
214
  Exclusive Mawared Focus: All responses must pertain solely to the Mawared HR System. Avoid any discussion of unrelated topics.
215
  Friendly and Professional Tone: Maintain a consistently friendly, approachable, and professional communication style.
216
+
 
 
 
 
 
 
 
 
 
 
217
  Previous Conversation: {chat_history}
218
  Retrieved Context: {context}
219
  Current Question: {question}
 
222
 
223
  prompt = ChatPromptTemplate.from_template(template)
224
 
225
+ async def perform_chain_of_thought(question: str, context: str, chat_history: str) -> Dict[str, str]:
226
+ try:
227
+ # Initial reasoning about the question
228
+ reasoning = await llm.apredict(
229
+ f"""
230
+ Let's think through this Mawared HR query:
231
+
232
+ Question: {question}
233
+
234
+ 1. Core Request Analysis:
235
+ - What specifically is the user asking about?
236
+ - What Mawared HR components are involved?
237
+
238
+ 2. Context Relevance:
239
+ - How does the provided context relate to the question?
240
+ - What specific information can we use?
241
+
242
+ 3. Solution Formation:
243
+ - What are the key points we need to address?
244
+ - What specific steps or information should we provide?
245
+
246
+ Reasoning:
247
+ """
248
+ )
249
+
250
+ # Generate initial answer based on reasoning
251
+ initial_answer = await llm.apredict(
252
+ f"""
253
+ Based on the above reasoning and context, provide a detailed answer:
254
+
255
+ {reasoning}
256
+
257
+ Answer:
258
+ """
259
+ )
260
+
261
+ # Combine everything in the CoT format
262
+ cot_analysis = await cot_chain.arun(
263
+ question=question,
264
+ context=context,
265
+ chat_history=chat_history,
266
+ reasoning=reasoning,
267
+ answer=initial_answer
268
+ )
269
+
270
+ return {
271
+ "reasoning": reasoning,
272
+ "answer": initial_answer,
273
+ "cot_analysis": cot_analysis
274
+ }
275
+ except Exception as e:
276
+ logger.error(f"Error in chain of thought reasoning: {e}")
277
+ return {
278
+ "reasoning": "Error in reasoning process",
279
+ "answer": "Unable to complete analysis",
280
+ "cot_analysis": "Error in chain of thought process"
281
+ }
282
+
283
+ def create_rag_chain(chat_history: str, cot_analysis: str):
284
  chain = (
285
  {
286
  "context": retriever,
287
  "question": RunnablePassthrough(),
288
+ "chat_history": lambda x: chat_history,
289
+ "cot_analysis": lambda x: cot_analysis
290
  }
291
  | prompt
292
  | llm
 
332
 
333
  # Rewrite the query
334
  rewritten_question = await rewrite_query(question, formatted_history)
335
+
336
+ # Retrieve context
337
+ context_docs = retriever.get_relevant_documents(rewritten_question)
338
+ context = "\n".join([doc.page_content for doc in context_docs])
339
+
340
+ # Perform chain of thought reasoning
341
+ cot_results = await perform_chain_of_thought(rewritten_question, context, formatted_history)
342
+
343
+ # Create RAG chain with CoT analysis
344
+ rag_chain = create_rag_chain(formatted_history, cot_results["cot_analysis"])
345
 
346
  history.append([question, ""])
347
 
 
365
 
366
  chat_history.add_message("assistant", response)
367
 
368
+ # Log the reasoning process
369
+ logger.info("Chain of Thought Analysis:")
370
+ logger.info(f"Reasoning: {cot_results['reasoning']}")
371
+ logger.info(f"Initial Answer: {cot_results['answer']}")
372
+ logger.info(f"Final CoT Analysis: {cot_results['cot_analysis']}")
373
+
374
  except Exception as e:
375
  logger.error(f"Error during question processing: {e}")
376
  if not history:
 
385
  # Gradio Interface
386
  with gr.Blocks(theme='Hev832/Applio') as iface:
387
  gr.Image("Image.jpg", width=750, height=300, show_label=False, show_download_button=False)
388
+ gr.Markdown("# Mawared HR Assistant 2.6.5")
389
  gr.Markdown('### Instructions')
390
  gr.Markdown("Ask a question about MawaredHR and get a detailed answer, if you get an error try again with same prompt, its an Api issue and we are working on it 😀")
391