Daemontatox
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,50 +1,61 @@
|
|
1 |
-
from langchain_community.vectorstores import Qdrant
|
2 |
-
from langchain_huggingface import HuggingFaceEmbeddings
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
|
|
|
|
5 |
from langchain.prompts import ChatPromptTemplate
|
6 |
from langchain.schema.runnable import RunnablePassthrough
|
7 |
from langchain.schema.output_parser import StrOutputParser
|
8 |
from qdrant_client import QdrantClient, models
|
9 |
-
from
|
10 |
-
|
11 |
-
|
12 |
-
from langchain_openai import ChatOpenAI ,OpenAI
|
13 |
|
|
|
|
|
|
|
14 |
|
15 |
# Load environment variables
|
16 |
load_dotenv()
|
17 |
|
18 |
-
|
|
|
|
|
|
|
|
|
19 |
|
20 |
# HuggingFace Embeddings
|
21 |
embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-large-en-v1.5")
|
22 |
|
23 |
# Qdrant Client Setup
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
29 |
|
|
|
30 |
collection_name = "mawared"
|
31 |
|
32 |
-
# Try to create collection
|
33 |
try:
|
34 |
client.create_collection(
|
35 |
collection_name=collection_name,
|
36 |
vectors_config=models.VectorParams(
|
37 |
size=768, # GTE-large embedding size
|
38 |
distance=models.Distance.COSINE
|
39 |
-
)
|
40 |
-
|
41 |
)
|
42 |
-
|
43 |
except Exception as e:
|
44 |
if "already exists" in str(e):
|
45 |
-
|
46 |
else:
|
47 |
-
|
|
|
48 |
|
49 |
# Create Qdrant vector store
|
50 |
db = Qdrant(
|
@@ -59,8 +70,13 @@ retriever = db.as_retriever(
|
|
59 |
search_kwargs={"k": 5}
|
60 |
)
|
61 |
|
62 |
-
|
63 |
-
llm = ChatOpenAI(
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
# Create prompt template
|
66 |
template = """
|
@@ -91,7 +107,7 @@ Answer
|
|
91 |
|
92 |
prompt = ChatPromptTemplate.from_template(template)
|
93 |
|
94 |
-
# Create the RAG chain
|
95 |
rag_chain = (
|
96 |
{"context": retriever, "question": RunnablePassthrough()}
|
97 |
| prompt
|
@@ -99,19 +115,26 @@ rag_chain = (
|
|
99 |
| StrOutputParser()
|
100 |
)
|
101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
-
#
|
104 |
-
def ask_question(question):
|
105 |
-
print("Answer:\t", end=" ", flush=True)
|
106 |
-
for chunk in rag_chain.stream(question):
|
107 |
-
print(chunk, end="", flush=True)
|
108 |
-
print("\n")
|
109 |
-
|
110 |
-
# Example usage
|
111 |
if __name__ == "__main__":
|
112 |
-
|
113 |
-
user_question = input("\n \n \n Ask a question (or type 'quit' to exit): ")
|
114 |
-
if user_question.lower() == 'quit':
|
115 |
-
break
|
116 |
-
answer = ask_question(user_question)
|
117 |
-
# print("\nFull answer received.\n")
|
|
|
|
|
|
|
1 |
import os
|
2 |
from dotenv import load_dotenv
|
3 |
+
from langchain_community.vectorstores import Qdrant
|
4 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
5 |
from langchain.prompts import ChatPromptTemplate
|
6 |
from langchain.schema.runnable import RunnablePassthrough
|
7 |
from langchain.schema.output_parser import StrOutputParser
|
8 |
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 |
|
20 |
+
# HuggingFace API Token
|
21 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
22 |
+
if not HF_TOKEN:
|
23 |
+
logger.error("HF_TOKEN is not set in the environment variables.")
|
24 |
+
exit(1)
|
25 |
|
26 |
# HuggingFace Embeddings
|
27 |
embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-large-en-v1.5")
|
28 |
|
29 |
# Qdrant Client Setup
|
30 |
+
try:
|
31 |
+
client = QdrantClient(
|
32 |
+
url=os.getenv("QDRANT_URL"),
|
33 |
+
api_key=os.getenv("QDRANT_API_KEY"),
|
34 |
+
prefer_grpc=True
|
35 |
+
)
|
36 |
+
except Exception as e:
|
37 |
+
logger.error("Failed to connect to Qdrant. Ensure QDRANT_URL and QDRANT_API_KEY are correctly set.")
|
38 |
+
exit(1)
|
39 |
|
40 |
+
# Define collection name
|
41 |
collection_name = "mawared"
|
42 |
|
43 |
+
# Try to create collection
|
44 |
try:
|
45 |
client.create_collection(
|
46 |
collection_name=collection_name,
|
47 |
vectors_config=models.VectorParams(
|
48 |
size=768, # GTE-large embedding size
|
49 |
distance=models.Distance.COSINE
|
50 |
+
)
|
|
|
51 |
)
|
52 |
+
logger.info(f"Created new collection: {collection_name}")
|
53 |
except Exception as e:
|
54 |
if "already exists" in str(e):
|
55 |
+
logger.info(f"Collection {collection_name} already exists, continuing...")
|
56 |
else:
|
57 |
+
logger.error(f"Error creating collection: {e}")
|
58 |
+
exit(1)
|
59 |
|
60 |
# Create Qdrant vector store
|
61 |
db = Qdrant(
|
|
|
70 |
search_kwargs={"k": 5}
|
71 |
)
|
72 |
|
73 |
+
# Set up the LLM
|
74 |
+
llm = ChatOpenAI(
|
75 |
+
base_url="https://api-inference.huggingface.co/v1/",
|
76 |
+
temperature=0,
|
77 |
+
api_key=HF_TOKEN,
|
78 |
+
model="meta-llama/Llama-3.3-70B-Instruct"
|
79 |
+
)
|
80 |
|
81 |
# Create prompt template
|
82 |
template = """
|
|
|
107 |
|
108 |
prompt = ChatPromptTemplate.from_template(template)
|
109 |
|
110 |
+
# Create the RAG chain
|
111 |
rag_chain = (
|
112 |
{"context": retriever, "question": RunnablePassthrough()}
|
113 |
| prompt
|
|
|
115 |
| StrOutputParser()
|
116 |
)
|
117 |
|
118 |
+
# Gradio Function
|
119 |
+
def ask_question_gradio(question):
|
120 |
+
try:
|
121 |
+
response = ""
|
122 |
+
for chunk in rag_chain.stream(question):
|
123 |
+
response += chunk
|
124 |
+
return response
|
125 |
+
except Exception as e:
|
126 |
+
logger.error(f"Error during question processing: {e}")
|
127 |
+
return "An error occurred. Please try again later."
|
128 |
+
|
129 |
+
# Gradio Interface
|
130 |
+
iface = gr.Interface(
|
131 |
+
fn=ask_question_gradio,
|
132 |
+
inputs=gr.Textbox(label="Ask a question about Mawared HR System:"),
|
133 |
+
outputs=gr.Textbox(label="Answer:"),
|
134 |
+
title="Mawared HR Assistant",
|
135 |
+
description="Ask questions about the Mawared HR system, and this assistant will provide answers based on the available context."
|
136 |
+
)
|
137 |
|
138 |
+
# Launch the Gradio App
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
if __name__ == "__main__":
|
140 |
+
iface.launch()
|
|
|
|
|
|
|
|
|
|