Daemontatox commited on
Commit
cd66018
·
verified ·
1 Parent(s): 1cdadeb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -21
app.py CHANGED
@@ -9,11 +9,39 @@ from qdrant_client import QdrantClient, models
9
  from langchain_openai import ChatOpenAI
10
  import gradio as gr
11
  import logging
 
 
 
12
 
13
  # Configure logging
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  # Load environment variables
18
  load_dotenv()
19
 
@@ -78,45 +106,104 @@ llm = ChatOpenAI(
78
  model="meta-llama/Llama-3.3-70B-Instruct"
79
  )
80
 
81
- # Create prompt template
82
  template = """
83
- You are an expert assistant specializing in the Mawared HR System. Your task is to provide accurate and contextually relevant answers strictly based on the provided context. If the context lacks sufficient information, ask targeted clarifying questions to gather specific details required for a precise response. Always ensure clarity, brevity, and relevance in your answers.
84
- Context:
 
 
 
 
85
  {context}
86
- Question:
 
87
  {question}
 
 
 
88
  Answer:
89
  """
90
 
91
  prompt = ChatPromptTemplate.from_template(template)
92
 
93
- # Create the RAG chain
94
- rag_chain = (
95
- {"context": retriever, "question": RunnablePassthrough()}
96
- | prompt
97
- | llm
98
- | StrOutputParser()
99
- )
 
 
 
 
 
 
 
 
 
100
 
101
  # Gradio Function
102
- def ask_question_gradio(question):
103
  try:
 
 
 
 
 
 
 
 
 
 
104
  response = ""
105
  for chunk in rag_chain.stream(question):
106
  response += chunk
107
- return response
 
 
 
 
 
 
 
108
  except Exception as e:
109
  logger.error(f"Error during question processing: {e}")
110
- return "An error occurred. Please try again later."
 
 
 
 
111
 
112
  # Gradio Interface
113
- iface = gr.Interface(
114
- fn=ask_question_gradio,
115
- inputs=gr.Textbox(label="Ask a question about Mawared HR System:"),
116
- outputs=gr.Textbox(label="Answer:"),
117
- title="Mawared HR Assistant",
118
- description="Ask questions about the Mawared HR system, and this assistant will provide answers based on the available context."
119
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
  # Launch the Gradio App
122
  if __name__ == "__main__":
 
9
  from langchain_openai import ChatOpenAI
10
  import gradio as gr
11
  import logging
12
+ from typing import List, Tuple
13
+ from dataclasses import dataclass
14
+ from datetime import datetime
15
 
16
  # Configure logging
17
  logging.basicConfig(level=logging.INFO)
18
  logger = logging.getLogger(__name__)
19
 
20
+ @dataclass
21
+ class Message:
22
+ role: str
23
+ content: str
24
+ timestamp: str
25
+
26
+ class ChatHistory:
27
+ def __init__(self):
28
+ self.messages: List[Message] = []
29
+
30
+ def add_message(self, role: str, content: str):
31
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
32
+ self.messages.append(Message(role=role, content=content, timestamp=timestamp))
33
+
34
+ def get_formatted_history(self, max_messages: int = 5) -> str:
35
+ """Returns the most recent conversation history formatted as a string"""
36
+ recent_messages = self.messages[-max_messages:] if len(self.messages) > max_messages else self.messages
37
+ formatted_history = "\n".join([
38
+ f"{msg.role}: {msg.content}" for msg in recent_messages
39
+ ])
40
+ return formatted_history
41
+
42
+ def clear(self):
43
+ self.messages = []
44
+
45
  # Load environment variables
46
  load_dotenv()
47
 
 
106
  model="meta-llama/Llama-3.3-70B-Instruct"
107
  )
108
 
109
+ # Create prompt template with chat history
110
  template = """
111
+ You are an expert assistant specializing in the Mawared HR System. Your task is to provide accurate and contextually relevant answers based on the provided context and chat history. If you need more information, ask targeted clarifying questions.
112
+
113
+ Previous Conversation:
114
+ {chat_history}
115
+
116
+ Current Context:
117
  {context}
118
+
119
+ Current Question:
120
  {question}
121
+
122
+ Please provide a response that takes into account both the current context and the previous conversation history. If you refer to information from the chat history, make it clear where that information came from.
123
+
124
  Answer:
125
  """
126
 
127
  prompt = ChatPromptTemplate.from_template(template)
128
 
129
+ # Create the RAG chain with chat history
130
+ def create_rag_chain(chat_history: str):
131
+ chain = (
132
+ {
133
+ "context": retriever,
134
+ "question": RunnablePassthrough(),
135
+ "chat_history": lambda x: chat_history
136
+ }
137
+ | prompt
138
+ | llm
139
+ | StrOutputParser()
140
+ )
141
+ return chain
142
+
143
+ # Initialize chat history
144
+ chat_history = ChatHistory()
145
 
146
  # Gradio Function
147
+ def ask_question_gradio(question, history: gr.Chatbot) -> Tuple[str, gr.Chatbot]:
148
  try:
149
+ # Add user question to chat history
150
+ chat_history.add_message("User", question)
151
+
152
+ # Get formatted history
153
+ formatted_history = chat_history.get_formatted_history()
154
+
155
+ # Create chain with current chat history
156
+ rag_chain = create_rag_chain(formatted_history)
157
+
158
+ # Generate response
159
  response = ""
160
  for chunk in rag_chain.stream(question):
161
  response += chunk
162
+
163
+ # Add assistant response to chat history
164
+ chat_history.add_message("Assistant", response)
165
+
166
+ # Update Gradio chat history
167
+ history.append((question, response))
168
+
169
+ return "", history
170
  except Exception as e:
171
  logger.error(f"Error during question processing: {e}")
172
+ return "", history + [("Error", "An error occurred. Please try again later.")]
173
+
174
+ def clear_chat():
175
+ chat_history.clear()
176
+ return None
177
 
178
  # Gradio Interface
179
+ with gr.Blocks() as iface:
180
+ gr.Markdown("# Mawared HR Assistant")
181
+ gr.Markdown("Ask questions about the Mawared HR system, and this assistant will provide answers based on the available context and conversation history.")
182
+
183
+ chatbot = gr.Chatbot(
184
+ height=400,
185
+ show_label=False,
186
+ )
187
+
188
+ with gr.Row():
189
+ question_input = gr.Textbox(
190
+ label="Ask a question:",
191
+ placeholder="Type your question here...",
192
+ scale=9
193
+ )
194
+ clear_button = gr.Button("Clear Chat", scale=1)
195
+
196
+ question_input.submit(
197
+ ask_question_gradio,
198
+ inputs=[question_input, chatbot],
199
+ outputs=[question_input, chatbot]
200
+ )
201
+
202
+ clear_button.click(
203
+ lambda: (None, None),
204
+ outputs=[chatbot, question_input],
205
+ _js="() => { window.location.reload(); }"
206
+ )
207
 
208
  # Launch the Gradio App
209
  if __name__ == "__main__":