proxy.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from flask import Flask, request, Response, jsonify
  2. import requests
  3. import logging
  4. app = Flask(__name__)
  5. # 配置日志
  6. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  7. logger = logging.getLogger(__name__)
  8. # 定义SOCKS5代理
  9. SOCKS_PROXY = 'socks5h://host.docker.internal:20170'
  10. proxies = {
  11. 'http': SOCKS_PROXY,
  12. 'https': SOCKS_PROXY
  13. }
  14. # API配置
  15. API_BASE = "https://api.groq.com/openai"
  16. @app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
  17. def proxy(path):
  18. try:
  19. # 构建转发请求
  20. headers = dict(request.headers)
  21. # 移除可能导致问题的头信息
  22. headers.pop('Host', None)
  23. headers.pop('Content-Length', None)
  24. # 添加User-Agent头,模拟浏览器请求
  25. if 'User-Agent' not in headers:
  26. headers[
  27. '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'
  28. # 构建请求URL
  29. url = f"{API_BASE}/{path}"
  30. logger.info(f"Forwarding request to: {url}")
  31. logger.debug(f"Request headers: {headers}")
  32. # 处理不同HTTP方法
  33. if request.method == 'POST':
  34. response = requests.post(
  35. url,
  36. headers=headers,
  37. data=request.get_data(),
  38. stream=True,
  39. proxies=proxies,
  40. timeout=60 # 添加超时设置
  41. )
  42. elif request.method == 'GET':
  43. response = requests.get(url, headers=headers, proxies=proxies, timeout=60)
  44. elif request.method == 'PUT':
  45. response = requests.put(url, headers=headers, data=request.get_data(), proxies=proxies, timeout=60)
  46. elif request.method == 'DELETE':
  47. response = requests.delete(url, headers=headers, proxies=proxies, timeout=60)
  48. else:
  49. return jsonify({"error": "Method not supported"}), 405
  50. logger.info(f"Received response with status: {response.status_code}")
  51. # 检查响应状态码
  52. if response.status_code == 403:
  53. logger.error("Received 403 Forbidden response")
  54. logger.error(f"Response content: {response.text}")
  55. return jsonify({"error": "Access forbidden, please check your credentials and proxy settings"}), 403
  56. # 处理流式响应
  57. if 'text/event-stream' in response.headers.get('Content-Type', ''):
  58. def generate():
  59. for chunk in response.iter_content(chunk_size=1024):
  60. if chunk:
  61. yield chunk
  62. return Response(generate(), content_type='text/event-stream')
  63. else:
  64. return response.content, response.status_code, dict(response.headers)
  65. except requests.exceptions.RequestException as e:
  66. logger.error(f"Request exception: {str(e)}")
  67. return jsonify({"error": f"Network error occurred: {str(e)}"}), 500
  68. except Exception as e:
  69. logger.error(f"Unexpected error: {str(e)}", exc_info=True)
  70. return jsonify({"error": f"An unexpected error occurred: {str(e)}"}), 500
  71. if __name__ == "__main__":
  72. app.run(host="0.0.0.0", port=4752, debug=False)