devchavda11 commited on
Commit
95ed623
ยท
verified ยท
1 Parent(s): 2c9b3ce

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +73 -44
src/streamlit_app.py CHANGED
@@ -1,12 +1,11 @@
1
-
2
-
3
  import os
4
  os.environ["STREAMLIT_HOME"] = "/tmp/.streamlit"
 
5
  import streamlit as st
6
  from chat_langraph import system, workflow, HumanMessage, AIMessage, get_all_chat_ids, ToolMessage
7
  import uuid
8
  import base64
9
- # import pyttsx3
10
 
11
  st.set_page_config(layout="wide")
12
  st.title("My Chatbot")
@@ -14,25 +13,18 @@ st.title("My Chatbot")
14
  TEMP_DIR = "/tmp"
15
  os.makedirs(TEMP_DIR, exist_ok=True)
16
 
17
-
18
- # --- Helpers ---
19
- # if ("speaker" not in st.session_state):
20
- # st.session_state.speaker = pyttsx3.init()
21
- # st.session_state.tospeak = False
22
-
23
  def set_title(messages):
24
  if messages:
25
  title = "New Chat"
26
  st.session_state.chat_dict[st.session_state.current_chat_id] = title
27
 
28
-
29
  def set_config():
30
  return {"configurable": {"thread_id": st.session_state.current_chat_id}}
31
 
32
-
33
  def load_session_state():
34
  if "chats" not in st.session_state:
35
  st.session_state.chats = get_all_chat_ids()
 
36
  if "current_chat_id" not in st.session_state:
37
  if len(st.session_state.chats) > 0:
38
  st.session_state.current_chat_id = st.session_state.chats[-1]
@@ -40,13 +32,14 @@ def load_session_state():
40
  new_id = str(uuid.uuid4())
41
  st.session_state.chats.append(new_id)
42
  st.session_state.current_chat_id = new_id
 
43
  if "chat_dict" not in st.session_state:
44
  st.session_state.chat_dict = {}
45
 
46
-
47
  def render_sidebar():
48
  with st.sidebar:
49
  st.title("Chats")
 
50
  if st.button("โž• New Chat"):
51
  new_id = str(uuid.uuid4())
52
  st.session_state.chats.append(new_id)
@@ -55,18 +48,21 @@ def render_sidebar():
55
  workflow.update_state(config, {"messages": [system]})
56
  st.session_state.chat_dict[new_id] = "New Chat"
57
  st.rerun()
 
58
  for chat_id in st.session_state.chats:
59
  if st.button(st.session_state.chat_dict.get(chat_id, "New Chat"), key=chat_id):
60
  st.session_state.current_chat_id = chat_id
61
 
 
62
 
63
  def create_download_link(file_path: str, label: str = None) -> str:
64
- """Generate HTML download link for a file."""
65
  if not os.path.exists(file_path):
66
  return ""
 
67
  try:
68
  with open(file_path, "rb") as f:
69
  data = f.read()
 
70
  b64 = base64.b64encode(data).decode()
71
  label = label or f"๐Ÿ“ฅ Download {os.path.basename(file_path)}"
72
  href = f'<a href="data:file/octet-stream;base64,{b64}" download="{os.path.basename(file_path)}">{label}</a>'
@@ -74,63 +70,96 @@ def create_download_link(file_path: str, label: str = None) -> str:
74
  except Exception as e:
75
  return f"Error creating download link: {e}"
76
 
77
-
78
-
79
-
80
-
81
  def loadchats():
82
  if "current_chat_id" not in st.session_state:
83
  return []
 
84
  config = {"configurable": {"thread_id": st.session_state.current_chat_id}}
85
  state = workflow.get_state(config)
86
  messages = state.values.get("messages", [])
 
87
  for message in messages:
88
- if(not message.content):
89
- continue
 
90
  if isinstance(message, HumanMessage):
91
  with st.chat_message("human"):
92
  st.write(message.content)
 
93
  elif isinstance(message, AIMessage):
94
  with st.chat_message("assistant"):
