Spaces:
Sleeping
Sleeping
File size: 9,762 Bytes
235461a | 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | import os
from datetime import datetime, timedelta
from threading import Lock
from typing import Any, Dict, Optional
import boto3
from botocore.exceptions import ClientError
from llm.connection_manager import get_checkpointer
# ------------------------- Agent's tool related utils -------------------------
# User-specific storage for tool results (thread-safe)
_user_tool_results: Dict[str, Dict] = {}
_storage_lock = Lock()
# Track when results were stored for cleanup
_result_timestamps: Dict[str, datetime] = {}
def store_tool_result(user_id: str, tool_name: str, result: Dict[str, Any]) -> None:
"""
Store tool result for a specific user.
Args:
user_id: Unique identifier for the user
tool_name: Name of the tool that produced the result
result: The result data to store
"""
with _storage_lock:
if user_id not in _user_tool_results:
_user_tool_results[user_id] = {}
_user_tool_results[user_id][tool_name] = result
_result_timestamps[f"{user_id}:{tool_name}"] = datetime.now()
print(f"[STORAGE] Stored {tool_name} result for user {user_id}: {result}")
def get_tool_result(user_id: str, tool_name: str) -> Optional[Dict[str, Any]]:
"""
Get tool result for a specific user and clear it.
Args:
user_id: Unique identifier for the user
tool_name: Name of the tool to get result for
Returns:
The tool result if found, None otherwise
"""
with _storage_lock:
if user_id in _user_tool_results and tool_name in _user_tool_results[user_id]:
result = _user_tool_results[user_id].pop(tool_name)
timestamp_key = f"{user_id}:{tool_name}"
if timestamp_key in _result_timestamps:
del _result_timestamps[timestamp_key]
print(f"[STORAGE] Retrieved {tool_name} result for user {user_id}: {result}")
return result
return None
def clear_user_tool_results(user_id: str) -> None:
"""
Clear all tool results for a specific user.
Args:
user_id: Unique identifier for the user
"""
with _storage_lock:
if user_id in _user_tool_results:
# Remove all timestamps for this user
keys_to_remove = [k for k in _result_timestamps.keys() if k.startswith(f"{user_id}:")]
for key in keys_to_remove:
del _result_timestamps[key]
del _user_tool_results[user_id]
print(f"[STORAGE] Cleared all tool results for user {user_id}")
def cleanup_old_tool_results(max_age_hours: int = 24) -> None:
"""
Clean up tool results older than the specified age.
Args:
max_age_hours: Maximum age in hours before cleanup (default: 24 hours)
"""
cutoff_time = datetime.now() - timedelta(hours=max_age_hours)
with _storage_lock:
keys_to_remove = []
for timestamp_key, timestamp in _result_timestamps.items():
if timestamp < cutoff_time:
keys_to_remove.append(timestamp_key)
for timestamp_key in keys_to_remove:
user_id, tool_name = timestamp_key.split(":", 1)
if user_id in _user_tool_results and tool_name in _user_tool_results[user_id]:
del _user_tool_results[user_id][tool_name]
# Clean up empty user entries
if not _user_tool_results[user_id]:
del _user_tool_results[user_id]
del _result_timestamps[timestamp_key]
if keys_to_remove:
print(f"[STORAGE] Cleaned up {len(keys_to_remove)} old tool results")
# ------------------------- S3 Upload of images -------------------------
def upload_generated_image_to_s3(image_data: bytes, image_id: str, user_id: str, prompt: str, title: str = "Generated Image") -> Dict[str, Any]:
"""
Upload a generated image to S3.
Args:
image_data: The image data as bytes
image_id: Unique identifier for the image
user_id: User identifier
prompt: The prompt used to generate the image
title: Custom title for the image
Returns:
Dict with success status, URL, and metadata or error message
"""
try:
# Initialize S3 client
s3_client = boto3.client(
"s3",
region_name=os.environ.get("AWS_REGION", "us-east-1"),
aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY"),
)
# Generate S3 key with userId and imageId for organization
key = f"users/{user_id}/images/{image_id}"
bucket_name = os.environ.get("AWS_S3_BUCKET_NAME")
if not bucket_name:
return {"success": False, "error": "AWS_S3_BUCKET_NAME environment variable is not set"}
# Upload to S3
s3_client.put_object(
Bucket=bucket_name,
Key=key,
Body=image_data,
ContentType="image/png",
Metadata={
"title": title,
"imageId": image_id,
"userId": user_id,
"uploadedAt": datetime.now().isoformat(),
"type": "generated",
"generationPrompt": prompt,
},
)
# Generate presigned URL for reading the uploaded file (valid for 2 hours)
presigned_url = s3_client.generate_presigned_url(
"get_object",
Params={"Bucket": bucket_name, "Key": key},
ExpiresIn=7200, # 2 hours
)
return {"success": True, "url": presigned_url, "image_id": image_id}
except ClientError as e:
return {"success": False, "error": str(e)}
except Exception as e:
return {"success": False, "error": str(e)}
# ------------------------- IP Generation Count and Guardrails -------------------------
def get_ip_generation_count(ip_address: str) -> int:
"""
Query the database for IP address generation count for the current week.
Args:
ip_address: The IP address to query
Returns:
generation_count
If no data found, returns 0
"""
try:
checkpointer = get_checkpointer()
# Get the start of the current week (Monday)
now = datetime.now()
start_of_week = now - timedelta(days=now.weekday())
start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0)
# Query the rate_limits table for this IP in current week
# Using a simple SQL query to get the data
with checkpointer.conn.cursor() as cursor:
cursor.execute(
"""
SELECT generation_count
FROM rate_limits
WHERE ip_address = %s AND week_start = %s
""",
(ip_address, start_of_week.date()),
)
row = cursor.fetchone()
if row:
count = row.get("generation_count")
print(f"[UTILS] IP {ip_address}: {count} generations already made this week")
return int(count)
print(f"[UTILS] IP {ip_address}: No data found")
return 0
except Exception as e:
print(f"[UTILS] Error querying IP generation data: {e}")
return 0
def create_rate_limits_table():
"""
Create the rate_limits table if it doesn't exist.
"""
try:
from llm.connection_manager import get_checkpointer
checkpointer = get_checkpointer()
with checkpointer.conn.cursor() as cursor:
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS rate_limits (
id SERIAL PRIMARY KEY,
ip_address VARCHAR(45) NOT NULL,
week_start DATE NOT NULL,
generation_count INTEGER DEFAULT 0,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(ip_address, week_start)
)
"""
)
checkpointer.conn.commit()
print("[UTILS] Rate limits table created/verified successfully")
except Exception as e:
print(f"[UTILS] Error creating rate limits table: {e}")
def create_or_update_ip_generation_count(ip_address: str) -> bool:
"""
Update the generation count for an IP address, or create a new one if it doesn't exist.
Args:
ip_address: The IP address to update
Returns:
True if successful, False otherwise
"""
try:
from llm.connection_manager import get_checkpointer
checkpointer = get_checkpointer()
# Get the start of the current week (Monday)
now = datetime.now()
start_of_week = now - timedelta(days=now.weekday())
start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0)
with checkpointer.conn.cursor() as cursor:
# Use UPSERT to either insert new record or update existing one
cursor.execute(
"""
INSERT INTO rate_limits (ip_address, week_start, generation_count, last_updated)
VALUES (%s, %s, 1, %s)
ON CONFLICT (ip_address, week_start)
DO UPDATE SET
generation_count = rate_limits.generation_count + 1,
last_updated = EXCLUDED.last_updated
""",
(ip_address, start_of_week.date(), now.isoformat()),
)
checkpointer.conn.commit()
print(f"[UTILS] Created or Updated generation count for IP {ip_address}")
return True
except Exception as e:
print(f"[UTILS] Error updating IP generation count: {e}")
return False
|