-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp2.py
More file actions
166 lines (145 loc) Β· 5.63 KB
/
Copy pathapp2.py
File metadata and controls
166 lines (145 loc) Β· 5.63 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
import os
import streamlit as st
import faiss
import pickle
import asyncio
import aiohttp
from huggingface_hub import hf_hub_download
from sentence_transformers import SentenceTransformer
import feedparser
import datetime
import numpy as np
# -------------------
# Streamlit config
# -------------------
st.set_page_config(page_title="π Agentic Financial RAG", layout="wide")
# -------------------
# Load FAISS index + metadata
# -------------------
@st.cache_resource
def load_finance_index():
faiss_path = hf_hub_download(
repo_id="krishnasimha/finance_data",
filename="financial_phrasebank_index.faiss",
repo_type="dataset"
)
pkl_path = hf_hub_download(
repo_id="krishnasimha/finance_data",
filename="financial_phrasebank_metadata.pkl",
repo_type="dataset"
)
index = faiss.read_index(faiss_path)
with open(pkl_path, "rb") as f:
metadata = pickle.load(f)
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
return index, metadata, embed_model
index, metadata, embed_model = load_finance_index()
# -------------------
# FAISS retrieval
# -------------------
def retrieve_docs(query, k=3):
query_emb = embed_model.encode([query], convert_to_numpy=True)
D, I = index.search(query_emb, k)
retrieved_texts = [metadata["texts"][i] for i in I[0]]
retrieved_sources = [metadata["sources"][i] for i in I[0]]
return retrieved_texts, retrieved_sources
# -------------------
# Async Together API call
# -------------------
async def async_together_chat(messages):
url = "https://api.together.xyz/v1/chat/completions"
headers = {
"Authorization": f"Bearer {os.environ['TOGETHER_API_KEY']}",
"Content-Type": "application/json",
}
payload = {
"model": "deepseek-ai/DeepSeek-V3",
"messages": messages,
}
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=payload) as resp:
result = await resp.json()
return result["choices"][0]["message"]["content"]
# -------------------
# RSS Financial News
# -------------------
RSS_URL = "https://news.google.com/rss/search?q=finance+stock+market&hl=en-IN&gl=IN&ceid=IN:en"
async def fetch_rss_url(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()
def get_financial_news():
raw_xml = asyncio.run(fetch_rss_url(RSS_URL))
feed = feedparser.parse(raw_xml)
articles = []
for entry in feed.entries[:5]:
articles.append({
"title": entry.title,
"link": entry.link,
"published": entry.published
})
return articles
# -------------------
# Session State: Chats
# -------------------
if "chats" not in st.session_state:
st.session_state.chats = {}
if "current_chat" not in st.session_state:
st.session_state.current_chat = "New Chat 1"
st.session_state.chats["New Chat 1"] = [
{"role": "system", "content": "You are a helpful financial assistant."}
]
# -------------------
# Sidebar: Chat Manager
# -------------------
st.sidebar.header("Chat Manager")
if st.sidebar.button("β New Chat"):
chat_count = len(st.session_state.chats) + 1
new_chat_name = f"New Chat {chat_count}"
st.session_state.chats[new_chat_name] = [
{"role": "system", "content": "You are a helpful financial assistant."}
]
st.session_state.current_chat = new_chat_name
chat_list = list(st.session_state.chats.keys())
selected_chat = st.sidebar.selectbox("Your chats:", chat_list, index=chat_list.index(st.session_state.current_chat))
st.session_state.current_chat = selected_chat
new_name = st.sidebar.text_input("Rename Chat:", st.session_state.current_chat)
if new_name and new_name != st.session_state.current_chat:
if new_name not in st.session_state.chats:
st.session_state.chats[new_name] = st.session_state.chats.pop(st.session_state.current_chat)
st.session_state.current_chat = new_name
# -------------------
# Streamlit UI
# -------------------
st.title(f"π {st.session_state.current_chat}")
st.subheader("π° Latest Financial News")
news_articles = get_financial_news()
for art in news_articles:
st.markdown(f"**{art['title']}** \n[Read more]({art['link']}) \n*Published: {art['published']}*")
st.write("---")
user_query = st.text_input("Ask me about finance, stocks, or banking:")
if user_query:
with st.spinner("Retrieving financial context..."):
docs, sources = retrieve_docs(user_query)
context_str = "\n".join(docs)
user_message = {
"role": "user",
"content": f"Answer the query based on the context below:\n\n{context_str}\n\nQuestion: {user_query}"
}
st.session_state.chats[st.session_state.current_chat].append(user_message)
answer = asyncio.run(async_together_chat(st.session_state.chats[st.session_state.current_chat]))
st.session_state.chats[st.session_state.current_chat].append({"role": "assistant", "content": answer})
st.write("### π‘ Answer")
st.write(answer)
st.write("### π Sources")
for src in sources:
st.write(f"- {src}")
# -------------------
# Display chat history
# -------------------
st.subheader("π¬ Chat History")
for msg in st.session_state.chats[st.session_state.current_chat]:
if msg["role"] == "user":
st.write(f"π§ **You:** {msg['content']}")
elif msg["role"] == "assistant":
st.write(f"π€ **Bot:** {msg['content']}")