Delete streamlit_app.py
Browse files- streamlit_app.py +0 -216
streamlit_app.py
DELETED
|
@@ -1,216 +0,0 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import os
|
| 3 |
-
from dotenv import load_dotenv
|
| 4 |
-
|
| 5 |
-
st.set_page_config(page_title="🚀 NVIDIA AI Assistant", page_icon="📈", layout="wide")
|
| 6 |
-
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import joblib
|
| 9 |
-
from datetime import datetime
|
| 10 |
-
# LangChain & LangGraph
|
| 11 |
-
from langchain_openai import ChatOpenAI # type: ignore
|
| 12 |
-
from langchain_chroma import Chroma # type: ignore
|
| 13 |
-
from langchain_huggingface import HuggingFaceEmbeddings # type: ignore
|
| 14 |
-
from langchain_community.tools import DuckDuckGoSearchRun # type: ignore
|
| 15 |
-
from langchain_core.messages import SystemMessage, HumanMessage # type: ignore
|
| 16 |
-
from langgraph.graph import StateGraph, END # type: ignore
|
| 17 |
-
from typing import TypedDict, Annotated
|
| 18 |
-
import operator
|
| 19 |
-
|
| 20 |
-
DRIVE_DB_PATH = "./chroma_db_v2"
|
| 21 |
-
CSV_PATH = "nvda_2014_to_2026.csv"
|
| 22 |
-
MODEL_PATH = "nvidia_price_model.pkl"
|
| 23 |
-
|
| 24 |
-
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 25 |
-
if not OPENAI_API_KEY:
|
| 26 |
-
st.error("❌ OPENAI_API_KEY not found in .env")
|
| 27 |
-
st.stop()
|
| 28 |
-
|
| 29 |
-
llm = ChatOpenAI(model="gpt-5.4", temperature=0.3, max_tokens=1024)
|
| 30 |
-
|
| 31 |
-
# ======================== LOAD COMPONENTS ========================
|
| 32 |
-
@st.cache_resource
|
| 33 |
-
def load_rag():
|
| 34 |
-
try:
|
| 35 |
-
device = "cuda" if os.system("nvidia-smi > nul 2>&1") == 0 else "cpu"
|
| 36 |
-
embeddings = HuggingFaceEmbeddings(model_name="all-mpnet-base-v2", model_kwargs={"device": device})
|
| 37 |
-
import chromadb # type: ignore
|
| 38 |
-
from chromadb.config import Settings # type: ignore
|
| 39 |
-
client = chromadb.PersistentClient(path=DRIVE_DB_PATH, settings=Settings(allow_reset=True))
|
| 40 |
-
vectorstore = Chroma(client=client, collection_name="nvidia_annual_reports_2014_2025", embedding_function=embeddings)
|
| 41 |
-
st.sidebar.success("✅ RAG Loaded")
|
| 42 |
-
return vectorstore
|
| 43 |
-
except Exception as e:
|
| 44 |
-
st.sidebar.warning(f"RAG issue: {e}")
|
| 45 |
-
return None
|
| 46 |
-
|
| 47 |
-
vectorstore = load_rag()
|
| 48 |
-
|
| 49 |
-
df = pd.read_csv(CSV_PATH, skiprows=[1])
|
| 50 |
-
df['Date'] = pd.to_datetime(df['Date'])
|
| 51 |
-
df = df.sort_values('Date').reset_index(drop=True)
|
| 52 |
-
|
| 53 |
-
ddg_search = DuckDuckGoSearchRun()
|
| 54 |
-
|
| 55 |
-
# ======================== LANGGRAPH STATE ========================
|
| 56 |
-
class AgentState(TypedDict):
|
| 57 |
-
query: str
|
| 58 |
-
response: str
|
| 59 |
-
debug_log: Annotated[str, operator.add]
|
| 60 |
-
next_node: str
|
| 61 |
-
|
| 62 |
-
# ======================== NODES ========================
|
| 63 |
-
def router_node(state: AgentState) -> AgentState:
|
| 64 |
-
q = state["query"].lower()
|
| 65 |
-
if any(x in q for x in ["predict", "forecast", "price", "7 day", "next week", "tomorrow"]):
|
| 66 |
-
state["next_node"] = "trader"
|
| 67 |
-
state["debug_log"] = "🚦 Router → Trader\n"
|
| 68 |
-
elif any(x in q for x in ["news", "outlook", "latest", "blackwell", "risk", "revenue", "financial"]):
|
| 69 |
-
state["next_node"] = "researcher"
|
| 70 |
-
state["debug_log"] = "🚦 Router → Researcher\n"
|
| 71 |
-
else:
|
| 72 |
-
state["next_node"] = "general"
|
| 73 |
-
state["debug_log"] = "🚦 Router → General\n"
|
| 74 |
-
return state
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def researcher_node(state: AgentState) -> AgentState:
|
| 78 |
-
query = state["query"]
|
| 79 |
-
context = ""
|
| 80 |
-
if vectorstore:
|
| 81 |
-
docs = vectorstore.similarity_search(query, k=5)
|
| 82 |
-
context = "\n\n".join([d.page_content[:700] for d in docs])
|
| 83 |
-
|
| 84 |
-
news = ddg_search.run(f"NVIDIA {query} latest news OR earnings")[:800]
|
| 85 |
-
|
| 86 |
-
resp = llm.invoke([
|
| 87 |
-
SystemMessage(content="You are NVIDIA expert researcher."),
|
| 88 |
-
HumanMessage(content=f"Query: {query}\n\nRAG:\n{context}\n\nNews:\n{news}")
|
| 89 |
-
]).content
|
| 90 |
-
|
| 91 |
-
state["response"] = resp
|
| 92 |
-
state["debug_log"] += "🔎 Researcher completed\n"
|
| 93 |
-
return state
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def trader_node(state: AgentState) -> AgentState:
|
| 97 |
-
debug = "📈 Trader (Prophet) activated → "
|
| 98 |
-
try:
|
| 99 |
-
checkpoint = joblib.load(MODEL_PATH)
|
| 100 |
-
model = checkpoint['prophet_model']
|
| 101 |
-
last_close = checkpoint['last_close']
|
| 102 |
-
last_date = checkpoint['last_date']
|
| 103 |
-
|
| 104 |
-
# Create future dataframe
|
| 105 |
-
future = model.make_future_dataframe(periods=7, freq='B')
|
| 106 |
-
|
| 107 |
-
# Properly add regressors for ALL rows (critical fix)
|
| 108 |
-
future['MA7'] = df['Close'].rolling(7).mean().iloc[-1]
|
| 109 |
-
future['MA30'] = df['Close'].rolling(30).mean().iloc[-1]
|
| 110 |
-
future['Vol7'] = df['Close'].tail(7).std()
|
| 111 |
-
future['Volume_MA7'] = df['Volume'].tail(7).mean()
|
| 112 |
-
|
| 113 |
-
forecast = model.predict(future)
|
| 114 |
-
pred = forecast.tail(7)[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].copy()
|
| 115 |
-
pred['ds'] = pred['ds'].dt.strftime('%Y-%m-%d')
|
| 116 |
-
|
| 117 |
-
final_pred = pred['yhat'].iloc[-1]
|
| 118 |
-
upside = (final_pred / last_close - 1) * 100
|
| 119 |
-
|
| 120 |
-
if upside > 4.0:
|
| 121 |
-
trade_rec = f"🟢 **STRONG BUY** – Trade window: next 24-48 hours"
|
| 122 |
-
elif upside > 1.8:
|
| 123 |
-
trade_rec = f"🟡 **BUY** – Good entry in next 3 days"
|
| 124 |
-
elif upside < -2.5:
|
| 125 |
-
trade_rec = f"🔴 **SELL / CAUTION**"
|
| 126 |
-
else:
|
| 127 |
-
trade_rec = "⚪ **HOLD** – Monitor closely"
|
| 128 |
-
|
| 129 |
-
lines = [f"{row['ds']}: **${row['yhat']:.2f}** (range ${row['yhat_lower']:.2f}–${row['yhat_upper']:.2f})"
|
| 130 |
-
for _, row in pred.iterrows()]
|
| 131 |
-
|
| 132 |
-
state["response"] = f"""**🚀 NVIDIA 7-DAY FORECAST**
|
| 133 |
-
|
| 134 |
-
**Current Price:** ${last_close:.2f} → **Day 7 Expected:** **${final_pred:.2f}** ({upside:+.1f}%)
|
| 135 |
-
|
| 136 |
-
**Predictions:**
|
| 137 |
-
""" + "\n".join(lines) + f"""
|
| 138 |
-
|
| 139 |
-
**Trade Recommendation:**
|
| 140 |
-
{trade_rec}
|
| 141 |
-
|
| 142 |
-
*Backtested MAPE: {checkpoint.get('backtest_mape', 2.23):.2f}%*"""
|
| 143 |
-
|
| 144 |
-
except Exception as e:
|
| 145 |
-
state["response"] = f"Forecast error: {str(e)}"
|
| 146 |
-
|
| 147 |
-
state["debug_log"] += debug + "\n"
|
| 148 |
-
return state
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
def general_node(state: AgentState) -> AgentState:
|
| 152 |
-
resp = llm.invoke([
|
| 153 |
-
SystemMessage(content="You are a helpful NVIDIA assistant."),
|
| 154 |
-
HumanMessage(content=state["query"])
|
| 155 |
-
]).content
|
| 156 |
-
state["response"] = resp
|
| 157 |
-
state["debug_log"] += "💬 General Agent\n"
|
| 158 |
-
return state
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
# ======================== BUILD GRAPH ========================
|
| 162 |
-
workflow = StateGraph(AgentState)
|
| 163 |
-
workflow.add_node("router", router_node)
|
| 164 |
-
workflow.add_node("researcher", researcher_node)
|
| 165 |
-
workflow.add_node("trader", trader_node)
|
| 166 |
-
workflow.add_node("general", general_node)
|
| 167 |
-
|
| 168 |
-
workflow.set_entry_point("router")
|
| 169 |
-
workflow.add_conditional_edges("router", lambda x: x["next_node"],
|
| 170 |
-
{"researcher": "researcher", "trader": "trader", "general": "general"})
|
| 171 |
-
for node in ["researcher", "trader", "general"]:
|
| 172 |
-
workflow.add_edge(node, END)
|
| 173 |
-
|
| 174 |
-
app = workflow.compile()
|
| 175 |
-
|
| 176 |
-
# ======================== UI ========================
|
| 177 |
-
st.title("🚀 NVIDIA AI Assistant – Multi-Agent System")
|
| 178 |
-
st.caption("NTU DSAI Capstone | RAG + DuckDuckGo + Prophet ML")
|
| 179 |
-
|
| 180 |
-
if "messages" not in st.session_state:
|
| 181 |
-
st.session_state.messages = []
|
| 182 |
-
|
| 183 |
-
for msg in st.session_state.messages:
|
| 184 |
-
with st.chat_message(msg["role"]):
|
| 185 |
-
st.markdown(msg["content"])
|
| 186 |
-
|
| 187 |
-
if prompt := st.chat_input("Ask anything about NVIDIA..."):
|
| 188 |
-
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 189 |
-
with st.chat_message("user"):
|
| 190 |
-
st.markdown(prompt)
|
| 191 |
-
|
| 192 |
-
with st.chat_message("assistant"):
|
| 193 |
-
with st.spinner("Thinking..."):
|
| 194 |
-
result = app.invoke({
|
| 195 |
-
"query": prompt,
|
| 196 |
-
"response": "",
|
| 197 |
-
"debug_log": "",
|
| 198 |
-
"next_node": ""
|
| 199 |
-
})
|
| 200 |
-
answer = result.get("response", "Sorry, I couldn't generate an answer.")
|
| 201 |
-
log = result.get("debug_log", "")
|
| 202 |
-
|
| 203 |
-
st.markdown(answer)
|
| 204 |
-
with st.expander("🔍 Debug Trace"):
|
| 205 |
-
st.code(log)
|
| 206 |
-
|
| 207 |
-
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 208 |
-
|
| 209 |
-
# Sidebar
|
| 210 |
-
with st.sidebar:
|
| 211 |
-
st.success("✅ Prophet ML Model Loaded")
|
| 212 |
-
st.success("✅ RAG Loaded")
|
| 213 |
-
st.success("✅ DuckDuckGo Ready")
|
| 214 |
-
if st.button("Clear Chat"):
|
| 215 |
-
st.session_state.messages = []
|
| 216 |
-
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|