Sulaiman8 commited on
Commit
9026943
·
verified ·
1 Parent(s): a7eaab8

Update data.py

Browse files
Files changed (1) hide show
  1. data.py +204 -204
data.py CHANGED
@@ -1,205 +1,205 @@
1
- import threading
2
- import logging
3
- import os
4
- import pandas as pd
5
- from typing import Dict
6
- import psutil
7
- import google.generativeai as genai
8
- from langchain_google_genai import ChatGoogleGenerativeAI
9
- from langchain_community.chat_models import ChatOpenAI
10
- from neo4j import GraphDatabase
11
- from datetime import datetime
12
- import sys
13
- import time
14
-
15
- # accessing and defining the llm served in the cluster
16
- from langchain_community.chat_models import ChatOpenAI
17
-
18
- NGROK_URL = "https://636e8b23c1fd.ngrok-free.app"
19
- VLLM_MODEL_NAME = "hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4"
20
-
21
- llm1 = ChatOpenAI(
22
- openai_api_key="EMPTY",
23
- openai_api_base=f"{NGROK_URL}/v1",
24
- model_name=VLLM_MODEL_NAME,
25
- temperature=0.0,
26
- )
27
-
28
- # graph db credentials and gemini api key management
29
-
30
- NEO4J_URI = "neo4j+s://83c91252.databases.neo4j.io"
31
- NEO4J_USER = "neo4j"
32
- NEO4J_PASS = "TKUo104Fqm6BtDNJ2eeb6RRM8xIBS80kdJKLOFv_CkI"
33
-
34
- logging.basicConfig(
35
- level=logging.INFO,
36
- format='%(asctime)s - %(levelname)s - %(message)s',
37
- handlers=[logging.StreamHandler()]
38
- )
39
- logger = logging.getLogger(__name__)
40
-
41
- API_KEYS = [
42
- "AIzaSyC4qW9fQAbiCS30xY-Tq086AoRB8lUfxes",
43
- "AIzaSyAxa91t80DFbtZG0Z8pyHlGG2X0v-sYSRc",
44
- "AIzaSyDGc7l82E1sa4GarTfGiTXC6dLD7Crk8oo",
45
- "AIzaSyC463t1T7I6AkKFt9z0eP85KpBVJsGljHc",
46
- "AIzaSyAHoi9xbYAThtjXlyF_IKFtruoWYoUCjJQ"
47
- ]
48
-
49
-
50
- model_key_counters: Dict[str, int] = {
51
- "gemini-2.5-flash": 0,
52
- "gemini-2.0-flash-lite": 0,
53
- "gemini-2.0-flash": 0,
54
- "gemini-2.5-flash-lite-preview-06-17": 0,
55
- "models/embedding-001": 0,
56
- "models/text-embedding-004": 0
57
- }
58
- counter_lock = threading.Lock()
59
-
60
- # Usage and Error Tracking
61
- key_usage: Dict[tuple, int] = {(model, key): 0 for model in model_key_counters for key in API_KEYS}
62
- key_errors: Dict[tuple, int] = {(model, key): 0 for model in model_key_counters for key in API_KEYS}
63
- MAX_ERRORS_PER_KEY = 50
64
-
65
- # Lock for genai API calls
66
- genai_lock = threading.Lock()
67
-
68
- # Chat Model Cache
69
- model_cache: Dict[str, ChatGoogleGenerativeAI | genai.GenerativeModel] = {}
70
-
71
- def select_key_for_model(model_name: str) -> str:
72
- """Select the next API key for the model using round-robin, skipping unreliable keys."""
73
- with counter_lock:
74
- available_keys = [k for k in API_KEYS if key_errors[(model_name, k)] < MAX_ERRORS_PER_KEY]
75
- if not available_keys:
76
- logger.warning(f"All keys for {model_name} exhausted. Resetting errors.")
77
- for k in API_KEYS:
78
- key_errors[(model_name, k)] = 0
79
- available_keys = API_KEYS
80
- index = model_key_counters[model_name] % len(available_keys)
81
- selected_key = available_keys[index]
82
- model_key_counters[model_name] = (index + 1) % len(available_keys)
83
- key_usage[(model_name, selected_key)] += 1
84
- logger.info(f"Key {selected_key[:10]}... selected for {model_name}, usage: {key_usage[(model_name, selected_key)]}")
85
- return selected_key
86
-
87
- def get_model(model_name: str, use_chat: bool) -> ChatGoogleGenerativeAI | genai.GenerativeModel:
88
- """Get or create a ChatGoogleGenerativeAI model with a selected key."""
89
- key = select_key_for_model(model_name)
90
- cache_key = f"{model_name}_{key}_{'chat' if use_chat else 'genai'}"
91
- if cache_key not in model_cache:
92
- try:
93
- genai.configure(api_key=key)
94
- if use_chat:
95
- model = ChatGoogleGenerativeAI(
96
- model=model_name,
97
- temperature=0.7,
98
- google_api_key=key
99
- )
100
- else:
101
- model = genai.GenerativeModel(model_name)
102
-
103
- model_cache[cache_key] = model
104
- logger.info(f"Created Model for {model_name} with key {key[:10]}...")
105
- except Exception as e:
106
- key_errors[(model_name, key)] += 1
107
- logger.error(f"Error creating model for {model_name}: {str(e)}")
108
- if key_errors[(model_name, key)] >= MAX_ERRORS_PER_KEY:
109
- logger.warning(f"Key {key[:10]}... unreliable for {model_name}")
110
- return get_model(model_name) # Retry
111
- return model_cache[cache_key]
112
-
113
- def call_genai_embedding_api(model_name: str, *args, **kwargs):
114
- """Call genai API with selected key, using a lock."""
115
- key = select_key_for_model(model_name)
116
- with genai_lock:
117
- try:
118
- genai.configure(api_key=key)
119
- return genai.embed_content(*args, **kwargs)
120
- except Exception as e:
121
- key_errors[(model_name, key)] += 1
122
- logger.error(f"API call failed for {model_name}: {str(e)}")
123
- if key_errors[(model_name, key)] >= MAX_ERRORS_PER_KEY:
124
- logger.warning(f"Key {key[:10]}... unreliable for {model_name}")
125
- raise
126
-
127
- def reset_key_metrics():
128
- """Reset usage and error counts for all (model, key) pairs."""
129
- with counter_lock:
130
- for (model, key) in key_usage:
131
- key_usage[(model, key)] = 0
132
- key_errors[(model, key)] = 0
133
- logger.info("Reset all API key usage and error counts for all models.")
134
-
135
- # Schedule metrics reset every 8 hours
136
- def schedule_reset():
137
- while True:
138
- try:
139
- time.sleep(8 * 60 * 60) # Reset every 8 hours
140
- reset_key_metrics()
141
- except Exception as e:
142
- logging.error(f"Error in reset_key_metrics: {e}")
143
-
144
- # CPU monitoring every 20 seconds
145
- def monitor_cpu():
146
- while True:
147
- try:
148
- cpu_usage = psutil.cpu_percent(interval=20) # Combine interval with sleep
149
- logging.info(f"CPU Utilization: {cpu_usage}%")
150
- except Exception as e:
151
- logging.error(f"Error in CPU monitoring: {e}")
152
-
153
- # Start threads
154
- reset_thread = threading.Thread(target=schedule_reset, daemon=True)
155
- monitor_thread = threading.Thread(target=monitor_cpu, daemon=True)
156
- reset_thread.start()
157
- monitor_thread.start()
158
-
159
- genai.configure(api_key=os.getenv("GEMINI_API_KEY_1"))
160
-
161
- _driver = None
162
- def get_driver():
163
- global _driver
164
- if _driver is None:
165
- _driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER,NEO4J_PASS))
166
- return _driver
167
-
168
-
169
-
170
- def debug_print(category, message):
171
- """
172
- Print a debug message with timestamp and category, flushed immediately.
173
-
174
- Args:
175
- category (str): Category of the debug message (e.g., NODE, AGENT, TOOL)
176
- message (str): The message to print
177
- """
178
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
179
- print(f"[{timestamp}] [{category}] {message}", flush=True, file=sys.stdout)
180
-
181
-
182
- # --- Data Loading ---
183
- eligibility_df = pd.read_csv("cards_eligibility_updated.csv")
184
- df = pd.read_csv("credit_card_data_updated.csv")
185
- # print(df.head())
186
- card_descriptions = dict(zip(df["name"], df["description"]))
187
- features = ['Fuel Surcharge Waiver', 'Insurance', 'Shopping Benefits', 'Airport Lounge Access', 'Co-Branded', 'Daily Spends (Grocery)', 'Dining Benefits', 'Domestic Travel Benefits', 'Entertainment', 'General Reward Points', 'Movie Benefits', 'Rupay Network Support', 'Student', 'UPI Transaction Support', 'Welcome Bonus', 'International Travel Benefits', 'premium', 'Flight Discounts', 'Hotel Benefits', 'Travel Benefits', 'Railway Benefits', 'Railway Lounge', 'Utility', 'Beginners (Entry Level)', 'E-commerce Platform Benefits', 'Air Miles', 'Jewellery Spends', 'Concierge Services', 'Food Delivery Benefits', 'Lifestyle & Luxury Perks', 'Spa Access Benefits', 'Golf Access & Perks', 'Super Premium', 'Frequent Flyer Benefits', 'Health Benefits', 'Rent Payment Benefits', 'Education', 'Lifetime Free', 'Roadside Assistance', 'EMI Conversion Options', 'No Forex Markup Fee', 'Secured FD Based', 'Cashback', 'Fuel Benefits', 'Business']
188
- df_all_cards = pd.read_csv("credit_card_data_updated.csv")
189
- all_card_names = df_all_cards["name"].tolist()
190
- all_card_lookup = dict(zip(df_all_cards["name"], df_all_cards["description"]))
191
-
192
-
193
- # --- Eligibility Lookup (now global) ---
194
- eligibility_lookup = {}
195
- for _, row in eligibility_df.iterrows():
196
- name = row["Name"].strip()
197
- eligibility_lookup[name] = {
198
- "bank": row["Bank"],
199
- "age_range": f"{row['Minimum Age']} to {row['Maximum Age']}",
200
- "income": f"{row['Minimum Income (LPA)']} LPA",
201
- "credit_score": row["Minimum Credit Score"],
202
- "joining_fee": row["Joining fee"],
203
- "annual_fee": row["Annual fee"],
204
- "issuer_link": row.get("Issuer Link", "").strip()
205
  }
 
