Spaces:
Sleeping
Sleeping
File size: 6,601 Bytes
effc62f 4885d74 effc62f a5f67d6 effc62f 4885d74 effc62f 4885d74 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 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 |
# frontend.py
"""
Streamlit frontend for MCP Agent
Provides a chat interface for interacting with the MCP backend
"""
import streamlit as st
import asyncio
from backend import get_agent, MCPAgent
import time
# Page configuration
st.set_page_config(
page_title="MCP Agent Chat",
page_icon="π€",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better chat appearance
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 = []
st.session_state.pending_query = None # For example queries
# Sidebar
with st.sidebar:
st.title("π€ MCP Agent")
st.markdown("---")
# Status indicator
if st.session_state.agent_initialized:
st.success("β
Agent Connected")
# Show available tools
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("---")
# Example queries
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("---")
# Clear chat button
if st.button("ποΈ Clear Chat", type="secondary"):
st.session_state.messages = []
st.session_state.history = []
st.rerun()
# Info section
st.markdown("### βΉοΈ About")
st.markdown("""
This chat interface connects to:
- **Math Server**: Basic arithmetic operations
- **Stock Server**: Real-time market data
The agent uses LangChain and MCP to intelligently route your queries to the appropriate tools.
""")
# 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
st.session_state.agent_initialized = True
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
# Process user message
async def process_user_message(user_input: str):
"""Process the user's message and get response from agent"""
agent = get_agent()
# Add user message to history
st.session_state.history.append({"role": "user", "content": user_input})
try:
# Get response from agent
response = await agent.process_message(user_input, st.session_state.history)
# Add assistant response to history
st.session_state.history.append({"role": "assistant", "content": response})
return response
except Exception as e:
return f"Error: {str(e)}"
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Process pending query from example buttons
if st.session_state.pending_query:
query = st.session_state.pending_query
st.session_state.pending_query = None # Clear it
# Add to messages
st.session_state.messages.append({"role": "user", "content": query})
# Process the 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)
# Get response
with st.spinner("Processing..."):
response = asyncio.run(process_example())
# Add response to messages
st.session_state.messages.append({"role": "assistant", "content": response})
# Rerun to display the new messages
st.rerun()
# Chat input
if prompt := st.chat_input("Type your message here..."):
# Add user message to chat
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
# Get and display assistant response
with st.chat_message("assistant"):
message_placeholder = st.empty()
# Run async function
async def get_response():
# Initialize agent if needed
if not st.session_state.agent_initialized:
if not await initialize_agent():
return "Failed to initialize agent. Please check the servers."
# Process message
return await process_user_message(prompt)
# Execute async function
with st.spinner("Thinking..."):
response = asyncio.run(get_response())
message_placeholder.markdown(response)
st.session_state.messages.append({"role": "assistant", "content": response})
# Auto-initialize agent on first load
if not st.session_state.agent_initialized:
with st.spinner("π§ Initializing agent..."):
asyncio.run(initialize_agent())
# Footer
st.markdown("---")
st.markdown(
"""
<div style='text-align: center; color: #666;'>
Powered by LangChain, MCP, and Hugging Face π€
</div>
""",
unsafe_allow_html=True
) |