鉴于不可控原因, openai 的接口我们是访问不了的.
但是在我们的服务器内是可以访问的.
此时, 我们可以通过 python3 搭建一个 web服务, 来反向代{过}{滤}理 openai.
通过访问我们的服务器来间接调用 openai 的 api 接口
python 语法简单,开发快捷, 也很方便集成一些自定义的业务逻辑
0x1 代码实现
from http.client import HTTPSConnection
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
PROXY_URL = 'api.openai.com'
HEADER_EXCLUSIVE = ['Host']
def get_header(src_header):
return {key: value for key, value in src_header.items() if key not in HEADER_EXCLUSIVE}
class ProxyHandler(BaseHTTPRequestHandler):
conn = HTTPSConnection(PROXY_URL)
def handle_request(self, method):
url = urlparse(self.path)
if method not in ('GET', 'POST', 'PUT', 'DELETE'):
self.send_error(400, 'Invalid method')
return
try:
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length) if content_length > 0 else None
headers = get_header(dict(self.headers.items()))
self.conn.request(method, self.path, body=body, headers=headers)
res = self.conn.getresponse()
self.send_response(res.status)
for header in res.getheaders():
self.send_header(header[0], header[1])
self.end_headers()
self.wfile.write(res.read())
except Exception as e:
self.send_error(500, str(e))
def do_GET(self):
self.handle_request('GET')
def do_POST(self):
self.handle_request('POST')
def do_PUT(self):
self.handle_request('PUT')
def do_DELETE(self):
self.handle_request('DELETE')
PORT = 9001
def run_proxy():
httpd = HTTPServer(('localhost', PORT), ProxyHandler)
print(f"Starting server at http://localhost:{PORT}")
httpd.serve_forever()
if __name__ == '__main__':
run_proxy()
0x2 启动服务
[root@ip-172-26-9-224 centos]# python3 openai.py
Starting server at http://localhost:9001
127.0.0.1 - - [07/Jul/2023 15:41:43] "GET /v1/models HTTP/1.1" 200 -
Snipaste_2023-07-07_15-42-45.png (274.07 KB, 下载次数: 0)
下载附件
2023-7-7 15:42 上传
由于代码简单, 就不写什么注释了....