File size: 3,044 Bytes
d0a09ec | 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 | from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import os
import requests
import time
from functools import wraps
app = Flask(__name__, static_folder='static')
CORS(app)
# Get API key from environment variable
ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY")
if not ANTHROPIC_API_KEY:
raise ValueError("ANTHROPIC_API_KEY not found in environment variables!")
# Simple rate limiting (per IP)
rate_limit_storage = {}
RATE_LIMIT = 50 # requests per hour per IP
RATE_WINDOW = 3600 # 1 hour in seconds
def rate_limit(f):
@wraps(f)
def decorated_function(*args, **kwargs):
ip = request.remote_addr
current_time = time.time()
# Clean old entries
if ip in rate_limit_storage:
rate_limit_storage[ip] = [t for t in rate_limit_storage[ip] if current_time - t < RATE_WINDOW]
else:
rate_limit_storage[ip] = []
# Check rate limit
if len(rate_limit_storage[ip]) >= RATE_LIMIT:
return jsonify({"error": "Rate limit exceeded. Please try again later."}), 429
# Add current request
rate_limit_storage[ip].append(current_time)
return f(*args, **kwargs)
return decorated_function
@app.route('/')
def index():
return send_from_directory('static', 'index.html')
@app.route('/<path:path>')
def static_files(path):
return send_from_directory('static', path)
@app.route('/api/chat', methods=['POST'])
@rate_limit
def chat():
try:
data = request.json
# Validate request
if not data or 'messages' not in data:
return jsonify({"error": "Invalid request format"}), 400
messages = data.get('messages', [])
system_prompt = data.get('system', '')
model = data.get('model', 'claude-sonnet-4-20250514')
max_tokens = data.get('max_tokens', 1000)
# Call Anthropic API
response = requests.post(
"https://api.anthropic.com/v1/messages",
headers={
"x-api-key": ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
"content-type": "application/json"
},
json={
"model": model,
"max_tokens": max_tokens,
"system": system_prompt,
"messages": messages
},
timeout=30
)
if response.status_code == 200:
return jsonify(response.json())
else:
return jsonify({
"error": f"API error: {response.status_code}",
"details": response.text
}), response.status_code
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/health', methods=['GET'])
def health():
return jsonify({"status": "healthy", "api_key_configured": bool(ANTHROPIC_API_KEY)})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |