Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,147 +1,147 @@
|
|
| 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 UnstructuredCSVLoader
|
| 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 = UnstructuredCSVLoader(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:\Users\Admin\Documents\CodeProjects_KD\RAG_ChatBot\people-1000.csv"
|
| 77 |
-
|
| 78 |
-
# ]
|
| 79 |
-
file_path = [
|
| 80 |
-
r"people-1000.csv"
|
| 81 |
-
|
| 82 |
-
]
|
| 83 |
-
#user_query = input(">>")
|
| 84 |
-
chain = create_chat_chain(file_path, openai_model)
|
| 85 |
-
|
| 86 |
-
queue = SimpleQueue()
|
| 87 |
-
LLM_MODEL = "gpt-4o"
|
| 88 |
-
llm = ChatOpenAI(
|
| 89 |
-
openai_api_key=os.environ['OPENAI_API_KEY'],
|
| 90 |
-
model=LLM_MODEL,
|
| 91 |
-
temperature=0.5
|
| 92 |
-
)
|
| 93 |
-
|
| 94 |
-
template = "You are an agent responsible for summarizing, and giving accurate responses regarding the High Jump Warehouse System Guide. '{question}' "
|
| 95 |
-
prompt = PromptTemplate.from_template(template)
|
| 96 |
-
memory = create_mem()
|
| 97 |
-
|
| 98 |
-
# Inspect the output of memory.load_memory_variables
|
| 99 |
-
#print(memory.load_memory_variables("inputs"))
|
| 100 |
-
|
| 101 |
-
def safe_itemgetter(key):
|
| 102 |
-
def getter(d):
|
| 103 |
-
if key not in d:
|
| 104 |
-
raise KeyError(f"Key '{key}' not found in the dictionary. Available keys: {list(d.keys())}")
|
| 105 |
-
return d[key]
|
| 106 |
-
return getter
|
| 107 |
-
|
| 108 |
-
conversation_chain = (
|
| 109 |
-
RunnablePassthrough.assign(
|
| 110 |
-
history=RunnableLambda(memory.load_memory_variables) | safe_itemgetter("chat_history")
|
| 111 |
-
)
|
| 112 |
-
| prompt
|
| 113 |
-
| llm
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
global_cb = None
|
| 117 |
-
with gr.Blocks() as demo:
|
| 118 |
-
with gr.Row():
|
| 119 |
-
gr.Markdown("<h1 style='text-align: center; width: 100%;'>RAG with Memory (Warehouse Assistant)</h1>")
|
| 120 |
-
with gr.Row():
|
| 121 |
-
with gr.Column(scale=1):
|
| 122 |
-
gr.Markdown("**Here's how to use this demo:**")
|
| 123 |
-
gr.Markdown("""This a conversational agent responsible for summarizing, and giving key highlights about the High Jump Warehouse System Guide .\n
|
| 124 |
-
|
| 125 |
-
Feel free to experiment with your own different queries and usage or accesibility requests!
|
| 126 |
-
""")
|
| 127 |
-
with gr.Column(scale=3):
|
| 128 |
-
ex = ["What is the job title for Lindsey Rice?", "What is the Job Title for Joshua Carey?", "What is the user id for Dakota Gomez?"]
|
| 129 |
-
chatbot = gr.Chatbot()
|
| 130 |
-
msg = gr.Textbox()
|
| 131 |
-
gr.Examples(ex, msg)
|
| 132 |
-
clear = gr.Button("Clear Chat History ")
|
| 133 |
-
#but = gr.Button(value="Get Callback Data ")
|
| 134 |
-
|
| 135 |
-
def process_input(user_message, history):
|
| 136 |
-
inputs = {"question": user_message}
|
| 137 |
-
outputs = chain(inputs)
|
| 138 |
-
print(outputs) # Debugging: Print the structure of the outputs
|
| 139 |
-
history.append([user_message, outputs['answer']]) # Use the correct key
|
| 140 |
-
return "", history
|
| 141 |
-
|
| 142 |
-
msg.submit(process_input, [msg, chatbot], [msg, chatbot])
|
| 143 |
-
|
| 144 |
-
clear.click(lambda: chain.memory.clear(), None, chatbot)
|
| 145 |
-
|
| 146 |
-
demo.queue()
|
| 147 |
demo.launch()
|
|
|
|
| 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 UnstructuredCSVLoader
|
| 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 = UnstructuredCSVLoader(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:\Users\Admin\Documents\CodeProjects_KD\RAG_ChatBot\people-1000.csv"
|
| 77 |
+
|
| 78 |
+
# ]
|
| 79 |
+
file_path = [
|
| 80 |
+
r"downloads/people-1000.csv"
|
| 81 |
+
|
| 82 |
+
]
|
| 83 |
+
#user_query = input(">>")
|
| 84 |
+
chain = create_chat_chain(file_path, openai_model)
|
| 85 |
+
|
| 86 |
+
queue = SimpleQueue()
|
| 87 |
+
LLM_MODEL = "gpt-4o"
|
| 88 |
+
llm = ChatOpenAI(
|
| 89 |
+
openai_api_key=os.environ['OPENAI_API_KEY'],
|
| 90 |
+
model=LLM_MODEL,
|
| 91 |
+
temperature=0.5
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
template = "You are an agent responsible for summarizing, and giving accurate responses regarding the High Jump Warehouse System Guide. '{question}' "
|
| 95 |
+
prompt = PromptTemplate.from_template(template)
|
| 96 |
+
memory = create_mem()
|
| 97 |
+
|
| 98 |
+
# Inspect the output of memory.load_memory_variables
|
| 99 |
+
#print(memory.load_memory_variables("inputs"))
|
| 100 |
+
|
| 101 |
+
def safe_itemgetter(key):
|
| 102 |
+
def getter(d):
|
| 103 |
+
if key not in d:
|
| 104 |
+
raise KeyError(f"Key '{key}' not found in the dictionary. Available keys: {list(d.keys())}")
|
| 105 |
+
return d[key]
|
| 106 |
+
return getter
|
| 107 |
+
|
| 108 |
+
conversation_chain = (
|
| 109 |
+
RunnablePassthrough.assign(
|
| 110 |
+
history=RunnableLambda(memory.load_memory_variables) | safe_itemgetter("chat_history")
|
| 111 |
+
)
|
| 112 |
+
| prompt
|
| 113 |
+
| llm
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
global_cb = None
|
| 117 |
+
with gr.Blocks() as demo:
|
| 118 |
+
with gr.Row():
|
| 119 |
+
gr.Markdown("<h1 style='text-align: center; width: 100%;'>RAG with Memory (Warehouse Assistant)</h1>")
|
| 120 |
+
with gr.Row():
|
| 121 |
+
with gr.Column(scale=1):
|
| 122 |
+
gr.Markdown("**Here's how to use this demo:**")
|
| 123 |
+
gr.Markdown("""This a conversational agent responsible for summarizing, and giving key highlights about the High Jump Warehouse System Guide .\n
|
| 124 |
+
|
| 125 |
+
Feel free to experiment with your own different queries and usage or accesibility requests!
|
| 126 |
+
""")
|
| 127 |
+
with gr.Column(scale=3):
|
| 128 |
+
ex = ["What is the job title for Lindsey Rice?", "What is the Job Title for Joshua Carey?", "What is the user id for Dakota Gomez?"]
|
| 129 |
+
chatbot = gr.Chatbot()
|
| 130 |
+
msg = gr.Textbox()
|
| 131 |
+
gr.Examples(ex, msg)
|
| 132 |
+
clear = gr.Button("Clear Chat History ")
|
| 133 |
+
#but = gr.Button(value="Get Callback Data ")
|
| 134 |
+
|
| 135 |
+
def process_input(user_message, history):
|
| 136 |
+
inputs = {"question": user_message}
|
| 137 |
+
outputs = chain(inputs)
|
| 138 |
+
print(outputs) # Debugging: Print the structure of the outputs
|
| 139 |
+
history.append([user_message, outputs['answer']]) # Use the correct key
|
| 140 |
+
return "", history
|
| 141 |
+
|
| 142 |
+
msg.submit(process_input, [msg, chatbot], [msg, chatbot])
|
| 143 |
+
|
| 144 |
+
clear.click(lambda: chain.memory.clear(), None, chatbot)
|
| 145 |
+
|
| 146 |
+
demo.queue()
|
| 147 |
demo.launch()
|