app.pyā¢11.5 kB
import streamlit as st
import requests
# Konfigurasi halaman
st.set_page_config(
page_title="MCP Server AI Assistant",
page_icon="š¤",
layout="wide"
)
# URL Server
SERVER_URL = "http://localhost:8000"
# Header
st.title("š¤ MCP Server AI Assistant")
st.markdown("---")
# Sidebar untuk memilih mode
st.sidebar.title("āļø Pengaturan")
mode = st.sidebar.radio(
"Pilih Mode:",
["Auto Tool Router", "Google Gemini AI", "Manual Tools"]
)
st.sidebar.markdown("---")
st.sidebar.info(
"**Auto Tool Router**: Otomatis memilih tool berdasarkan prompt\n\n"
"**Google Gemini AI**: Chat dengan AI Google Gemini\n\n"
"**Manual Tools**: Pilih tool secara manual"
)
# ============================================
# MODE 1: Auto Tool Router
# ============================================
if mode == "Auto Tool Router":
st.header("š Auto Tool Router")
st.write("Masukkan pertanyaan dan sistem akan otomatis memilih tool yang tepat.")
prompt = st.text_input(
"Pertanyaan:",
placeholder="Contoh: cuaca di Jakarta, berita teknologi, definisi python, quote bijak"
)
if st.button("š Kirim", type="primary"):
if prompt:
with st.spinner("Memproses..."):
try:
response = requests.post(
f"{SERVER_URL}/auto",
json={"prompt": prompt}
)
if response.status_code == 200:
result = response.json()
st.success("ā
Berhasil!")
# Tampilkan response LLM
st.markdown("### š¬ Jawaban:")
st.write(result.get("response", "Tidak ada response"))
# Tampilkan raw data dalam expander
with st.expander("š Lihat Data Mentah"):
st.json(result.get("raw_data", {}))
else:
st.error(f"ā Error: {response.status_code}")
st.write(response.text)
except Exception as e:
st.error(f"ā Koneksi gagal: {str(e)}")
st.info("Pastikan server berjalan di http://localhost:8000")
else:
st.warning("ā ļø Masukkan pertanyaan terlebih dahulu")
# ============================================
# MODE 2: Google Gemini AI
# ============================================
elif mode == "Google Gemini AI":
st.header("š§ Google Gemini AI")
st.write("Chat dengan Google Gemini AI untuk pertanyaan apapun.")
# Session state untuk menyimpan history chat
if "messages" not in st.session_state:
st.session_state.messages = []
# Tampilkan history chat
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Input chat
if prompt := st.chat_input("Tanya sesuatu..."):
# Tampilkan pesan user
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# Kirim ke API dan tampilkan response
with st.chat_message("assistant"):
with st.spinner("Berpikir..."):
try:
response = requests.post(
f"{SERVER_URL}/llm",
json={"prompt": prompt}
)
if response.status_code == 200:
result = response.json()
ai_response = result.get("response", "Tidak ada response")
st.markdown(ai_response)
st.session_state.messages.append({"role": "assistant", "content": ai_response})
else:
error_msg = f"Error: {response.status_code}"
st.error(error_msg)
except Exception as e:
error_msg = f"Koneksi gagal: {str(e)}"
st.error(error_msg)
# Tombol clear chat
if st.button("šļø Clear Chat"):
st.session_state.messages = []
st.rerun()
# ============================================
# MODE 3: Manual Tools
# ============================================
elif mode == "Manual Tools":
st.header("š ļø Manual Tools")
tool = st.selectbox(
"Pilih Tool:",
["Weather", "News", "Dictionary", "Quotes", "Web Search"]
)
st.markdown("---")
# Weather Tool
if tool == "Weather":
st.subheader("š¤ļø Weather Tool")
city = st.text_input("Nama Kota:", value="Jakarta")
if st.button("Cek Cuaca", type="primary"):
with st.spinner("Mengambil data cuaca..."):
try:
response = requests.post(
f"{SERVER_URL}/auto",
json={"prompt": f"cuaca di {city}"}
)
if response.status_code == 200:
result = response.json()
st.success(f"ā
Cuaca di {result.get('city', city)}")
col1, col2 = st.columns(2)
with col1:
st.metric("š”ļø Suhu", f"{result.get('temp_c', 'N/A')}°C")
with col2:
st.info(f"āļø {result.get('description', 'N/A')}")
else:
st.error(f"ā Error: {response.status_code}")
except Exception as e:
st.error(f"ā Koneksi gagal: {str(e)}")
# News Tool
elif tool == "News":
st.subheader("š° News Tool")
topic = st.text_input("Topik Berita:", value="technology")
if st.button("Cari Berita", type="primary"):
with st.spinner("Mencari berita..."):
try:
response = requests.post(
f"{SERVER_URL}/auto",
json={"prompt": f"berita {topic}"}
)
if response.status_code == 200:
articles = response.json()
st.success(f"ā
Ditemukan {len(articles)} berita")
for i, article in enumerate(articles, 1):
with st.expander(f"š {i}. {article.get('title', 'No Title')}"):
st.write(f"**Sumber:** {article.get('source', {}).get('name', 'Unknown')}")
st.write(f"**Deskripsi:** {article.get('description', 'No description')}")
st.write(f"**Link:** [{article.get('url', '#')}]({article.get('url', '#')})")
else:
st.error(f"ā Error: {response.status_code}")
except Exception as e:
st.error(f"ā Koneksi gagal: {str(e)}")
# Dictionary Tool
elif tool == "Dictionary":
st.subheader("š Dictionary Tool")
word = st.text_input("Kata (dalam bahasa Inggris):", value="technology")
if st.button("Cari Definisi", type="primary"):
with st.spinner("Mencari definisi..."):
try:
response = requests.post(
f"{SERVER_URL}/auto",
json={"prompt": f"definisi {word}"}
)
if response.status_code == 200:
result = response.json()
if "error" not in result:
st.success(f"ā
Definisi: {result.get('word', word)}")
st.info(f"**Part of Speech:** {result.get('part_of_speech', 'N/A')}")
st.write(f"**Definition:** {result.get('definition', 'N/A')}")
if result.get('example'):
st.write(f"**Example:** _{result.get('example')}_")
else:
st.warning("ā ļø Kata tidak ditemukan")
else:
st.error(f"ā Error: {response.status_code}")
except Exception as e:
st.error(f"ā Koneksi gagal: {str(e)}")
# Quotes Tool
elif tool == "Quotes":
st.subheader("š Quotes Tool")
st.write("Dapatkan kutipan bijak acak")
if st.button("Dapatkan Quote", type="primary"):
with st.spinner("Mengambil quote..."):
try:
response = requests.post(
f"{SERVER_URL}/auto",
json={"prompt": "quote bijak"}
)
if response.status_code == 200:
result = response.json()
st.success("ā
Quote of the Day")
st.markdown(f"### _{result.get('quote', 'No quote')}_")
st.write(f"**ā {result.get('author', 'Unknown')}**")
else:
st.error(f"ā Error: {response.status_code}")
except Exception as e:
st.error(f"ā Koneksi gagal: {str(e)}")
# Web Search Tool
elif tool == "Web Search":
st.subheader("š Web Search Tool")
query = st.text_input("Query Pencarian:", value="python programming")
if st.button("Cari", type="primary"):
with st.spinner("Mencari..."):
try:
response = requests.post(
f"{SERVER_URL}/auto",
json={"prompt": query}
)
if response.status_code == 200:
result = response.json()
st.success("ā
Hasil Pencarian")
if result.get('heading'):
st.subheader(result.get('heading'))
if result.get('abstract'):
st.write(result.get('abstract'))
if result.get('related'):
st.write("**Related Topics:**")
for item in result.get('related', []):
if isinstance(item, dict) and 'Text' in item:
st.write(f"- {item['Text']}")
else:
st.error(f"ā Error: {response.status_code}")
except Exception as e:
st.error(f"ā Koneksi gagal: {str(e)}")
# Footer
st.markdown("---")
st.markdown(
"<div style='text-align: center; color: gray;'>"
"MCP Server AI Assistant | Powered by FastAPI & Streamlit"
"</div>",
unsafe_allow_html=True
)