123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- from flask import Flask, request, Response, jsonify
- import requests
- import logging
- app = Flask(__name__)
- # 配置日志
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
- logger = logging.getLogger(__name__)
- # 定义SOCKS5代理
- SOCKS_PROXY = 'socks5h://host.docker.internal:20170'
- proxies = {
- 'http': SOCKS_PROXY,
- 'https': SOCKS_PROXY
- }
- # API配置
- API_BASE = "https://api.groq.com/openai"
- @app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
- def proxy(path):
- try:
- # 构建转发请求
- headers = dict(request.headers)
- # 移除可能导致问题的头信息
- headers.pop('Host', None)
- headers.pop('Content-Length', None)
- # 添加User-Agent头,模拟浏览器请求
- if 'User-Agent' not in headers:
- headers[
- 'User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
- # 构建请求URL
- url = f"{API_BASE}/{path}"
- logger.info(f"Forwarding request to: {url}")
- logger.debug(f"Request headers: {headers}")
- # 处理不同HTTP方法
- if request.method == 'POST':
- response = requests.post(
- url,
- headers=headers,
- data=request.get_data(),
- stream=True,
- proxies=proxies,
- timeout=60 # 添加超时设置
- )
- elif request.method == 'GET':
- response = requests.get(url, headers=headers, proxies=proxies, timeout=60)
- elif request.method == 'PUT':
- response = requests.put(url, headers=headers, data=request.get_data(), proxies=proxies, timeout=60)
- elif request.method == 'DELETE':
- response = requests.delete(url, headers=headers, proxies=proxies, timeout=60)
- else:
- return jsonify({"error": "Method not supported"}), 405
- logger.info(f"Received response with status: {response.status_code}")
- # 检查响应状态码
- if response.status_code == 403:
- logger.error("Received 403 Forbidden response")
- logger.error(f"Response content: {response.text}")
- return jsonify({"error": "Access forbidden, please check your credentials and proxy settings"}), 403
- # 处理流式响应
- if 'text/event-stream' in response.headers.get('Content-Type', ''):
- def generate():
- for chunk in response.iter_content(chunk_size=1024):
- if chunk:
- yield chunk
- return Response(generate(), content_type='text/event-stream')
- else:
- return response.content, response.status_code, dict(response.headers)
- except requests.exceptions.RequestException as e:
- logger.error(f"Request exception: {str(e)}")
- return jsonify({"error": f"Network error occurred: {str(e)}"}), 500
- except Exception as e:
- logger.error(f"Unexpected error: {str(e)}", exc_info=True)
- return jsonify({"error": f"An unexpected error occurred: {str(e)}"}), 500
- if __name__ == "__main__":
- app.run(host="0.0.0.0", port=4752, debug=False)
|