File size: 8,929 Bytes
4e3cd79
5a6715f
 
8edd409
 
 
 
 
5a6715f
 
8359d12
72ccc50
8359d12
0217602
 
c2c5723
 
 
 
0217602
 
 
cd66018
 
 
4c81ad7
34b0a17
7eb2b48
bbc9fae
7eb2b48
936fd23
9950104
8359d12
8edd409
4c81ad7
 
 
 
 
 
 
 
 
 
 
 
 
cd66018
4c81ad7
 
 
736da61
bbc9fae
4c81ad7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3206d9d
547606d
3206d9d
4c81ad7
 
 
 
 
52a3d0e
4c81ad7
 
 
 
 
 
03d6372
4c81ad7
 
 
 
 
 
 
 
 
 
 
 
 
52a3d0e
4c81ad7
736da61
4c81ad7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52a3d0e
 
4c81ad7
 
52a3d0e
 
 
 
 
4c81ad7
91a7826
 
b89373e
 
 
 
 
 
 
4c81ad7
 
 
 
 
14bd49d
 
 
 
 
 
 
 
 
 
 
92b6108
 
 
 
 
 
 
 
a106ce8
92b6108
936fd23
5a6715f
9367f10
 
 
 
 
14bd49d
 
 
64f4771
a76f205
 
 
 
64f4771
5a6715f
 
 
 
632dfa0
64f4771
5a6715f
64f4771
92b6108
 
 
 
75f78f2
64f4771
5a6715f
64f4771
5a6715f
64f4771
4c81ad7
9c4781b
 
 
 
4c81ad7
 
595159e
a61471c
595159e
a61471c
595159e
 
 
 
a61471c
595159e
 
 
a61471c
 
 
595159e
a61471c
7074c5b
595159e
4c81ad7
 
 
 
 
9c4781b
 
7fa65bd
4c81ad7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c311d4
4c81ad7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a76f205
4c81ad7
a76f205
5bdbb4a
a76f205
4c81ad7
 
 
 
c05cd1b
632dfa0
4c81ad7
 
cd66018
 
 
 
 
c05cd1b
cd66018
 
 
 
 
 
 
 
 
 
6e94dfd
 
cd66018
8359d12
0217602
51a7d9e
0217602
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import spaces
import subprocess 

subprocess.run(
    'pip install flash-attn --no-build-isolation',
    env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"},
    shell=True
)


import os
import torch
from dotenv import load_dotenv
from langchain_community.vectorstores import Qdrant
from langchain_huggingface import HuggingFaceEmbeddings
from langchain.prompts import ChatPromptTemplate
from langchain.schema.runnable import RunnablePassthrough
from langchain.schema.output_parser import StrOutputParser
from qdrant_client import QdrantClient, models
from langchain_openai import ChatOpenAI
import gradio as gr
import logging
from typing import List, Tuple
from dataclasses import dataclass
from datetime import datetime
from transformers import AutoTokenizer, AutoModelForCausalLM ,pipeline
from langchain_huggingface.llms import HuggingFacePipeline
import re
from langchain_huggingface.llms import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline,BitsAndBytesConfig,TextIteratorStreamer
from langchain_cerebras import ChatCerebras



# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@dataclass
class Message:
    role: str
    content: str
    timestamp: str

class ChatHistory:
    def __init__(self):
        self.messages: List[Message] = []
    
    def add_message(self, role: str, content: str):
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.messages.append(Message(role=role, content=content, timestamp=timestamp))
    
    def get_formatted_history(self, max_messages: int = 10) -> str:
        """Returns the most recent conversation history formatted as a string"""
        recent_messages = self.messages[-max_messages:] if len(self.messages) > max_messages else self.messages
        formatted_history = "\n".join([
            f"{msg.role}: {msg.content}" for msg in recent_messages
        ])
        return formatted_history
    
    def clear(self):
        self.messages = []

# Load environment variables
load_dotenv()

# HuggingFace API Token
HF_TOKEN = os.getenv("HF_TOKEN")
C_apikey = os.getenv("C_apikey")
OPENAPI_KEY = os.getenv("OPENAPI_KEY")

if not HF_TOKEN:
    logger.error("HF_TOKEN is not set in the environment variables.")
    exit(1)

# HuggingFace Embeddings
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

# Qdrant Client Setup
try:
    client = QdrantClient(
        url=os.getenv("QDRANT_URL"),
        api_key=os.getenv("QDRANT_API_KEY"),
        prefer_grpc=False
    )
except Exception as e:
    logger.error("Failed to connect to Qdrant. Ensure QDRANT_URL and QDRANT_API_KEY are correctly set.")
    exit(1)

# Define collection name
collection_name = "mawared"

# Try to create collection
try:
    client.create_collection(
        collection_name=collection_name,
        vectors_config=models.VectorParams(
            size=384,  # GTE-large embedding size
            distance=models.Distance.COSINE
        )
    )
    logger.info(f"Created new collection: {collection_name}")
except Exception as e:
    if "already exists" in str(e):
        logger.info(f"Collection {collection_name} already exists, continuing...")
    else:
        logger.error(f"Error creating collection: {e}")
        exit(1)

