Spaces:
Sleeping

FINBOT-END / app /backend.py
PavanKumarD's picture
Update app/backend.py
e05372f verified
Raw History Blame Contribute Delete
10.3 kB
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."