Spaces:
Sleeping
Sleeping
Update app/main.py
Browse files110 unmodified lines111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194110 unmodified lines print(f"[QUERY LOG] Session: {session_id} | KB: {kb_type} | Input Tokens: {input_tokens} | Output Tokens: {output_tokens} | Time: {time_taken}s")
return JSONResponse(content={"response": answer})
@app.post("/voice")async def voice_endpoint( request: Request, query: str = Form(...), user_data_text: str = Form(""), session_id: str = Form(...), kb_type: str = Form("bank") # default to banking): start_time = time.time() chat_history = chat_sessions.get(session_id, []) combined_user_data = user_data_text.strip()
# Choose correct FAISS index & chunks if kb_type.lower() == "nse": index, chunks = nse_index, nse_chunks else: index, chunks = bank_index, bank_chunks
# --- Generate cleaner, voice-friendly response --- query_vec = embedding_model.encode([query]) _, indices = index.search(np.array(query_vec), 10) retrieved = [chunks[i] for i in indices[0] if i < len(chunks)] relevant_chunks = list(dict.fromkeys(retrieved)) context = "\n".join(relevant_chunks)
# Summarize long history summary_block = "" if chat_history and len(chat_history) > 6: summary_block = summarize_chat_history(chat_history)
# Build a voice-optimized prompt prompt = f"""You are FinBot, a calm and professional banking voice assistant.You are talking to the user through a voice interface.Your task is to answer clearly and naturally, using short sentences (2–4 lines).Do NOT use emojis, markdown, equations, or special characters.
Use the following context for your answer:<context>{context}</context>
Conversation summary:{summary_block}
User said: "{query}"
If the question is not financial or unrelated, respond in a friendly, natural tone.Example style:- "Your balance is around 20,000 rupees."- "I’ve transferred that successfully."- "Could you please repeat that?"
Keep tone polite, confident, and simple.Respond only with plain conversational text."""
try: client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=openrouter_keys[-1]) completion = client.chat.completions.create( model=MODEL_NAME, messages=[{"role": "user", "content": prompt}], extra_headers={"X-Title": "FinBotVoice"} ) answer = completion.choices[0].message.content.strip() except Exception as e: print("❌ Voice answer generation error:", e) answer = "Sorry, I couldn’t process that right now."
# --- Update chat history --- chat_history.append({"role": "user", "message": query}) chat_history.append({"role": "bot", "message": answer}) chat_sessions[session_id] = chat_history
# Log performance time_taken = round(time.time() - start_time, 2) print(f"[VOICE QUERY] Session: {session_id} | KB: {kb_type} | Time: {time_taken}s | Msg: {query[:40]}")
return JSONResponse(content={"response": answer})app/main.py+81