@@ -85,6 +85,34 @@ def get_ai_response(user_message, model):
85
85
except Exception as e :
86
86
return "I'm here to listen and support you. Sometimes I have trouble connecting, but I want you to know that your feelings are valid and you're not alone. Would you like to share more about what you're experiencing?"
87
87
88
+ def cached_user_ip ():
89
+ # Check if IP is already cached in session state
90
+ if hasattr (st .session_state , 'cached_ip' ) and hasattr (st .session_state , 'ip_cache_time' ):
91
+ # Check if cache is still valid (cache for 1 hour)
92
+ cache_age = datetime .now () - st .session_state .ip_cache_time
93
+ if cache_age < timedelta (hours = 1 ):
94
+ return st .session_state .cached_ip
95
+
96
+ # Cache is missing or expired, fetch new IP
97
+ try :
98
+ response = requests .get ("https://api.ipify.org" , timeout = 5 )
99
+ ip = response .text .strip ()
100
+ # Cache the IP and timestamp
101
+ st .session_state .cached_ip = ip
102
+ st .session_state .ip_cache_time = datetime .now ()
103
+
104
+ return ip
105
+ except (requests .RequestException , requests .Timeout , Exception ):
106
+ # Fallback: use session ID or generate a unique identifier
107
+ fallback_id = f"session_{ hash (str (st .session_state )) % 100000 } "
108
+
109
+ # Cache the fallback ID so we use the same one consistently
110
+ if not hasattr (st .session_state , 'cached_ip' ):
111
+ st .session_state .cached_ip = fallback_id
112
+ st .session_state .ip_cache_time = datetime .now ()
113
+
114
+ return st .session_state .cached_ip
115
+
88
116
#Implementing IP Based Isolation
89
117
def get_user_ip ():
90
118
try :
@@ -94,7 +122,7 @@ def get_user_ip():
94
122
95
123
#Saving and loading to/from JSON File
96
124
def get_memory_file ():
97
- ip = get_user_ip ()
125
+ ip = cached_user_ip ()
98
126
os .makedirs ("data" , exist_ok = True )
99
127
return f"data/conversations_{ ip } .json"
100
128
@@ -108,4 +136,4 @@ def load_conversations():
108
136
if not os .path .exists (memory_file ):
109
137
return []
110
138
with open (memory_file , 'r' , encoding = "utf-8" ) as f :
111
- return json .load (f )
139
+ return json .load (f )
0 commit comments