-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.py
245 lines (188 loc) · 8.85 KB
/
app.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File: app.py
## It has two states:
## 1. from LangGraph, for internal sanitization, UMLS expansion. The sanitized will only be shown in the comment section of the sql
## 2. from st.session_state, this is for UI to display the original question and the final answer.
from config import init_session_state, add_button_styles
from ui.chat_display import display_chat_messages
from ui.query_confirmation import create_query_confirmation_ui
from langchain.schema import HumanMessage
import streamlit as st
import json
from utils.my_langchain_tools import *
from utils.error_handler import handle_query_error, clear_error_state, clear_confirmation_state
from utils.message_handler import store_ai_message
from utils.chain_processor import process_chain_response
import my_db_specifics
from langchain_core.messages import ToolMessage, AIMessage
import graph_definition as gd
import os
#from copy import deepcopy
config = {"configurable": {"thread_id": "1", "user_id": "sixing"}}
# Example queries that can be used via buttons
EXAMPLE_QUERIES = []
def load_examples():
for example_list in [
(my_db_specifics.sql_examples),
(my_db_specifics.graph_examples),
(my_db_specifics.full_text_search_examples),
(my_db_specifics.vector_search_examples)
]:
for example in example_list:
EXAMPLE_QUERIES.append(example)
with open("interaction.jsonl", "r") as file:
for line in file:
example = json.loads(line)
EXAMPLE_QUERIES.append(example)
load_examples()
def create_example_buttons():
"""Create buttons for example queries in a single column"""
for idx, example in enumerate(EXAMPLE_QUERIES):
if st.button(
example["input"],
key=f"example_{idx}",
use_container_width=True,
):
handle_example_query(example)
st.rerun()
def handle_example_query(example):
"""Handle when an example query button is clicked"""
# Add the user's "question" to the chat
st.session_state.messages.append(AIMessage(content=example["input"], additional_kwargs={"function": {"arguments": str({"question": example["input"], "top_k": 5})}}))
st.session_state.messages.append(HumanMessage(content=example["input"]))
# Set up the confirmation state as if the bot generated this query
st.session_state.awaiting_confirmation = True
st.session_state.current_query = example["query"]
st.session_state.current_chain_input = example["input"]
st.session_state.tool_name = example["tool_name"]
def process_confirmed_query(query):
"""Process a confirmed query and store the response"""
with st.spinner("Processing confirmed query..."):
#print ("hello", query)
#print ("in if prompt", app.get_state(config))
tool_name = st.session_state.tool_name
tool_message = [
{
"name": tool_name,
"type": "user",
"content": query
}
]
gd.app.update_state(config, {"messages": tool_message}, as_node="human_feedback")
print ("process_confirmed_query", gd.app.get_state(config))
#app.stream(None, config, stream_mode="values")
events = list(gd.app.stream(None, config, stream_mode="values"))
#print ("events", events)
last_event = events[-1]
#print (last_event)
#print ("state", event)
#print (event["messages"][-1].content)
print ("----question-----")
print (last_event["messages"][-1].additional_kwargs.get("question"))
print ("----final_query-----")
print (last_event["messages"][-1].additional_kwargs.get("query"))
print ("----query_result-----")
print (last_event["messages"][-1].additional_kwargs.get("execute_result"))
print ("----answer-----")
print (last_event["messages"][-1].content)
store_ai_message(last_event["messages"][-1].content, last_event["messages"][-1].additional_kwargs.get("query"))
clear_confirmation_state()
def handle_confirmation_result(confirmation_result):
"""Handle the result of query confirmation"""
if confirmation_result == "waiting":
return False
if confirmation_result is not None:
try:
process_confirmed_query(confirmation_result)
return True
except Exception as e:
handle_query_error(e)
return True
else:
st.warning("Query rejected. Please try a different question.")
clear_error_state()
return True
def run_chatbot():
"""Main function to run the chatbot interface"""
# Configure the sidebar
with st.sidebar:
st.markdown("### Example queries you can try:")
create_example_buttons()
# Main chat interface
st.title("DrugBot 💊")
# Initialize session state
init_session_state()
print ("********************At the beginning st.session_state", st.session_state)
# Display chat messages in main area
display_chat_messages()
# Handle confirmation UI if needed
if st.session_state.awaiting_confirmation:
#print ("in awaiting_confirmation", app.get_state(config))
confirmation_result = create_query_confirmation_ui()
if handle_confirmation_result(confirmation_result):
st.rerun()
# Create columns for chat input and dropdown
input_col, dropdown_col, is_expanded_col = st.columns([5, 1, 1])
#input_col, dropdown_col = st.columns([5, 1])
with input_col:
prompt = st.chat_input(
"What would you like to know about the drugs database?",
key="chat_input"
)
with dropdown_col:
user_tool = st.selectbox(
"Tools to select:",
options=["Automatic", "SQL", "Graph", "Vector", "Fulltext", "Mimicking"],
key="tool_selector",
label_visibility="collapsed"
)
with is_expanded_col:
is_expanded_checkbox = st.checkbox(
"Medical terms to UMLS",
key="is_expanded"
)
if prompt:
#print ("input_message", input_message)
try:
expanded_prompt = prompt
if is_expanded_checkbox:
with st.spinner("Querying UMLS..."):
expanded_prompt = expand_question(prompt)
input_message = HumanMessage(content=expanded_prompt, tool_choice=user_tool.lower())
with st.spinner("Processing response..."):
#st.session_state.messages.append(HumanMessage(content=input_message.content))
st.session_state.messages.append(HumanMessage(content=prompt))
for event in gd.app.stream({"messages": [input_message]}, config, stream_mode="values"):
print ("len:", len(event["messages"]))
#print ("in try if prompt", app.get_state(config).values["messages"])
#st.session_state.tool_name = "clarifying"
#print ("!!!!!!!!!!!!!!!!!!!!!!gd.app.get_state(config).values", gd.app.get_state(config).values)
generated_message = gd.app.get_state(config).values["messages"][-1]
#print ("!!!!!!!!!!!!!!!!!!!!!!generated_message", generated_message)
#### AI needs to ask a clarifying question
if isinstance(generated_message, AIMessage):
tool_name = "clarifying"
tool_call_id = "dummy_tool_id"
print ("=================================================tool_name", tool_name, "tool_call_id", tool_call_id)
process_chain_response(generated_message.content, tool_name, tool_call_id, expanded_prompt)
elif isinstance(generated_message, ToolMessage):
print ("============================ in prompt, toolmessage, generated_message", generated_message)
generated_query = generated_message.content
#print ("generated_query\n", type(app.get_state(config).values["messages"][-1]), app.get_state(config).values["messages"][-1])
tool_name = generated_message.name
tool_call_id = generated_message.tool_call_id
process_chain_response(generated_query, tool_name, tool_call_id, expanded_prompt)
except Exception as e:
st.error(f"Error: {str(e)}")
st.rerun()
if __name__ == "__main__":
# checkpoint = "checkpoints.db"
# if os.path.isfile(checkpoint):
# os.remove(checkpoint)
st.set_page_config(
page_title="DrugBot",
page_icon="💊",
layout="wide", # Make better use of screen width
initial_sidebar_state="expanded" # Start with sidebar visible
)
add_button_styles()
run_chatbot()