Sulaiman8/Credit-Card-Recommender-Knowledge-graph-implementation
0
1import google.generativeai as genai2import pandas as pd3import os4import json5from data import df_all_cards6 7#handling intent classification for retrieval8def handle_query_classification(user_query):9 genai.configure(api_key=os.environ.get("api_key_1")) 10 model1 = genai.GenerativeModel('gemini-2.0-flash')11 prompt = f"""12 You are a smart financial assistant.13 14 ### User's Query:15 {user_query}16 17 ### Task:18 Classify the user's intent into one of the following categories:19 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).20 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?".21 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.22 23 24 Respond ONLY in the following JSON format:25 If intent is "no_retrieval", you MUST include a helpful 'response' field.26 If intent is "retrieve" or "specific", do NOT include any response or explanation.27 28 Respond in this exact format:29 {{30 "intent": "retrieve" | "specific" | "no_retrieval",31 "response": "Only include this if intent is 'no_retrieval'"32 }}33 34 """35 36 raw_response = model1.generate_content(prompt).text.strip()37 38 # Clean any markdown formatting if present39 if raw_response.startswith("```"):40 raw_response = raw_response.strip("`").strip()41 if raw_response.startswith("json"):42 raw_response = raw_response[len("json"):].strip()43 44 try:45 parsed = json.loads(raw_response)46 return parsed47 except Exception as e:48 print("JSON parsing error:", e)49 print("Raw response from LLM:", raw_response)50 raise51# result = handle_query_classification("Want to optimize my spending – travel often, premium hotels, and online shopping.")52# if result["intent"] == "no_retrieval":53# print(result['response'])54 55#passing the card mentioned in the user query56def find_matching_card(user_query):57 lowered_query = user_query.lower()58 for _, row in df_all_cards.iterrows():59 if row["name"].lower() in lowered_query:60 return row.to_dict()61 return None62 63 64#for queries enquiring about a card65def generate_card_response_with_context(user_query, card_info):66 genai.configure(api_key=os.environ.get("api_key_1")) 67 model1 = genai.GenerativeModel('gemini-2.0-flash')68 prompt = f"""69You are a helpful financial assistant. A user has asked about a specific credit card.70 71Card Name: {card_info.get('name')}72Description: {card_info.get('description')}73 74User's Question: {user_query}75 76Please provide a concise, relevant answer using the above card context.77"""78 response = model1.generate_content(prompt)79 return response.text.strip()80 81 