95
- st.write(message.content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  elif isinstance(message, ToolMessage):
97
  with st.chat_message("assistant"):
98
  st.info("Using Appropriate tool")
99
- if(message.name == "plot_graph" and "Filepath" in message.content):
100
- st.image(message.content.split(":")[1] , "๐Ÿ“Š")
101
- if("Filepath" in message.content):
102
- st.markdown(create_download_link(message.content.split(":")[1]) , True)
103
-
 
 
 
 
 
104
  return messages
105
 
106
 
107
- # --- Main Chat Flow ---
108
 
109
  load_session_state()
110
  render_sidebar()
111
 
 
112
  if "current_chat_id" in st.session_state:
113
  loadchats()
 
114
  user_input = st.chat_input("Your message:")
115
- if user_input :
 
116
  with st.chat_message("human"):
117
  st.write(user_input)
118
 
119
  with st.chat_message("assistant"):
120
- response_placeholder = st.empty()
121
- full_response = ""
122
- for message, metadata in workflow.stream(
123
- {"messages": [system, HumanMessage(user_input)]},
124
- config={"configurable": {"thread_id": st.session_state.current_chat_id}},
125
- stream_mode="messages",
126
- ):
127
- tool_link = ""
128
- if isinstance(message, AIMessage):
129
- full_response += message.content or ""
130
- elif isinstance(message, ToolMessage):
131
- st.info("Using Appropriate tool")
132
- response_placeholder.markdown(full_response + " ")
133
- st.rerun()
134
- # if(st.session_state.tospeak):
135
- # st.session_state.speaker.say(full_response)
136
- # st.session_state.runAndWait()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  os.environ["STREAMLIT_HOME"] = "/tmp/.streamlit"
3
+
4
  import streamlit as st
5
  from chat_langraph import system, workflow, HumanMessage, AIMessage, get_all_chat_ids, ToolMessage
6
  import uuid
7
  import base64
8
+ import io
9
 
10
  st.set_page_config(layout="wide")
11
  st.title("My Chatbot")
 
13
  TEMP_DIR = "/tmp"
14
  os.makedirs(TEMP_DIR, exist_ok=True)
15
 
 
 
 
 
 
 
16
  def set_title(messages):
17
  if messages:
18
  title = "New Chat"
19
  st.session_state.chat_dict[st.session_state.current_chat_id] = title
20
 
 
21
  def set_config():
22
  return {"configurable": {"thread_id": st.session_state.current_chat_id}}
23
 
 
24
  def load_session_state():
25
  if "chats" not in st.session_state:
26
  st.session_state.chats = get_all_chat_ids()
27
+
28
  if "current_chat_id" not in st.session_state:
29
  if len(st.session_state.chats) > 0:
30
  st.session_state.current_chat_id = st.session_state.chats[-1]
 
32
  new_id = str(uuid.uuid4())
33
  st.session_state.chats.append(new_id)
34
  st.session_state.current_chat_id = new_id
35
+
36
  if "chat_dict" not in st.session_state:
37
  st.session_state.chat_dict = {}
38
 
 
39
  def render_sidebar():
40
  with st.sidebar:
41
  st.title("Chats")
42
+
43
  if st.button("โž• New Chat"):
44
  new_id = str(uuid.uuid4())
45
  st.session_state.chats.append(new_id)
 
48
  workflow.update_state(config, {"messages": [system]})
49
  st.session_state.chat_dict[new_id] = "New Chat"
50
  st.rerun()
51
+
52
  for chat_id in st.session_state.chats:
53
  if st.button(st.session_state.chat_dict.get(chat_id, "New Chat"), key=chat_id):
54
  st.session_state.current_chat_id = chat_id
55
 
56
+ st.markdown("---")
57
 
58
  def create_download_link(file_path: str, label: str = None) -> str:
 
59
  if not os.path.exists(file_path):
60
  return ""
61
+
62
  try:
63
  with open(file_path, "rb") as f:
64
  data = f.read()
65
+
66
  b64 = base64.b64encode(data).decode()
67
  label = label or f"๐Ÿ“ฅ Download {os.path.basename(file_path)}"
68
  href = f'<a href="data:file/octet-stream;base64,{b64}" download="{os.path.basename(file_path)}">{label}</a>'
 
70
  except Exception as e:
71
  return f"Error creating download link: {e}"
72
 
 
 
 
 
73
  def loadchats():
74
  if "current_chat_id" not in st.session_state:
75
  return []
76
+
77
  config = {"configurable": {"thread_id": st.session_state.current_chat_id}}
78
  state = workflow.get_state(config)
79
  messages = state.values.get("messages", [])
80
+
81
  for message in messages:
82
+ if not message.content:
83
+ continue
84
+
85
  if isinstance(message, HumanMessage):
86
  with st.chat_message("human"):
87
  st.write(message.content)
88
+
89
  elif isinstance(message, AIMessage):
90
  with st.chat_message("assistant"):
91
+
92
+ content = message.content
93
+ rendered_text = ""
94
+
95
+ if isinstance(content, list):
96
+ for item in content:
97
+ if isinstance(item, str):
98
+ rendered_text += item
99
+ elif isinstance(item, dict) and "text" in item:
100
+ rendered_text += item["text"]
101
+ else:
102
+ rendered_text = str(content)
103
+
104
+ st.write(rendered_text)
105
+
106
  elif isinstance(message, ToolMessage):
107
  with st.chat_message("assistant"):
108
  st.info("Using Appropriate tool")
109
+
110
+ if message.name == "plot_graph" and "Filepath" in message.content:
111
+ st.image(message.content.split(":")[1], "๐Ÿ“Š")
112
+
113
+ if "Filepath" in message.content:
114
+ st.markdown(
115
+ create_download_link(message.content.split(":")[1]),
116
+ unsafe_allow_html=True
117
+ )
118
+
119
  return messages
120
 
121
 
 
122
 
123
  load_session_state()
124
  render_sidebar()
125
 
126
+
127
  if "current_chat_id" in st.session_state:
128
  loadchats()
129
+
130
  user_input = st.chat_input("Your message:")
131
+
132
+ if user_input:
133
  with st.chat_message("human"):
134
  st.write(user_input)
135
 
136
  with st.chat_message("assistant"):
137
+ with st.spinner("Assistant is thinking..."):
138
+
139
+ response_placeholder = st.empty()
140
+ full_response = ""
141
+
142
+ for message, metadata in workflow.stream(
143
+ {"messages": [system, HumanMessage(user_input)]},
144
+ config={"configurable": {"thread_id": st.session_state.current_chat_id}},
145
+ stream_mode="messages",
146
+ ):
147
+
148
+ if isinstance(message, AIMessage):
149
+ content = message.content
150
+
151
+ if isinstance(content, list):
152
+ for item in content:
153
+ if isinstance(item, str):
154
+ full_response += item
155
+ elif isinstance(item, dict) and "text" in item:
156
+ full_response += item["text"]
157
+ else:
158
+ full_response += str(content)
159
+
160
+ elif isinstance(message, ToolMessage):
161
+ st.info("Using Appropriate tool")
162
+
163
+ response_placeholder.markdown(full_response + " ")
164
+
165
+ st.rerun()