소스 검색

首次提交代码

GXX 1 개월 전
커밋
8d385971a4
6개의 변경된 파일139개의 추가작업 그리고 0개의 파일을 삭제
  1. 4 0
      .idea/.gitignore
  2. 6 0
      .idea/vcs.xml
  3. 18 0
      Dockerfile
  4. 18 0
      README.md
  5. 90 0
      proxy.py
  6. 3 0
      requirements.txt

+ 4 - 0
.idea/.gitignore

@@ -0,0 +1,4 @@
+# 默认忽略的文件
+/shelf/
+/workspace.xml
+VCS.XML

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="" vcs="Git" />
+  </component>
+</project>

+ 18 - 0
Dockerfile

@@ -0,0 +1,18 @@
+# 基础镜像使用Python 3.9
+FROM python:3.9-slim
+
+# 设置工作目录
+WORKDIR /app
+
+# 把当前目录的内容复制到工作目录
+COPY . .
+
+# 安装Python依赖
+RUN pip install requests[socks] requests flask
+
+# 暴露代理服务端口
+EXPOSE 4752
+
+# 运行代理服务
+CMD ["python", "proxy.py"]
+

+ 18 - 0
README.md

@@ -0,0 +1,18 @@
+1.修改源代码中你想代理的端点和代理配置:
+# 修改为你自己的翻墙代理配置
+SOCKS_PROXY = 'socks5h://host.docker.internal:20170'
+proxies = {
+    'http': SOCKS_PROXY,
+    'https': SOCKS_PROXY
+}
+
+# 修改为你想代理的openai端点
+API_BASE = "https://api.groq.com/openai"
+
+使用方法:
+
+pip install requirements.txt
+
+python proxy.py
+
+将日志中输出的url作为openai端点配置使用即可!

+ 90 - 0
proxy.py

@@ -0,0 +1,90 @@
+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)

+ 3 - 0
requirements.txt

@@ -0,0 +1,3 @@
+flask
+requests
+logging