Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +73 -46
src/streamlit_app.py
CHANGED
|
@@ -4,14 +4,14 @@ import uuid
|
|
| 4 |
import os
|
| 5 |
import base64
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
TEMP_DIR = "/tmp"
|
| 9 |
os.makedirs(TEMP_DIR, exist_ok=True)
|
| 10 |
|
| 11 |
-
st.set_page_config(layout="wide")
|
| 12 |
-
st.title("MY CHATBOT")
|
| 13 |
-
|
| 14 |
|
|
|
|
| 15 |
def set_title(messages):
|
| 16 |
if messages:
|
| 17 |
title = "New Chat"
|
|
@@ -46,11 +46,69 @@ def render_sidebar():
|
|
| 46 |
config = {"configurable": {"thread_id": new_id}}
|
| 47 |
workflow.update_state(config, {"messages": [system]})
|
| 48 |
st.session_state.chat_dict[new_id] = "New Chat"
|
|
|
|
| 49 |
for chat_id in st.session_state.chats:
|
| 50 |
if st.button(st.session_state.chat_dict.get(chat_id, "New Chat"), key=chat_id):
|
| 51 |
st.session_state.current_chat_id = chat_id
|
| 52 |
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
def loadchats():
|
| 55 |
if "current_chat_id" not in st.session_state:
|
| 56 |
return []
|
|
@@ -59,70 +117,39 @@ def loadchats():
|
|
| 59 |
messages = state.values.get("messages", [])
|
| 60 |
for message in messages:
|
| 61 |
if isinstance(message, HumanMessage):
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
st.write(message.content)
|
| 65 |
elif isinstance(message, AIMessage):
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
st.write(message.content)
|
| 69 |
elif isinstance(message, ToolMessage):
|
| 70 |
render_tool_message(message)
|
| 71 |
return messages
|
| 72 |
|
| 73 |
|
| 74 |
-
|
| 75 |
-
try:
|
| 76 |
-
with open(file_path, "rb") as f:
|
| 77 |
-
data = f.read()
|
| 78 |
-
b64 = base64.b64encode(data).decode()
|
| 79 |
-
href = f'<a href="data:file/octet-stream;base64,{b64}" download="{os.path.basename(file_path)}">{label}</a>'
|
| 80 |
-
return href
|
| 81 |
-
except Exception as e:
|
| 82 |
-
return f"Error creating download link: {e}"
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def render_tool_message(tool_message: ToolMessage):
|
| 86 |
-
"""Render tool output including download links for any created files."""
|
| 87 |
-
with st.chat_message("assistant"):
|
| 88 |
-
st.info("Tool executed")
|
| 89 |
-
|
| 90 |
-
# If tool_message has an explicit "file" field in content/metadata
|
| 91 |
-
if hasattr(tool_message, "content") and isinstance(tool_message.content, dict):
|
| 92 |
-
file_paths = tool_message.content.get("files", [])
|
| 93 |
-
for file_path in file_paths:
|
| 94 |
-
if os.path.exists(file_path):
|
| 95 |
-
if file_path.lower().endswith((".png", ".jpg", ".jpeg")):
|
| 96 |
-
st.image(file_path, caption=os.path.basename(file_path))
|
| 97 |
-
st.markdown(
|
| 98 |
-
create_download_link(file_path, f"📥 Download {os.path.basename(file_path)}"),
|
| 99 |
-
unsafe_allow_html=True,
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
# --- Main App Logic ---
|
| 104 |
load_session_state()
|
| 105 |
render_sidebar()
|
| 106 |
|
| 107 |
if "current_chat_id" in st.session_state:
|
| 108 |
loadchats()
|
| 109 |
-
user_input = st.chat_input("Your message:
|
| 110 |
-
if user_input
|
| 111 |
with st.chat_message("human"):
|
| 112 |
st.write(user_input)
|
| 113 |
|
| 114 |
with st.chat_message("assistant"):
|
| 115 |
response_placeholder = st.empty()
|
| 116 |
full_response = ""
|
|
|
|
| 117 |
for message, metadata in workflow.stream(
|
| 118 |
{"messages": [system, HumanMessage(user_input)]},
|
| 119 |
config={"configurable": {"thread_id": st.session_state.current_chat_id}},
|
| 120 |
stream_mode="messages",
|
| 121 |
):
|
| 122 |
-
if isinstance(message, AIMessage)
|
| 123 |
-
full_response += message.content
|
| 124 |
-
|
| 125 |
-
if isinstance(message, ToolMessage):
|
| 126 |
render_tool_message(message)
|
| 127 |
|
| 128 |
response_placeholder.markdown(full_response)
|
|
|
|
| 4 |
import os
|
| 5 |
import base64
|
| 6 |
|
| 7 |
+
st.set_page_config(layout="wide")
|
| 8 |
+
st.title("College Chatbot")
|
| 9 |
+
|
| 10 |
TEMP_DIR = "/tmp"
|
| 11 |
os.makedirs(TEMP_DIR, exist_ok=True)
|
| 12 |
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# --- Helpers ---
|
| 15 |
def set_title(messages):
|
| 16 |
if messages:
|
| 17 |
title = "New Chat"
|
|
|
|
| 46 |
config = {"configurable": {"thread_id": new_id}}
|
| 47 |
workflow.update_state(config, {"messages": [system]})
|
| 48 |
st.session_state.chat_dict[new_id] = "New Chat"
|
| 49 |
+
|
| 50 |
for chat_id in st.session_state.chats:
|
| 51 |
if st.button(st.session_state.chat_dict.get(chat_id, "New Chat"), key=chat_id):
|
| 52 |
st.session_state.current_chat_id = chat_id
|
| 53 |
|
| 54 |
|
| 55 |
+
def create_download_link(file_path: str, label: str = None) -> str:
|
| 56 |
+
"""Generate HTML download link for a file."""
|
| 57 |
+
if not os.path.exists(file_path):
|
| 58 |
+
return ""
|
| 59 |
+
try:
|
| 60 |
+
with open(file_path, "rb") as f:
|
| 61 |
+
data = f.read()
|
| 62 |
+
b64 = base64.b64encode(data).decode()
|
| 63 |
+
label = label or f"📥 Download {os.path.basename(file_path)}"
|
| 64 |
+
href = f'<a href="data:file/octet-stream;base64,{b64}" download="{os.path.basename(file_path)}">{label}</a>'
|
| 65 |
+
return href
|
| 66 |
+
except Exception as e:
|
| 67 |
+
return f"Error creating download link: {e}"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def show_file(file_path: str):
|
| 71 |
+
"""Show file inline + download link."""
|
| 72 |
+
if not os.path.exists(file_path):
|
| 73 |
+
return
|
| 74 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 75 |
+
if ext in [".png", ".jpg", ".jpeg"]:
|
| 76 |
+
st.image(file_path, caption=os.path.basename(file_path))
|
| 77 |
+
elif ext in [".txt", ".py", ".java", ".cpp", ".md"]:
|
| 78 |
+
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 79 |
+
st.code(f.read(), language=ext.lstrip("."))
|
| 80 |
+
st.markdown(create_download_link(file_path), unsafe_allow_html=True)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def render_tool_message(tool_message: ToolMessage):
|
| 84 |
+
"""Render tool execution based on tool name instead of message content."""
|
| 85 |
+
file_related_keywords = ["read", "write", "file", "save", "export", "create"]
|
| 86 |
+
with st.chat_message("assistant"):
|
| 87 |
+
tool_name = getattr(tool_message, "name", "").lower()
|
| 88 |
+
st.info(f"🧰 Tool used: {tool_name or 'Unknown Tool'}")
|
| 89 |
+
|
| 90 |
+
# Check if this is a file-related tool
|
| 91 |
+
if any(k in tool_name for k in file_related_keywords):
|
| 92 |
+
# Find all files in TEMP_DIR (freshly modified ones)
|
| 93 |
+
created_files = sorted(
|
| 94 |
+
[os.path.join(TEMP_DIR, f) for f in os.listdir(TEMP_DIR)],
|
| 95 |
+
key=lambda x: os.path.getmtime(x),
|
| 96 |
+
reverse=True,
|
| 97 |
+
)
|
| 98 |
+
if created_files:
|
| 99 |
+
st.success("📄 File(s) created by tool:")
|
| 100 |
+
for file_path in created_files[:3]: # show up to 3 recent
|
| 101 |
+
show_file(file_path)
|
| 102 |
+
else:
|
| 103 |
+
st.warning("No new file detected in /tmp.")
|
| 104 |
+
else:
|
| 105 |
+
# Non-file tools
|
| 106 |
+
if isinstance(tool_message.content, str):
|
| 107 |
+
st.write(tool_message.content)
|
| 108 |
+
elif isinstance(tool_message.content, dict):
|
| 109 |
+
st.json(tool_message.content)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
def loadchats():
|
| 113 |
if "current_chat_id" not in st.session_state:
|
| 114 |
return []
|
|
|
|
| 117 |
messages = state.values.get("messages", [])
|
| 118 |
for message in messages:
|
| 119 |
if isinstance(message, HumanMessage):
|
| 120 |
+
with st.chat_message("human"):
|
| 121 |
+
st.write(message.content)
|
|
|
|
| 122 |
elif isinstance(message, AIMessage):
|
| 123 |
+
with st.chat_message("assistant"):
|
| 124 |
+
st.write(message.content)
|
|
|
|
| 125 |
elif isinstance(message, ToolMessage):
|
| 126 |
render_tool_message(message)
|
| 127 |
return messages
|
| 128 |
|
| 129 |
|
| 130 |
+
# --- Main Chat Flow ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
load_session_state()
|
| 132 |
render_sidebar()
|
| 133 |
|
| 134 |
if "current_chat_id" in st.session_state:
|
| 135 |
loadchats()
|
| 136 |
+
user_input = st.chat_input("Your message:")
|
| 137 |
+
if user_input:
|
| 138 |
with st.chat_message("human"):
|
| 139 |
st.write(user_input)
|
| 140 |
|
| 141 |
with st.chat_message("assistant"):
|
| 142 |
response_placeholder = st.empty()
|
| 143 |
full_response = ""
|
| 144 |
+
|
| 145 |
for message, metadata in workflow.stream(
|
| 146 |
{"messages": [system, HumanMessage(user_input)]},
|
| 147 |
config={"configurable": {"thread_id": st.session_state.current_chat_id}},
|
| 148 |
stream_mode="messages",
|
| 149 |
):
|
| 150 |
+
if isinstance(message, AIMessage):
|
| 151 |
+
full_response += message.content or ""
|
| 152 |
+
elif isinstance(message, ToolMessage):
|
|
|
|
| 153 |
render_tool_message(message)
|
| 154 |
|
| 155 |
response_placeholder.markdown(full_response)
|