# Create Qdrant vector store
db = Qdrant(
    client=client,
    collection_name=collection_name,
    embeddings=embeddings,
)

# Create retriever
retriever = db.as_retriever(
    search_type="similarity",
    search_kwargs={"k": 5}
)

# retriever = db.as_retriever(
#     search_type="mmr",
#     search_kwargs={"k": 5, "fetch_k": 10, "lambda_mult": 0.5}
# )




# retriever = db.as_retriever(
#     search_type="similarity_score_threshold",
#     search_kwargs={"k": 5, "score_threshold": 0.8}
# )



# Load model directly



# Set up the LLM
# llm = ChatOpenAI(
#     base_url="https://api-inference.huggingface.co/v1/",
#     temperature=0,
#     api_key=HF_TOKEN,
#     model="mistralai/Mistral-Nemo-Instruct-2407",
#     max_tokens=None,
#     timeout=None
    
# )


#llm = ChatOpenAI(
   # base_url="https://openrouter.ai/api/v1",
    #temperature=0.01,
   # api_key=OPENAPI_KEY,
    #model="google/gemini-2.0-flash-exp:free",
    #max_tokens=None,
    #timeout=None,
  #  max_retries=3,

#)


# llm = ChatCerebras(
#     model="llama-3.3-70b",
#     api_key=C_apikey,
#     stream=True
# )



quantization_config = BitsAndBytesConfig(
         load_in_4bit=True,
         bnb_4bit_compute_dtype=torch.bfloat16,
         bnb_4bit_quant_type="nf4",
         bnb_4bit_use_double_quant=True
)




model_id = "meta-llama/Llama-3.2-3B-Instruct" 
tokenizer = AutoTokenizer.from_pretrained(model_id)

model = AutoModelForCausalLM.from_pretrained(
         model_id,
         torch_dtype=torch.float16,
         device_map="cuda",
         attn_implementation="flash_attention_2",
         #quantization_config=quantization_config
)

pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=8192 )

llm = HuggingFacePipeline(pipeline=pipe)





# Create prompt template with chat history
template = """
You are an expert assistant specializing in the Mawared HR System. Your role is to provide precise and contextually relevant answers based on the retrieved context and chat history.

Key Responsibilities:

Use the given chat history and retrieved context to craft accurate and detailed responses.
If necessary, ask specific and targeted clarifying questions to gather more information.
Present step-by-step instructions in a clear, numbered format when applicable.
Rules for Responses:

Strictly use the information from the provided context and chat history. Avoid making up or fabricating any details.
Do not reference the retrieval process, sources, pages, or documents in your responses.
Maintain a conversational flow by asking relevant follow-up questions to engage the user and enhance the interaction.
Inputs for Your Response:

Previous Conversation: {chat_history}
Retrieved Context: {context}
Current Question: {question}
Answer:{{answer}}
Your answers must be expressive, detailed, and fully address the user’s needs without deviating from the provided information.
"""

prompt = ChatPromptTemplate.from_template(template)

# Create the RAG chain with chat history



def create_rag_chain(chat_history: str):
    chain = (
        {
            "context": retriever,
            "question": RunnablePassthrough(),
            "chat_history": lambda x: chat_history
        }
        | prompt
        | llm
        | StrOutputParser()
    )
    return chain

# Initialize chat history
chat_history = ChatHistory()

# Gradio Function
@spaces.GPU()
def ask_question_gradio(question, history):
    try:
        # Add user question to chat history
        chat_history.add_message("user", question)
        
        # Get formatted history
        formatted_history = chat_history.get_formatted_history()
        
        # Create chain with current chat history
        rag_chain = create_rag_chain(formatted_history)
        
        # Generate response
        response = ""
        for chunk in rag_chain.stream(question):
            response += chunk
        
        # Add assistant response to chat history
        chat_history.add_message("assistant", response)
        
        # Update Gradio chat history
        history.append({"role": "user", "content": question})
        history.append({"role": "assistant", "content": response})
        
        return "", history
    except Exception as e:
        logger.error(f"Error during question processing: {e}")
        return "", history + [{"role": "assistant", "content": "An error occurred. Please try again later."}]

def clear_chat():
    chat_history.clear()
    return [], ""

# Gradio Interface
with gr.Blocks(theme='lone17/kotaemon') as iface:
    gr.Image("Image.jpg" , width=1200 , height=300 ,show_label=False, show_download_button=False)
    gr.Markdown("# Mawared HR Assistant 2.5.1")
    gr.Markdown('### Instructions')
    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 😀")

           
    
    chatbot = gr.Chatbot(
        height=750,
        show_label=False,
        type="messages"  # Using the new messages format
    )
    
    with gr.Row():
        question_input = gr.Textbox(
            label="Ask a question:",
            placeholder="Type your question here...",
            scale=30
        )
        clear_button = gr.Button("Clear Chat", scale=1)
    
    question_input.submit(
        ask_question_gradio,
        inputs=[question_input, chatbot],
        outputs=[question_input, chatbot]
    )
    
    clear_button.click(
        clear_chat,
        outputs=[chatbot, question_input]
    )

# Launch the Gradio App
if __name__ == "__main__":
    iface.launch()