-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathweb_interface.py
More file actions
169 lines (132 loc) · 5.71 KB
/
web_interface.py
File metadata and controls
169 lines (132 loc) · 5.71 KB
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
"""Streamlit web interface for the React Agent."""
# Import gRPC configuration first to suppress warnings
import grpc_config
import streamlit as st
import asyncio
import json
import nest_asyncio
from datetime import datetime
from chatbot import ReactChatbot
from async_utils import run_async_safe
# Enable nested event loops for Streamlit compatibility
nest_asyncio.apply()
async def run_chatbot_safely(chatbot, prompt):
"""Safely run the chatbot with proper async handling."""
try:
return await chatbot.chat(prompt)
except Exception as e:
return {
"input": prompt,
"output": f"I apologize, but I encountered an error: {str(e)}",
"steps": [],
"success": False,
"error": str(e),
"metadata": {}
}
# Page configuration
st.set_page_config(
page_title="Octopus Prime Chatbot",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded"
)
# Initialize session state
if "chatbot" not in st.session_state:
st.session_state.chatbot = ReactChatbot(verbose=False)
if "messages" not in st.session_state:
st.session_state.messages = []
if "show_steps" not in st.session_state:
st.session_state.show_steps = False
if "streaming_mode" not in st.session_state:
st.session_state.streaming_mode = False
def main():
"""Main Streamlit application."""
# Title and description
st.title("🤖 Octopus Prime Chatbot")
st.markdown("I am Octopus Prime, your intelligent assistant. I can help you with various tasks and provide information.")
# Sidebar
with st.sidebar:
st.header("⚙️ Settings")
# Real-time thinking mode
if st.button("🧠 Switch to Real-time Thinking Mode", type="primary"):
st.switch_page("web_interface_streaming.py")
st.divider()
# Show reasoning steps toggle
st.session_state.show_steps = st.checkbox(
"Show reasoning steps",
value=st.session_state.show_steps,
help="Display the agent's thought process and tool usage"
)
st.divider()
# Statistics
st.header("📊 Statistics")
if st.button("Refresh Stats"):
stats = st.session_state.chatbot.get_stats()
st.json(stats)
st.divider()
# Clear conversation
if st.button("🧹 Clear Conversation", type="secondary"):
st.session_state.messages = []
st.session_state.chatbot.clear_history()
st.rerun()
st.divider()
# Available tools
st.header("🔧 Available Tools")
tools = st.session_state.chatbot.agent.tool_manager.get_tool_descriptions()
for tool_name, description in tools.items():
st.write(f"**{tool_name}**: {description}")
# Main chat interface
chat_container = st.container()
with chat_container:
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
# Show reasoning steps if enabled and available
if (st.session_state.show_steps and
message["role"] == "assistant" and
"steps" in message):
with st.expander("🧠 Reasoning Steps", expanded=False):
for i, step in enumerate(message["steps"], 1):
st.write(f"**Step {i}:**")
st.write(f"💭 **Thought**: {step['thought']}")
if step.get('action'):
st.write(f"🔧 **Action**: {step['action']}")
st.write(f"📝 **Input**: {step['action_input']}")
if step.get('observation'):
st.write(f"👁️ **Observation**: {step['observation']}")
if i < len(message["steps"]):
st.divider()
# Chat input
if prompt := st.chat_input("Ask me anything..."):
# Add user message to chat
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.write(prompt)
# Get assistant response
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
# Run the chatbot asynchronously with proper event loop handling
response = run_async_safe(run_chatbot_safely(st.session_state.chatbot, prompt))
# Display response
if response["success"]:
st.write(response["output"])
# Add to session state with steps
assistant_message = {
"role": "assistant",
"content": response["output"],
"steps": response["steps"] if st.session_state.show_steps else []
}
st.session_state.messages.append(assistant_message)
else:
error_msg = f"❌ Error: {response['error']}"
st.error(error_msg)
st.session_state.messages.append({
"role": "assistant",
"content": error_msg
})
# Rerun to update the interface
st.rerun()
if __name__ == "__main__":
main()