reubk commited on
Commit
3f79ca5
·
verified ·
1 Parent(s): 10969a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -49
app.py CHANGED
@@ -1,64 +1,94 @@
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
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
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
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
27
 
28
- response = ""
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
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
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
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 gradio as gr
2
+ import os
3
+ import time
4
+ from huggingface_hub import login
5
+ from langchain_community.document_loaders import TextLoader
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ from langchain_community.vectorstores import SKLearnVectorStore
8
+ from langchain_huggingface import ChatHuggingFace, HuggingFacePipeline, HuggingFaceEmbeddings
9
+ from langchain.prompts import PromptTemplate
10
+ from langchain_core.output_parsers import StrOutputParser
11
 
12
+ HF_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
13
+ login(token=HF_TOKEN)
 
 
14
 
15
+ data=TextLoader("erikdata.txt").load()
16
+ text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(chunk_size=125, chunk_overlap=5)
17
+ data_split = text_splitter.split_documents(data)
18
 
19
+ model_name = "BAAI/llm-embedder"
20
+ model_kwargs = {'device': 'cpu'}
21
+ encode_kwargs = {'normalize_embeddings': False}
22
+ hf = HuggingFaceEmbeddings(
23
+ model_name=model_name,
24
+ model_kwargs=model_kwargs,
25
+ encode_kwargs=encode_kwargs
26
+ )
27
+ vectorstore = SKLearnVectorStore.from_documents(
28
+ documents=data_split,
29
+ embedding=hf,
30
+ )
31
+ retriever = vectorstore.as_retriever(k=4)
32
 
33
+ prompt = PromptTemplate(
34
+ template="""You are an AI replica of Professor Erik Birgersson. Professor Erik is the director of the Engineering Science Program in the National University of Singapore.
35
+ Your students are likely to be Engineering Science undergraduates who are lost on the syllabus on the following courses:
36
+ 1. Numerical Methods and Statistics (ESP2107) which covers concepts such as interpolation, root finding, numerical differentiation and integration and linear systems, using MATLAB code.
37
+ 2. Principles of Continua (ESP2106) which covers concepts such as computational fluid dynamics, heat transfer, Cauchy's equation, vectors and tensors.
38
+ Use the following documents to answer the question and try to follow the way he speaks.
39
+ If you don't know the answer, just say that you don't know.
40
+ Use three sentences maximum and keep the answer concise. You MUST only output one question and one answer.
41
+ Documents: {documents}
42
+ Question: {user_message}
43
+ Answer:
44
+ """,
45
+ input_variables=["user_message", "documents"],
46
+ )
47
 
48
+ llm = HuggingFacePipeline.from_model_id(
49
+ model_id="meta-llama/Llama-3.2-1B",
50
+ task="text-generation",
51
+ pipeline_kwargs=dict(
52
+ max_new_tokens=64,
53
+ )
54
+ )
55
 
56
+ rag_chain = prompt | llm |StrOutputParser()
57
 
58
+ class RAGApplication:
59
+ def __init__(self, retriever, rag_chain):
60
+ self.retriever = retriever
61
+ self.rag_chain = rag_chain
62
+ def run(self, user_message):
63
+ documents = self.retriever.invoke(user_message)
64
+ doc_texts = "\\n".join([doc.page_content for doc in documents])
65
+ answer = self.rag_chain.invoke({"user_message": user_message, "documents": doc_texts})
66
+ answer = answer.split('Answer:\n')[1].split('Question:')[0] #splitting the answer output
67
+ return answer
68
 
69
+ rag_application = RAGApplication(retriever, rag_chain)
 
70
 
71
 
72
+ with gr.Blocks() as demo:
73
+ chatbot = gr.Chatbot(type="messages")
74
+ msg = gr.Textbox()
75
+ clear = gr.Button("Clear")
76
+
77
+ def user(user_message, history: list):
78
+ return history + [{"role": "user", "content": user_message}]
79
+
80
+ def bot(user_message, history: list):
81
+ bot_message = rag_application.run(user_message)
82
+ history.append({"role": "assistant", "content": ""})
83
+ for character in bot_message:
84
+ history[-1]['content'] += character
85
+ time.sleep(0.005)
86
+ yield history
 
 
 
87
 
88
+ msg.submit(user, [msg, chatbot], chatbot, queue=False).then(
89
+ bot, [msg, chatbot], chatbot
90
+ )
91
+ clear.click(lambda: None, None, chatbot, queue=False)
92
 
93
  if __name__ == "__main__":
94
  demo.launch()