-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexp_chat_with_case_st.py
225 lines (183 loc) · 7.76 KB
/
exp_chat_with_case_st.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import os
import dotenv
from dotenv import load_dotenv
import openai
from llama_index import(
SimpleDirectoryReader,
VectorStoreIndex,
StorageContext,
ServiceContext,
LLMPredictor,
GPTVectorStoreIndex,
QuestionAnswerPrompt
)
import pinecone
from llama_index.vector_stores import PineconeVectorStore
from llama_index.retrievers import VectorIndexRetriever
from langchain.chat_models import ChatOpenAI
from llama_index.vector_stores.types import ExactMatchFilter, MetadataFilters
import streamlit as st
import sys
load_dotenv()
openai.api_key = st.secrets["OPENAI_API_KEY"]
# if len(sys.argv) < 2:
# print("No argument")
# sys.exit(1)
# url_segment = sys.argv[1]
# print(f"Recieved Url sement: {url_segment}")
def create_list_of_case_numbers(cases_folder_path):
list_of_case_numbers = []
for sub_folder in os.listdir(cases_folder_path):
sub_folder_path = os.path.join(cases_folder_path, sub_folder)
cases = os.listdir(sub_folder_path)
for case in cases:
case_number = case.replace(".docx","")
list_of_case_numbers.append(case_number)
return list_of_case_numbers
def build_case_query_engine(case_num, prompt_template):
pinecone.init(
api_key=st.secrets["PINECONE_API_KEY"],
environment=st.secrets["PINECONE_ENVIRONMENT"]
)
index_name = "cases-index"
if index_name not in pinecone.list_indexes():
pinecone.create_index(
index_name,
dimension=1536,
metric='cosine'
)
print("Pinecone canvas does not exist. Just created and connected.")
pinecone_index = pinecone.Index(index_name)
print("Pinecone canvas already exists. Now we're connected.")
vector_store = PineconeVectorStore(pinecone_index=pinecone_index)
vector_index = VectorStoreIndex.from_vector_store(vector_store=vector_store)
filters = MetadataFilters(filters=[
ExactMatchFilter(
key = "case_num",
value = case_num
)
])
# PROMPT_TEMPLATE = (
# "Here are the context information:"
# "\n------------------------------\n"
# "{context_str}"
# "\n------------------------------\n"
# "You are a AI legal assistant for lawyers in Hong Kong. Answer the follwing question in two parts. Break down these two parts with sub-headings. First, explained what happened in the case for reference in the context. Second, explain how this case is relevant to the following siutation or question: {query_str}. \n"
# )
PROMPT_TEMPLATE = (prompt_template)
# PROMPT_TEMPLATE = (
# "Here are the context information:"
# "\n---------------------------------\n"
# "{context_str}"
# "\n---------------------------------\n"
# "You are a AI legal assistant for lawyers in Hong Kong. Answer your question based on the context given and you must mention the exact sentences or paragraphs you used to return the answer of this question: {query_str}"
# )
QA_PROMPT = QuestionAnswerPrompt(PROMPT_TEMPLATE)
query_engine = vector_index.as_query_engine(
similarity_top_k=3,
vector_store_query_mode="default",
filters=filters,
text_qa_template=QA_PROMPT,
streaming = True,
service_context=build_context("gpt-3.5-turbo")
)
print("Query engine created.")
return query_engine
def build_context(model_name):
llm_predictor = LLMPredictor(
llm=ChatOpenAI(temperature=0, model_name=model_name)
)
return ServiceContext.from_defaults(llm_predictor=llm_predictor)
def query_case(case_num, query, prompt_template):
query_engine = build_case_query_engine(case_num, prompt_template)
response = query_engine.query(query)
# print("HAHAH")
# print(response.get_formatted_sources().strip())
return response.response_gen
def main():
params = st.experimental_get_query_params()
if params:
incoming = params['case_num'][0]
else:
incoming = 0
st.set_page_config(
page_title=":robot_face:Chat with Any Case",
page_icon=":robot_face:",
layout="centered",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://www.extremelycoolapp.com/help',
'Report a bug': "https://www.extremelycoolapp.com/bug",
'About': "# Find me at [email protected]"
}
)
st.info("This is just an experimental version to test prompt template.", icon="ℹ️")
st.title(":robot_face: Chat with Any Case")
cases_folder_path = "./data/DCPI"
list_of_case_numbers = create_list_of_case_numbers(cases_folder_path)
st.sidebar.title("Prompt Template Experimentation")
with st.sidebar:
user_input_prompt_template = st.sidebar.text_area("Prompt Template:", placeholder="See below as an example.")
st.button("submit")
st.divider()
st.markdown("**Original prompt template:**")
st.code("Here are the context information:"
"\n---------------------------------\n"
"{context_str}"
"\n---------------------------------\n"
"You are a AI legal assistant for lawyers in Hong Kong. Answer your question based on the context given and you must mention the exact sentences or paragraphs you used to return the answer of this question: {query_str}")
st.divider()
st.markdown("**Prompt template you're using**")
st.code(user_input_prompt_template)
if "messages" not in st.session_state.keys():
st.session_state.messages = [
{"role": "assistant", "content": f"Ask me a question about this case!"}
]
if "streaming" not in st.session_state:
st.session_state.streaming = False
if "selected_case" not in st.session_state:
st.session_state.selected_case = None
if prompt := st.chat_input("Your question"):
st.session_state.messages.append({"role": "user", "content": prompt})
st.session_state.streaming = True
if st.session_state.streaming:
st.warning("Please wait for the current answer to complete.")
st.selectbox(
'Which case would you like to chat with?',
("Please wait...",), disabled=True)
case_num = st.session_state.selected_case
else:
if st.session_state.selected_case != None:
index = list_of_case_numbers.index(st.session_state.selected_case)
else:
if incoming != 0:
index = list_of_case_numbers.index(incoming)
else:
index = 0
case_num = st.selectbox(
'Which case would you like to chat with?',
(list_of_case_numbers), index = index)
if st.session_state.selected_case != case_num:
st.session_state.selected_case = case_num
st.session_state.messages = [
{"role": "assistant", "content": f"Ask me a question about case {case_num}."}
]
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
if st.session_state.messages[-1]["role"] != "assistant":
with st.chat_message("assistant"):
with st.spinner("Generating answer..."):
response = query_case(case_num, prompt, user_input_prompt_template)
ans_box = st.empty()
stream = []
for res in response:
stream.append(res)
answer = "".join(stream).strip()
ans_box.markdown(answer)
message = {"role": "assistant", "content": answer}
st.session_state.messages.append(message)
st.session_state.streaming = False
st.experimental_rerun()
if __name__ == "__main__":
main()