Spaces:
Sleeping
Sleeping
Boris Shapkin
commited on
Commit
·
5018bdb
1
Parent(s):
6225aed
app file
Browse files
app.py
ADDED
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
import pickle
|
4 |
+
from langchain.prompts import ChatPromptTemplate
|
5 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
6 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
7 |
+
from huggingface_llm import HuggingFaceLLM
|
8 |
+
from langchain.retrievers import ParentDocumentRetriever
|
9 |
+
from langchain.storage import InMemoryStore
|
10 |
+
from langchain_chroma import Chroma
|
11 |
+
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate
|
12 |
+
from langchain_core.output_parsers import StrOutputParser
|
13 |
+
from langchain_core.runnables import RunnableLambda
|
14 |
+
from datetime import date
|
15 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
16 |
+
|
17 |
+
# Environment variables
|
18 |
+
# os.environ['LANGCHAIN_TRACING_V2'] = 'true'
|
19 |
+
# os.environ['LANGCHAIN_ENDPOINT'] = 'https://api.smith.langchain.com'
|
20 |
+
# os.environ['LANGCHAIN_API_KEY'] = os.environ.get('LANGCHAIN_API_KEY')
|
21 |
+
|
22 |
+
|
23 |
+
# Load model and tokenizer
|
24 |
+
# @st.cache_resource
|
25 |
+
# def load_model():
|
26 |
+
# model_name = "allenai/OLMo-7B-Instruct"
|
27 |
+
# tokenizer = AutoTokenizer.from_pretrained(model_name)
|
28 |
+
# model = AutoModelForCausalLM.from_pretrained(model_name)
|
29 |
+
# return model, tokenizer
|
30 |
+
|
31 |
+
# model, tokenizer = load_model()
|
32 |
+
def load_from_pickle(filename):
|
33 |
+
with open(filename, "rb") as file:
|
34 |
+
return pickle.load(file)
|
35 |
+
def load_retriever(docstore_path,chroma_path,embeddings,child_splitter,parent_splitter):
|
36 |
+
"""Loads the vector store and document store, initializing the retriever."""
|
37 |
+
db3 = Chroma(collection_name="full_documents", #collection_name shoud be the same as in the first time
|
38 |
+
embedding_function=embeddings,
|
39 |
+
persist_directory=chroma_path
|
40 |
+
)
|
41 |
+
store_dict = load_from_pickle(docstore_path)
|
42 |
+
|
43 |
+
store = InMemoryStore()
|
44 |
+
store.mset(list(store_dict.items()))
|
45 |
+
|
46 |
+
retriever = ParentDocumentRetriever(
|
47 |
+
vectorstore=db3,
|
48 |
+
docstore=store,
|
49 |
+
child_splitter=child_splitter,
|
50 |
+
parent_splitter=parent_splitter,
|
51 |
+
search_kwargs={"k": 5}
|
52 |
+
)
|
53 |
+
return retriever
|
54 |
+
def inspect(state):
|
55 |
+
if "context_sources" not in st.session_state:
|
56 |
+
st.session_state.context_sources = []
|
57 |
+
context = state['normal_context']
|
58 |
+
st.session_state.context_sources =[doc.metadata['source'] for doc in context]
|
59 |
+
st.session_state.context_content = [doc.page_content for doc in context]
|
60 |
+
return state
|
61 |
+
def retrieve_normal_context(retriever, question):
|
62 |
+
docs = retriever.invoke(question)
|
63 |
+
return docs
|
64 |
+
|
65 |
+
# Your OLMOLLM class implementation here (adapted for the Hugging Face model)
|
66 |
+
|
67 |
+
@st.cache_resource
|
68 |
+
def get_chain(temperature):
|
69 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L12-v2")
|
70 |
+
|
71 |
+
docstore_path = 'repos_github_opensmodel.pcl'
|
72 |
+
chroma_path = 'repos_github_opensmodel'
|
73 |
+
parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000,
|
74 |
+
chunk_overlap=500)
|
75 |
+
|
76 |
+
# create the child documents - The small chunks
|
77 |
+
child_splitter = RecursiveCharacterTextSplitter(chunk_size=300,
|
78 |
+
chunk_overlap=50)
|
79 |
+
retriever = load_retriever(docstore_path,chroma_path,embeddings,child_splitter,parent_splitter)
|
80 |
+
|
81 |
+
# Replace the local OLMOLLM with the Hugging Face model
|
82 |
+
llm = HuggingFaceLLM(
|
83 |
+
model_id="EleutherAI/gpt-neo-1.3B", # or another suitable model
|
84 |
+
temperature=temperature,
|
85 |
+
max_tokens=256
|
86 |
+
)
|
87 |
+
|
88 |
+
today = date.today()
|
89 |
+
# Response prompt
|
90 |
+
response_prompt_template = """You are an assistant who helps Ocean Hack Week community to answer their questions. I am going to ask you a question. Your response should be comprehensive and not contradicted with the following context if they are relevant. Otherwise, ignore them if they are not relevant.
|
91 |
+
Keep track of chat history: {chat_history}
|
92 |
+
Today's date: {date}
|
93 |
+
## Normal Context:
|
94 |
+
{normal_context}
|
95 |
+
|
96 |
+
# Original Question: {question}
|
97 |
+
|
98 |
+
# Answer (embed links where relevant):
|
99 |
+
|
100 |
+
"""
|
101 |
+
response_prompt = ChatPromptTemplate.from_template(response_prompt_template)
|
102 |
+
context_chain = RunnableLambda(lambda x: {
|
103 |
+
"question": x["question"],
|
104 |
+
"normal_context": retrieve_normal_context(retriever,x["question"]),
|
105 |
+
# "step_back_context": retrieve_step_back_context(retriever,generate_queries_step_back.invoke({"question": x["question"]})),
|
106 |
+
"chat_history": x["chat_history"],
|
107 |
+
"date": today})
|
108 |
+
chain = (
|
109 |
+
context_chain
|
110 |
+
| RunnableLambda(inspect)
|
111 |
+
| response_prompt
|
112 |
+
| llm
|
113 |
+
| StrOutputParser()
|
114 |
+
)
|
115 |
+
return chain
|
116 |
+
|
117 |
+
def clear_chat_history():
|
118 |
+
st.session_state.messages = []
|
119 |
+
st.session_state.context_sources = []
|
120 |
+
st.session_state.key = 0
|
121 |
+
|
122 |
+
st.set_page_config(page_title='OHW AI')
|
123 |
+
|
124 |
+
# Sidebar
|
125 |
+
with st.sidebar:
|
126 |
+
st.title("OHW Assistant")
|
127 |
+
temperature = st.slider("Temperature: ", 0.0, 1.0, 0.5, 0.1)
|
128 |
+
chain = get_chain(temperature)
|
129 |
+
st.button('Clear Chat History', on_click=clear_chat_history)
|
130 |
+
|
131 |
+
# Main app
|
132 |
+
if "messages" not in st.session_state:
|
133 |
+
st.session_state.messages = []
|
134 |
+
|
135 |
+
|
136 |
+
for q, message in enumerate(st.session_state.messages):
|
137 |
+
if (message["role"] == 'assistant'):
|
138 |
+
with st.chat_message(message["role"]):
|
139 |
+
tab1, tab2 = st.tabs(["Answer", "Sources"])
|
140 |
+
with tab1:
|
141 |
+
st.markdown(message["content"])
|
142 |
+
|
143 |
+
with tab2:
|
144 |
+
for i, source in enumerate(message["sources"]):
|
145 |
+
name = f'{source}'
|
146 |
+
with st.expander(name):
|
147 |
+
st.markdown(f'{message["context"][i]}')
|
148 |
+
|
149 |
+
else:
|
150 |
+
question = message["content"]
|
151 |
+
with st.chat_message(message["role"]):
|
152 |
+
st.markdown(message["content"])
|
153 |
+
|
154 |
+
|
155 |
+
if prompt := st.chat_input("How may I assist you today?"):
|
156 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
157 |
+
with st.chat_message("user"):
|
158 |
+
st.markdown(prompt)
|
159 |
+
|
160 |
+
with st.chat_message("assistant"):
|
161 |
+
query=st.session_state.messages[-1]['content']
|
162 |
+
tab1, tab2 = st.tabs(["Answer", "Sources"])
|
163 |
+
with tab1:
|
164 |
+
placeholder = st.empty() # Create a placeholder in Streamlit
|
165 |
+
full_answer = ""
|
166 |
+
for chunk in chain.stream({"question": query, "chat_history":st.session_state.messages}):
|
167 |
+
|
168 |
+
full_answer += chunk
|
169 |
+
placeholder.markdown(full_answer,unsafe_allow_html=True)
|
170 |
+
|
171 |
+
with tab2:
|
172 |
+
for i, source in enumerate(st.session_state.context_sources):
|
173 |
+
name = f'{source}'
|
174 |
+
with st.expander(name):
|
175 |
+
st.markdown(f'{st.session_state.context_content[i]}')
|
176 |
+
|
177 |
+
|
178 |
+
|
179 |
+
|
180 |
+
st.session_state.messages.append({"role": "assistant", "content": full_answer})
|
181 |
+
st.session_state.messages[-1]['sources'] = st.session_state.context_sources
|
182 |
+
st.session_state.messages[-1]['context'] = st.session_state.context_content
|