Spaces:
Running
Running
File size: 5,884 Bytes
effc62f 29206ac effc62f 98d495a effc62f 4885d74 effc62f 29206ac effc62f 29206ac effc62f a5f67d6 effc62f 98d495a effc62f 98d495a effc62f 98d495a effc62f 98d495a effc62f 98d495a effc62f 4885d74 effc62f 98d495a effc62f |
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 |
# frontend.py
import streamlit as st
import asyncio
from backend import get_agent, MCPAgent
import time
st.set_page_config(
page_title="MCP Agent Chat",
page_icon="π€",
layout="wide",
initial_sidebar_state="expanded"
)
st.markdown("""
<style>
.stChatMessage {
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
.user-message {
background-color: #e3f2fd;
}
.assistant-message {
background-color: #f5f5f5;
}
.sidebar-info {
padding: 1rem;
background-color: #f0f2f6;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state
if "messages" not in st.session_state:
st.session_state.messages = []
st.session_state.history = [] # For agent history
st.session_state.agent_initialized = False
st.session_state.available_tools = [] # Add this to ensure iterable default
st.session_state.pending_query = None # For example queries
# Sidebar
with st.sidebar:
st.title("π€ MCP AI Algo Trade App Demo")
st.markdown("### βΉοΈ About")
st.markdown("""
This chat interface connects to:
- **Math Server**: Basic arithmetic operations
- **Stock Server**: Mock Real-time market data
The agent uses LangChain and MCP to intelligently route your queries to the appropriate tools.
""")
st.markdown("---")
if st.session_state.agent_initialized:
st.success("β
Agent Connected")
st.markdown("### π οΈ Available Tools")
available_tools = st.session_state.get("available_tools", [])
for tool in available_tools:
st.markdown(f"β’ `{tool}`")
else:
st.info("β³ Agent Initializing...")
st.markdown("---")
st.markdown("### π‘ Example Queries")
example_queries = [
"What's the price of AAPL?",
"Show me the market summary",
"Get news about TSLA",
"Calculate 25 * 4",
"What's 100 divided by 7?",
"Add 456 and 789"
]
for query in example_queries:
if st.button(query, key=f"example_{query}"):
st.session_state.pending_query = query
st.rerun()
st.markdown("---")
if st.button("ποΈ Clear Chat", type="secondary"):
st.session_state.messages = []
st.session_state.history = []
st.rerun()
# Main chat interface
st.title("π¬ MCP Agent Chat")
st.markdown("Ask me about stocks, math calculations, or general questions!")
# Initialize agent asynchronously
async def initialize_agent():
"""Initialize the agent if not already done"""
if not st.session_state.agent_initialized:
agent = get_agent()
with st.spinner("π§ Initializing MCP servers..."):
try:
tools = await agent.initialize()
st.session_state.available_tools = tools or [] # Guard against None
st.session_state.agent_initialized = True
st.rerun() # Add this to refresh UI after init
return True
except Exception as e:
st.error(f"Failed to initialize agent: {str(e)}")
st.info("Please make sure the stock server is running: `python stock_server.py`")
return False
return True
async def process_user_message(user_input: str):
"""Process the user's message and get response from agent"""
agent = get_agent()
st.session_state.history.append({"role": "user", "content": user_input})
try:
response = await agent.process_message(user_input, st.session_state.history)
st.session_state.history.append({"role": "assistant", "content": response})
return response
except Exception as e:
return f"Error: {str(e)}"
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if st.session_state.pending_query:
query = st.session_state.pending_query
st.session_state.pending_query = None # Clear it
st.session_state.messages.append({"role": "user", "content": query})
async def process_example():
if not st.session_state.agent_initialized:
if not await initialize_agent():
return "Failed to initialize agent. Please check the servers."
return await process_user_message(query)
with st.spinner("Processing..."):
response = asyncio.run(process_example())
st.session_state.messages.append({"role": "assistant", "content": response})
st.rerun()
if prompt := st.chat_input("Type your message here..."):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
message_placeholder = st.empty()
async def get_response():
if not st.session_state.agent_initialized:
if not await initialize_agent():
return "Failed to initialize agent. Please check the servers."
return await process_user_message(prompt)
with st.spinner("Thinking..."):
response = asyncio.run(get_response())
message_placeholder.markdown(response)
st.session_state.messages.append({"role": "assistant", "content": response})
if not st.session_state.agent_initialized:
with st.spinner("π§ Initializing agent..."):
asyncio.run(initialize_agent())
st.markdown("---")
st.markdown(
"""
<div style='text-align: center; color: #666;'>
Powered by LangGraph, LangChain, MCP, and Hugging Face
Developed by Lorentz Yeung
</div>
""",
unsafe_allow_html=True
) |