Spaces:
Sleeping
Sleeping
File size: 10,254 Bytes
eae71a4 5204218 eae71a4 da9aff2 5204218 6eb1f91 eae71a4 66ccb37 5204218 eae71a4 da9aff2 5204218 da9aff2 5204218 eae71a4 5204218 da9aff2 5204218 da9aff2 5204218 da9aff2 5204218 da9aff2 eae71a4 da9aff2 5204218 eae71a4 5204218 da9aff2 5204218 da9aff2 5204218 da9aff2 5204218 da9aff2 5204218 da9aff2 eae71a4 5204218 eae71a4 da9aff2 eae71a4 1580683 5204218 1580683 5204218 eae71a4 5204218 eae71a4 5204218 eae71a4 1580683 eae71a4 5204218 eae71a4 5204218 e05372f | 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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | import os
import fitz # PyMuPDF
import faiss
import numpy as np
import traceback
from dotenv import load_dotenv
from openai import OpenAI
from sentence_transformers import SentenceTransformer
# Load environment variables
load_dotenv()
current_api_index = 0
# ✅ Load multiple OpenRouter API keys from env
openrouter_keys = os.getenv("OPENROUTER_API_KEYS", "").split(",")
# ✅ Preferred model
MODEL_NAME = "z-ai/glm-4.5-air:free"
# ✅ Embedding model
embedding_model = SentenceTransformer("models/all-MiniLM-L6-v2")
# -------- PDF Utils --------
def extract_text_from_pdf(pdf_path):
doc = fitz.open(pdf_path)
return " ".join([page.get_text() for page in doc])
def build_faiss_index(text, chunk_size=1000, overlap=150):
chunks, i = [], 0
while i < len(text):
chunk = text[i:i + chunk_size]
chunks.append(chunk)
i += chunk_size - overlap
embeddings = embedding_model.encode(chunks)
index = faiss.IndexFlatL2(embeddings.shape[1])
index.add(np.array(embeddings))
return index, chunks
# -------- Chat History Summarizer --------
def summarize_chat_history(chat_history, model=MODEL_NAME):
if not chat_history:
return ""
history_text = "\n".join([f"{'User' if h['role'] == 'user' else 'FinBot'}: {h['message']}" for h in chat_history])
prompt = f"""
Summarize the following conversation between a user and FinBot in 2-3 lines.
<conversation>
{history_text}
</conversation>
Summary:
"""
try:
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=openrouter_keys[-1])
completion = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
extra_headers={"HTTP-Referer": "http://localhost:8000", "X-Title": "FinBot"}
)
return completion.choices[0].message.content.strip()
except Exception as e:
print("⚠️ Failed to summarize:", e)
return ""
# -------- Prompt Builders --------
def build_prompt_bank(query, context, user_data_text="", summary_block=""):
system_prompt = """You are a helpful assistant. Automatically detect the language of the user's question and respond in the same language."""
user_data_block = f"\n<user_data>\n{user_data_text.strip()}\n</user_data>" if user_data_text else ""
return f"""
ou are FinBot, a helpful and knowledgeable AI assistant designed to assist users with financial banking queries.
You're also capable of answering general questions like greetings, date, time, or friendly comments in a conversational tone and properly explain to the user your response.
You should act proficional as well as a close friend whom the user has known for a long time.
Your responsibilities:
- Use <context> and <user_data> to answer financial questions precisely.
- Answer general questions like a friend explaining everyting.
- Do not hallucinate information.
- Use some 3-7 respectful sentences per response that makes good sense.
- more context info for general questions.
- do not mention the thinking process just answer the question.
Format responses with:
- add proper heading and side heading formating and tables and equations properly
- Use headings (##, ###) for sections.
- Use bullet points (-) for lists, no nested lists inside table cells.
- Use **bold** to highlight important terms.
- Do not include raw <br> or HTML—just Markdown syntax.
- give proper equations using LaTeX syntax ($...$ or $$...$$)
Respond in Markdown format.
<system_prompt>
{system_prompt}
</system_prompt>
<chat_history>
{summary_block}
</chat_history>
<context>
{context}
</context>
{user_data_block}
<question>
{query}
</question>
"""
def build_prompt_nse(query, context, summary_block=""):
system_prompt = """You are a helpful assistant. Automatically detect the language of the user's question and respond in the same language."""
return f"""
You are FinBot NSE, a professional and knowledgeable AI assistant designed to interpret and answer questions from NSE circulars, SEBI regulations, and financial compliance documents.
You must always maintain a formal, factual, and report-like tone.
Your responsibilities:
- Use <context> to answer queries precisely.
- Do not hallucinate or assume information outside <context>.
- Summarize circulars, clauses, rules, and highlight **dates, figures, percentages** where available.
- Answer in **3–7 formal, well-structured sentences** like a compliance officer would.
- If context is insufficient, politely state that information is not available.
- Keep tone **professional and factual**, not casual.
Format responses with:
- Use **Markdown headings (##, ###)** for sections.
- Use bullet points (-) for key highlights.
- Use **bold** for important terms.
- Use tables where needed (dates, figures, clauses).
- Give equations or percentages in proper LaTeX ($...$ or $$...$$).
- Never include raw <br> or HTML—only Markdown.
Respond in Markdown format.
<system_prompt>
{system_prompt}
</system_prompt>
<chat_history>
{summary_block}
</chat_history>
<context>
{context}
</context>
{user_data_block}
<question>
{query}
</question>
"""
# -------- Answer Generator --------
def generate_answer(query, index, chunks, chat_history=None, user_data_text="", top_k=10, kb_type="bank"):
global current_api_index
query_vec = embedding_model.encode([query])
_, indices = index.search(np.array(query_vec), top_k)
retrieved = [chunks[i] for i in indices[0] if i < len(chunks)]
relevant_chunks = list(dict.fromkeys(retrieved))
if not relevant_chunks:
return "⚠️ No relevant context found. Please try again with a different query."
context = "\n".join(relevant_chunks)
# Smart history
conversation_summary = ""
MAX_HISTORY_TURNS = 6
if chat_history and len(chat_history) > MAX_HISTORY_TURNS:
conversation_summary = summarize_chat_history(chat_history)
chat_history.clear()
summary_block = f"<chat_summary>\n{conversation_summary}\n</chat_summary>" if conversation_summary else ""
# Select prompt
if kb_type.lower() == "nse":
prompt = build_prompt_nse(query, context, user_data_text, summary_block)
else:
prompt = build_prompt_bank(query, context, user_data_text, summary_block)
# Retry keys
indices_to_try = [current_api_index] + [i for i in range(len(openrouter_keys)) if i != current_api_index]
for idx in indices_to_try:
api_key = openrouter_keys[idx].strip()
try:
print(f"🔑 Trying API Key #{idx + 1}")
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key)
completion = client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "user", "content": prompt}],
extra_headers={"HTTP-Referer": "http://localhost:8000", "X-Title": "FinBot"}
)
current_api_index = idx
return completion.choices[0].message.content.strip()
except Exception as e:
print(f"❌ Failed with Key #{idx+1}: {e}")
traceback.print_exc()
return "❗ All API keys failed. Please try later."
# -------- Voice Prompt Builder --------
def build_prompt_voice(query, context, summary_block=""):
system_prompt = """You are a calm and professional voice assistant that responds naturally in speech form, not in text formatting."""
return f"""
You are FinBot Voice, a friendly and natural-sounding AI banking assistant.
You are speaking through a voice interface, so keep responses short, polite, and conversational.
Avoid technical jargon or formal tone — speak like a real assistant.
Rules:
- Use only plain text (no markdown, no symbols, no equations, no emojis).
- Keep each answer 1–3 sentences long.
- If unclear, ask the user politely to repeat.
- If answering financial or banking queries, be confident and clear.
- If it's small talk or greeting, reply warmly but concisely.
- Do not add extra formatting, punctuation, or special characters.
<context>
{context}
</context>
Conversation summary:
{summary_block}
User said: "{query}"
Respond naturally in plain spoken English.
"""
# -------- Voice Answer Generator --------
def generate_voice_response(query, index, chunks, chat_history=None, user_data_text="", top_k=10):
"""Generate a short, conversational voice-optimized response"""
global current_api_index
# ✅ Encode & Retrieve Context
query_vec = embedding_model.encode([query])
_, indices = index.search(np.array(query_vec), top_k)
retrieved = [chunks[i] for i in indices[0] if i < len(chunks)]
relevant_chunks = list(dict.fromkeys(retrieved))
if not relevant_chunks:
return "I couldn’t find related information. Could you please repeat?"
context = "\n".join(relevant_chunks)
# ✅ Summarize history (optional)
conversation_summary = ""
MAX_HISTORY_TURNS = 6
if chat_history and len(chat_history) > MAX_HISTORY_TURNS:
conversation_summary = summarize_chat_history(chat_history)
chat_history.clear()
summary_block = f"<chat_summary>\n{conversation_summary}\n</chat_summary>" if conversation_summary else ""
# ✅ Build voice-specific prompt
prompt = build_prompt_voice(query, context, summary_block)
# ✅ Try each API key
indices_to_try = [current_api_index] + [i for i in range(len(openrouter_keys)) if i != current_api_index]
for idx in indices_to_try:
api_key = openrouter_keys[idx].strip()
try:
print(f"🔊 Using API Key #{idx + 1} for voice generation")
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key)
completion = client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "user", "content": prompt}],
extra_headers={"X-Title": "FinBotVoice"}
)
current_api_index = idx
return completion.choices[0].message.content.strip()
except Exception as e:
print(f"❌ Voice generation failed with Key #{idx+1}: {e}")
traceback.print_exc()
return "I’m having trouble responding right now. Please try again later."
|