Skip to content

Commit e57d69d

Browse files
Merge pull request #44 from dev9086/main
Increased Latency Caused by Redundant Network Requests
2 parents 7f9165c + 4d44f34 commit e57d69d

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

core/utils.py

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,34 @@ def get_ai_response(user_message, model):
8585
except Exception as e:
8686
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?"
8787

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+
88116
#Implementing IP Based Isolation
89117
def get_user_ip():
90118
try:
@@ -94,7 +122,7 @@ def get_user_ip():
94122

95123
#Saving and loading to/from JSON File
96124
def get_memory_file():
97-
ip = get_user_ip()
125+
ip = cached_user_ip()
98126
os.makedirs("data", exist_ok=True)
99127
return f"data/conversations_{ip}.json"
100128

@@ -108,4 +136,4 @@ def load_conversations():
108136
if not os.path.exists(memory_file):
109137
return []
110138
with open(memory_file, 'r', encoding="utf-8") as f:
111-
return json.load(f)
139+
return json.load(f)

0 commit comments

Comments
 (0)