File size: 3,221 Bytes
ca95ebe | 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 | import google.generativeai as genai
import pandas as pd
import os
import json
from data import df_all_cards
#handling intent classification for retrieval
def handle_query_classification(user_query):
genai.configure(api_key=os.environ.get("api_key_1"))
model1 = genai.GenerativeModel('gemini-2.0-flash')
prompt = f"""
You are a smart financial assistant.
### User's Query:
{user_query}
### Task:
Classify the user's intent into one of the following categories:
1. "retrieve" → If the user is asking for card suggestions, recommendations, or showing cards (e.g., "suggest a card", "need a travel card") OR if they mention their lifestyle, income, spending, or needs (e.g., travel, shopping, fuel, rewards, luxury).
2. "specific" → If the user is asking about a particular credit card by name (even if the word "card" is not used). Examples: "Tell me about HDFC Regalia", "Is SBI Elite good?".
3. "no_retrieval" → ONLY if the query is generic (e.g., “What is credit score?”), casual chit-chat (e.g., “Hi”), or doesn’t mention any lifestyle, financial needs, or specific card names.
Respond ONLY in the following JSON format:
If intent is "no_retrieval", you MUST include a helpful 'response' field.
If intent is "retrieve" or "specific", do NOT include any response or explanation.
Respond in this exact format:
{{
"intent": "retrieve" | "specific" | "no_retrieval",
"response": "Only include this if intent is 'no_retrieval'"
}}
"""
raw_response = model1.generate_content(prompt).text.strip()
# Clean any markdown formatting if present
if raw_response.startswith("```"):
raw_response = raw_response.strip("`").strip()
if raw_response.startswith("json"):
raw_response = raw_response[len("json"):].strip()
try:
parsed = json.loads(raw_response)
return parsed
except Exception as e:
print("JSON parsing error:", e)
print("Raw response from LLM:", raw_response)
raise
# result = handle_query_classification("Want to optimize my spending – travel often, premium hotels, and online shopping.")
# if result["intent"] == "no_retrieval":
# print(result['response'])
#passing the card mentioned in the user query
def find_matching_card(user_query):
lowered_query = user_query.lower()
for _, row in df_all_cards.iterrows():
if row["name"].lower() in lowered_query:
return row.to_dict()
return None
#for queries enquiring about a card
def generate_card_response_with_context(user_query, card_info):
genai.configure(api_key=os.environ.get("api_key_1"))
model1 = genai.GenerativeModel('gemini-2.0-flash')
prompt = f"""
You are a helpful financial assistant. A user has asked about a specific credit card.
Card Name: {card_info.get('name')}
Description: {card_info.get('description')}
User's Question: {user_query}
Please provide a concise, relevant answer using the above card context.
"""
response = model1.generate_content(prompt)
return response.text.strip()
|