Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,111 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
6 |
-
"""
|
7 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
|
|
|
|
20 |
for val in history:
|
21 |
if val[0]:
|
22 |
messages.append({"role": "user", "content": val[0]})
|
23 |
if val[1]:
|
24 |
messages.append({"role": "assistant", "content": val[1]})
|
|
|
25 |
|
26 |
-
|
27 |
-
|
28 |
response = ""
|
29 |
-
|
30 |
-
|
31 |
-
messages,
|
32 |
max_tokens=max_tokens,
|
33 |
stream=True,
|
34 |
temperature=temperature,
|
35 |
top_p=top_p,
|
36 |
):
|
37 |
-
token =
|
38 |
-
|
39 |
response += token
|
40 |
yield response
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
-
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
demo = gr.ChatInterface(
|
47 |
-
|
48 |
additional_inputs=[
|
49 |
-
gr.
|
50 |
-
gr.
|
51 |
-
gr.Slider(
|
52 |
-
gr.Slider(
|
53 |
-
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
],
|
|
|
|
|
|
|
60 |
)
|
61 |
|
62 |
-
|
63 |
if __name__ == "__main__":
|
64 |
demo.launch()
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
from huggingface_hub import InferenceClient
|
4 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
+
from langchain.vectorstores import Chroma
|
6 |
+
from langchain.embeddings import HuggingFaceBgeEmbeddings
|
7 |
+
from langchain.document_loaders import PyPDFLoader, UnstructuredFileLoader, CSVLoader
|
8 |
+
from langchain.chains import RetrievalQA
|
9 |
+
from langchain.prompts import PromptTemplate
|
10 |
|
11 |
+
# Initialize the Zephyr client
|
|
|
|
|
12 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
13 |
|
14 |
+
# Function to load documents based on file type
|
15 |
+
def load_documents(file_path):
|
16 |
+
if file_path.endswith(".pdf"):
|
17 |
+
loader = PyPDFLoader(file_path)
|
18 |
+
elif file_path.endswith(".txt") or file_path.endswith(".docx"):
|
19 |
+
loader = UnstructuredFileLoader(file_path)
|
20 |
+
elif file_path.endswith(".csv"):
|
21 |
+
loader = CSVLoader(file_path)
|
22 |
+
else:
|
23 |
+
raise ValueError("Unsupported file format")
|
24 |
+
|
25 |
+
documents = loader.load()
|
26 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
27 |
+
return text_splitter.split_documents(documents)
|
28 |
|
29 |
+
# Function to create or update vector store
|
30 |
+
def create_vector_store(documents, persist_dir="vector_db"):
|
31 |
+
embeddings = HuggingFaceBgeEmbeddings(
|
32 |
+
model_name="BAAI/bge-large-en",
|
33 |
+
model_kwargs={"device": "cpu"}
|
34 |
+
)
|
35 |
+
vector_store = Chroma.from_documents(documents, embeddings, persist_directory=persist_dir)
|
36 |
+
return vector_store
|
37 |
+
|
38 |
+
# Function to handle user queries
|
39 |
+
def respond(message, history, system_message, max_tokens, temperature, top_p, retriever):
|
40 |
+
# Retrieve relevant context
|
41 |
+
relevant_docs = retriever.get_relevant_documents(message)
|
42 |
+
context = "\n".join([doc.page_content for doc in relevant_docs])
|
43 |
+
|
44 |
+
# Format the prompt
|
45 |
+
prompt_template = """
|
46 |
+
Use the following context to answer the user's question.
|
47 |
+
If you don't know the answer, say "I don't know."
|
48 |
+
|
49 |
+
Context:
|
50 |
+
{context}
|
51 |
+
|
52 |
+
Question:
|
53 |
+
{question}
|
54 |
+
|
55 |
+
Answer:
|
56 |
+
"""
|
57 |
+
formatted_prompt = prompt_template.format(context=context, question=message)
|
58 |
|
59 |
+
# Build conversational history
|
60 |
+
messages = [{"role": "system", "content": system_message}]
|
61 |
for val in history:
|
62 |
if val[0]:
|
63 |
messages.append({"role": "user", "content": val[0]})
|
64 |
if val[1]:
|
65 |
messages.append({"role": "assistant", "content": val[1]})
|
66 |
+
messages.append({"role": "user", "content": formatted_prompt})
|
67 |
|
68 |
+
# Stream response from Zephyr
|
|
|
69 |
response = ""
|
70 |
+
for msg in client.chat_completion(
|
71 |
+
messages=messages,
|
|
|
72 |
max_tokens=max_tokens,
|
73 |
stream=True,
|
74 |
temperature=temperature,
|
75 |
top_p=top_p,
|
76 |
):
|
77 |
+
token = msg.choices[0].delta.content
|
|
|
78 |
response += token
|
79 |
yield response
|
80 |
|
81 |
+
# Initialize the vector store
|
82 |
+
persist_dir = "vector_db"
|
83 |
+
retriever = None # Will be initialized dynamically
|
84 |
+
|
85 |
+
def handle_query(message, history, system_message, max_tokens, temperature, top_p, file=None):
|
86 |
+
global retriever
|
87 |
+
if file: # Process uploaded file
|
88 |
+
documents = load_documents(file.name)
|
89 |
+
vector_store = create_vector_store(documents, persist_dir)
|
90 |
+
retriever = vector_store.as_retriever()
|
91 |
+
if not retriever:
|
92 |
+
return "No documents have been uploaded yet. Please upload a file to provide context."
|
93 |
+
return respond(message, history, system_message, max_tokens, temperature, top_p, retriever)
|
94 |
|
95 |
+
# Gradio app setup
|
|
|
|
|
96 |
demo = gr.ChatInterface(
|
97 |
+
fn=handle_query,
|
98 |
additional_inputs=[
|
99 |
+
gr.File(label="Upload File", type="file"),
|
100 |
+
gr.Textbox(value="You are a knowledgeable assistant.", label="System Message"),
|
101 |
+
gr.Slider(1, 2048, step=1, value=512, label="Max Tokens"),
|
102 |
+
gr.Slider(0.1, 4.0, step=0.1, value=0.7, label="Temperature"),
|
103 |
+
gr.Slider(0.1, 1.0, step=0.05, value=0.95, label="Top-p"),
|
|
|
|
|
|
|
|
|
|
|
104 |
],
|
105 |
+
outputs="text",
|
106 |
+
title="RAG with Zephyr-7B",
|
107 |
+
description="A Retrieval-Augmented Generation chatbot powered by Zephyr-7B and Chroma vector database.",
|
108 |
)
|
109 |
|
|
|
110 |
if __name__ == "__main__":
|
111 |
demo.launch()
|