kdembla commited on
Commit
aacd66f
·
verified ·
1 Parent(s): 16aabc1

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +8 -13
  2. app.py +143 -0
  3. requirements.txt +11 -0
README.md CHANGED
@@ -1,13 +1,8 @@
1
- ---
2
- title: WarehouseAssistant RAGBOT
3
- emoji: 🚀
4
- colorFrom: green
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 4.37.1
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ title: WarehouseAssistant
2
+ emoji: 📈
3
+ colorFrom: pink
4
+ colorTo: blue
5
+ sdk: gradio
6
+ sdk_version: 4.36.1
7
+ app_file: app.py
8
+ pinned: true
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from langchain_openai import ChatOpenAI
3
+ from langchain.memory import ConversationBufferMemory
4
+ from langchain.chains import ConversationalRetrievalChain
5
+ from langchain_community.document_loaders import UnstructuredPDFLoader
6
+ from langchain_openai import OpenAIEmbeddings
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain_community.vectorstores import DocArrayInMemorySearch
9
+ from operator import itemgetter
10
+ from queue import SimpleQueue
11
+ from langchain_core.runnables import RunnableLambda, RunnablePassthrough
12
+ from langchain.prompts import PromptTemplate
13
+
14
+ import os
15
+ from dotenv import load_dotenv
16
+ load_dotenv()
17
+ API_KEY = os.getenv("OPENAI_API_KEY")
18
+ print("Hi Krish")
19
+
20
+ def setup_qa_chain(file_path, openai_model):
21
+ docs = []
22
+ for filepath in file_path:
23
+ loader = UnstructuredPDFLoader(filepath)
24
+ docs.extend(loader.load())
25
+ return docs
26
+
27
+ def split_docs(docs):
28
+ # Split documents
29
+ text_splitter = RecursiveCharacterTextSplitter(
30
+ chunk_size=500,
31
+ chunk_overlap=100
32
+ )
33
+ return text_splitter.split_documents(docs)
34
+
35
+ def embed(docs, API_KEY):
36
+ # Create embeddings and store in vectordb
37
+ embeddings = OpenAIEmbeddings(openai_api_key=API_KEY)
38
+ vectordb = DocArrayInMemorySearch.from_documents(docs, embeddings)
39
+ return vectordb
40
+
41
+ def create_retriever(vectordb):
42
+ # Define retriever
43
+ retriever = vectordb.as_retriever(
44
+ search_type='mmr'
45
+ )
46
+ return retriever
47
+
48
+ def create_mem():
49
+ # Setup memory for contextual conversation
50
+ memory = ConversationBufferMemory(
51
+ memory_key='chat_history',
52
+ return_messages=True,
53
+ output_key='answer' # Explicitly set the output key to avoid ambiguity
54
+ )
55
+ return memory
56
+
57
+ def create_chat_chain(file_path, openai_model):
58
+ docs = setup_qa_chain(file_path, openai_model)
59
+ split_documents = split_docs(docs)
60
+ embeddings = embed(split_documents, API_KEY=API_KEY)
61
+ retr = create_retriever(embeddings)
62
+ mem = create_mem()
63
+ llm_def = ChatOpenAI(model=openai_model, temperature=0, api_key=API_KEY, max_tokens=1100)
64
+ chain = ConversationalRetrievalChain.from_llm(
65
+ llm=llm_def,
66
+ retriever=retr,
67
+ memory=mem,
68
+ return_source_documents=True,
69
+ verbose=True
70
+ )
71
+ return chain
72
+
73
+ if __name__ == "__main__":
74
+ openai_model = "gpt-4o"
75
+ file_path = [
76
+ r"C:\WarehouseAsst_PoC\data\Advantage Dashboard Functional Description.pdf",
77
+ r"data\user_guide.pdf"
78
+ ]
79
+ user_query = input(">>")
80
+ chain = create_chat_chain(file_path, openai_model)
81
+
82
+ queue = SimpleQueue()
83
+ LLM_MODEL = "gpt-4o"
84
+ llm = ChatOpenAI(
85
+ openai_api_key=os.environ['OPENAI_API_KEY'],
86
+ model=LLM_MODEL,
87
+ temperature=0.5
88
+ )
89
+
90
+ template = "You are an agent responsible for summarizing, and giving accurate responses regarding the High Jump Warehouse System Guide. '{question}' "
91
+ prompt = PromptTemplate.from_template(template)
92
+ memory = create_mem()
93
+
94
+ # Inspect the output of memory.load_memory_variables
95
+ #print(memory.load_memory_variables("inputs"))
96
+
97
+ def safe_itemgetter(key):
98
+ def getter(d):
99
+ if key not in d:
100
+ raise KeyError(f"Key '{key}' not found in the dictionary. Available keys: {list(d.keys())}")
101
+ return d[key]
102
+ return getter
103
+
104
+ conversation_chain = (
105
+ RunnablePassthrough.assign(
106
+ history=RunnableLambda(memory.load_memory_variables) | safe_itemgetter("chat_history")
107
+ )
108
+ | prompt
109
+ | llm
110
+ )
111
+
112
+ global_cb = None
113
+ with gr.Blocks() as demo:
114
+ with gr.Row():
115
+ gr.Markdown("<h1 style='text-align: center; width: 100%;'>RAG with Memory (Warehouse Assistant)</h1>")
116
+ with gr.Row():
117
+ with gr.Column(scale=1):
118
+ gr.Markdown("**Here's how to use this demo:**")
119
+ gr.Markdown("""This a conversational agent responsible for summarizing, and giving key highlights about the High Jump Warehouse System Guide .\n
120
+
121
+ Feel free to experiment with your own different queries and usage or accesibility requests!
122
+ """)
123
+ with gr.Column(scale=3):
124
+ ex = ["Where can I find the Inbound pallets menu?", "How can I navigate the Pallet Question Master?", "Where can I find the A-Frame Items Configurations menu?"]
125
+ chatbot = gr.Chatbot()
126
+ msg = gr.Textbox()
127
+ gr.Examples(ex, msg)
128
+ clear = gr.Button("Clear Chat History ")
129
+ #but = gr.Button(value="Get Callback Data ")
130
+
131
+ def process_input(user_message, history):
132
+ inputs = {"question": user_message}
133
+ outputs = chain(inputs)
134
+ print(outputs) # Debugging: Print the structure of the outputs
135
+ history.append([user_message, outputs['answer']]) # Use the correct key
136
+ return "", history
137
+
138
+ msg.submit(process_input, [msg, chatbot], [msg, chatbot])
139
+
140
+ clear.click(lambda: chain.memory.clear(), None, chatbot)
141
+
142
+ demo.queue()
143
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio==4.36.1
2
+ openai==1.33.0
3
+ langchain==0.2.3
4
+ python-dotenv==1.0.1
5
+ faiss-cpu==1.8.0
6
+ pdfplumber==0.11.0
7
+ unstructured==0.7.12
8
+ promptlayer==1.0.3
9
+ tiktoken==0.7.0
10
+ langchain-openai==0.1.8
11
+ langchain-community==0.2.4