1
+ import threading
2
+ import logging
3
+ import os
4
+ import pandas as pd
5
+ from typing import Dict
6
+ import psutil
7
+ import google.generativeai as genai
8
+ from langchain_google_genai import ChatGoogleGenerativeAI
9
+ from langchain_openai import ChatOpenAI
10
+ from neo4j import GraphDatabase
11
+ from datetime import datetime
12
+ import sys
13
+ import time
14
+
15
+ # accessing and defining the llm served in the cluster
16
+ from langchain_community.chat_models import ChatOpenAI
17
+
18
+ NGROK_URL = "https://636e8b23c1fd.ngrok-free.app"
19
+ VLLM_MODEL_NAME = "hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4"
20
+
21
+ llm1 = ChatOpenAI(
22
+ openai_api_key="EMPTY",
23
+ openai_api_base=f"{NGROK_URL}/v1",
24
+ model_name=VLLM_MODEL_NAME,
25
+ temperature=0.0,
26
+ )
27
+
28
+ # graph db credentials and gemini api key management
29
+
30
+ NEO4J_URI = "neo4j+s://83c91252.databases.neo4j.io"
31
+ NEO4J_USER = "neo4j"
32
+ NEO4J_PASS = "TKUo104Fqm6BtDNJ2eeb6RRM8xIBS80kdJKLOFv_CkI"
33
+
34
+ logging.basicConfig(
35
+ level=logging.INFO,
36
+ format='%(asctime)s - %(levelname)s - %(message)s',
37
+ handlers=[logging.StreamHandler()]
38
+ )
39
+ logger = logging.getLogger(__name__)
40
+
41
+ API_KEYS = [
42
+ "AIzaSyC4qW9fQAbiCS30xY-Tq086AoRB8lUfxes",
43
+ "AIzaSyAxa91t80DFbtZG0Z8pyHlGG2X0v-sYSRc",
44
+ "AIzaSyDGc7l82E1sa4GarTfGiTXC6dLD7Crk8oo",
45
+ "AIzaSyC463t1T7I6AkKFt9z0eP85KpBVJsGljHc",
46
+ "AIzaSyAHoi9xbYAThtjXlyF_IKFtruoWYoUCjJQ"
47
+ ]
48
+
49
+
50
+ model_key_counters: Dict[str, int] = {
51
+ "gemini-2.5-flash": 0,
52
+ "gemini-2.0-flash-lite": 0,
53
+ "gemini-2.0-flash": 0,
54
+ "gemini-2.5-flash-lite-preview-06-17": 0,
55
+ "models/embedding-001": 0,
56
+ "models/text-embedding-004": 0
57
+ }
58
+ counter_lock = threading.Lock()
59
+
60
+ # Usage and Error Tracking
61
+ key_usage: Dict[tuple, int] = {(model, key): 0 for model in model_key_counters for key in API_KEYS}
62
+ key_errors: Dict[tuple, int] = {(model, key): 0 for model in model_key_counters for key in API_KEYS}
63
+ MAX_ERRORS_PER_KEY = 50
64
+
65
+ # Lock for genai API calls
66
+ genai_lock = threading.Lock()
67
+
68
+ # Chat Model Cache
69
+ model_cache: Dict[str, ChatGoogleGenerativeAI | genai.GenerativeModel] = {}
70
+
71
+ def select_key_for_model(model_name: str) -> str:
72
+ """Select the next API key for the model using round-robin, skipping unreliable keys."""
73
+ with counter_lock:
74
+ available_keys = [k for k in API_KEYS if key_errors[(model_name, k)] < MAX_ERRORS_PER_KEY]
75
+ if not available_keys:
76
+ logger.warning(f"All keys for {model_name} exhausted. Resetting errors.")
77
+ for k in API_KEYS:
78
+ key_errors[(model_name, k)] = 0
79
+ available_keys = API_KEYS
80
+ index = model_key_counters[model_name] % len(available_keys)
81
+ selected_key = available_keys[index]
82
+ model_key_counters[model_name] = (index + 1) % len(available_keys)
83
+ key_usage[(model_name, selected_key)] += 1
84
+ logger.info(f"Key {selected_key[:10]}... selected for {model_name}, usage: {key_usage[(model_name, selected_key)]}")
85
+ return selected_key
86
+
87
+ def get_model(model_name: str, use_chat: bool) -> ChatGoogleGenerativeAI | genai.GenerativeModel:
88
+ """Get or create a ChatGoogleGenerativeAI model with a selected key."""
89
+ key = select_key_for_model(model_name)
90
+ cache_key = f"{model_name}_{key}_{'chat' if use_chat else 'genai'}"
91
+ if cache_key not in model_cache:
92
+ try:
93
+ genai.configure(api_key=key)
94
+ if use_chat:
95
+ model = ChatGoogleGenerativeAI(
96
+ model=model_name,
97
+ temperature=0.7,
98
+ google_api_key=key
99
+ )
100
+ else:
101
+ model = genai.GenerativeModel(model_name)
102
+
103
+ model_cache[cache_key] = model
104
+ logger.info(f"Created Model for {model_name} with key {key[:10]}...")
105
+ except Exception as e:
106
+ key_errors[(model_name, key)] += 1
107
+ logger.error(f"Error creating model for {model_name}: {str(e)}")
108
+ if key_errors[(model_name, key)] >= MAX_ERRORS_PER_KEY:
109
+ logger.warning(f"Key {key[:10]}... unreliable for {model_name}")
110
+ return get_model(model_name) # Retry
111
+ return model_cache[cache_key]
112
+
113
+ def call_genai_embedding_api(model_name: str, *args, **kwargs):
114
+ """Call genai API with selected key, using a lock."""
115
+ key = select_key_for_model(model_name)
116
+ with genai_lock:
117
+ try:
118
+ genai.configure(api_key=key)
119
+ return genai.embed_content(*args, **kwargs)
120
+ except Exception as e:
121
+ key_errors[(model_name, key)] += 1
122
+ logger.error(f"API call failed for {model_name}: {str(e)}")
123
+ if key_errors[(model_name, key)] >= MAX_ERRORS_PER_KEY:
124
+ logger.warning(f"Key {key[:10]}... unreliable for {model_name}")
125
+ raise
126
+
127
+ def reset_key_metrics():
128
+ """Reset usage and error counts for all (model, key) pairs."""
129
+ with counter_lock:
130
+ for (model, key) in key_usage:
131
+ key_usage[(model, key)] = 0
132
+ key_errors[(model, key)] = 0
133
+ logger.info("Reset all API key usage and error counts for all models.")
134
+
135
+ # Schedule metrics reset every 8 hours
136
+ def schedule_reset():
137
+ while True:
138
+ try:
139
+ time.sleep(8 * 60 * 60) # Reset every 8 hours
140
+ reset_key_metrics()
141
+ except Exception as e:
142
+ logging.error(f"Error in reset_key_metrics: {e}")
143
+
144
+ # CPU monitoring every 20 seconds
145
+ def monitor_cpu():
146
+ while True:
147
+ try:
148
+ cpu_usage = psutil.cpu_percent(interval=20) # Combine interval with sleep
149
+ logging.info(f"CPU Utilization: {cpu_usage}%")
150
+ except Exception as e:
151
+ logging.error(f"Error in CPU monitoring: {e}")
152
+
153
+ # Start threads
154
+ reset_thread = threading.Thread(target=schedule_reset, daemon=True)
155
+ monitor_thread = threading.Thread(target=monitor_cpu, daemon=True)
156
+ reset_thread.start()
157
+ monitor_thread.start()
158
+
159
+ genai.configure(api_key=os.getenv("GEMINI_API_KEY_1"))
160
+
161
+ _driver = None
162
+ def get_driver():
163
+ global _driver
164
+ if _driver is None:
165
+ _driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER,NEO4J_PASS))
166
+ return _driver
167
+
168
+
169
+
170
+ def debug_print(category, message):
171
+ """
172
+ Print a debug message with timestamp and category, flushed immediately.
173
+
174
+ Args:
175
+ category (str): Category of the debug message (e.g., NODE, AGENT, TOOL)
176
+ message (str): The message to print
177
+ """
178
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
179
+ print(f"[{timestamp}] [{category}] {message}", flush=True, file=sys.stdout)
180
+
181
+
182
+ # --- Data Loading ---
183
+ eligibility_df = pd.read_csv("cards_eligibility_updated.csv")
184
+ df = pd.read_csv("credit_card_data_updated.csv")
185
+ # print(df.head())
186
+ card_descriptions = dict(zip(df["name"], df["description"]))
187
+ features = ['Fuel Surcharge Waiver', 'Insurance', 'Shopping Benefits', 'Airport Lounge Access', 'Co-Branded', 'Daily Spends (Grocery)', 'Dining Benefits', 'Domestic Travel Benefits', 'Entertainment', 'General Reward Points', 'Movie Benefits', 'Rupay Network Support', 'Student', 'UPI Transaction Support', 'Welcome Bonus', 'International Travel Benefits', 'premium', 'Flight Discounts', 'Hotel Benefits', 'Travel Benefits', 'Railway Benefits', 'Railway Lounge', 'Utility', 'Beginners (Entry Level)', 'E-commerce Platform Benefits', 'Air Miles', 'Jewellery Spends', 'Concierge Services', 'Food Delivery Benefits', 'Lifestyle & Luxury Perks', 'Spa Access Benefits', 'Golf Access & Perks', 'Super Premium', 'Frequent Flyer Benefits', 'Health Benefits', 'Rent Payment Benefits', 'Education', 'Lifetime Free', 'Roadside Assistance', 'EMI Conversion Options', 'No Forex Markup Fee', 'Secured FD Based', 'Cashback', 'Fuel Benefits', 'Business']
188
+ df_all_cards = pd.read_csv("credit_card_data_updated.csv")
189
+ all_card_names = df_all_cards["name"].tolist()
190
+ all_card_lookup = dict(zip(df_all_cards["name"], df_all_cards["description"]))
191
+
192
+
193
+ # --- Eligibility Lookup (now global) ---
194
+ eligibility_lookup = {}
195
+ for _, row in eligibility_df.iterrows():
196
+ name = row["Name"].strip()
197
+ eligibility_lookup[name] = {
198
+ "bank": row["Bank"],
199
+ "age_range": f"{row['Minimum Age']} to {row['Maximum Age']}",
200
+ "income": f"{row['Minimum Income (LPA)']} LPA",
201
+ "credit_score": row["Minimum Credit Score"],
202
+ "joining_fee": row["Joining fee"],
203
+ "annual_fee": row["Annual fee"],
204
+ "issuer_link": row.get("Issuer Link", "").strip()
205
  }