Spaces:
Sleeping
Sleeping
Update app/backend.py
Browse files198 unmodified lines199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271198 unmodified linesexcept 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 Contextquery_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 = 6if 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 promptprompt = build_prompt_voice(query, context, summary_block)# ✅ Try each API keyindices_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 = idxreturn 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."198 unmodified lines199200201202198 unmodified linesexcept Exception as e:print(f"❌ Failed with Key #{idx+1}: {e}")traceback.print_exc()return "❗ All API keys failed. Please try later."
app/backend.py+1-70