使用 Nginx 反向代理 OpenAI API

发布于 2023-08-02  53 次阅读


项目需要使用到 OpenAI 的 API,但是国内服务器无法直连,因此要么用科学方法,要么使用反代的 API,我选择了后者,在此记录下配置文件。

server {
 listen 443 ssl;
 server_name your.domain;
 ssl_certificate /path/to/certificate;
 ssl_certificate_key /path/to/certificate_key;
 ssl_session_cache shared:le_nginx_SSL:1m;
 ssl_session_timeout 1440m;
 ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
 ssl_prefer_server_ciphers on;
 ssl_ciphers your_ciphers;
 location / {
   proxy_pass  https://api.openai.com/;
   proxy_ssl_server_name on;
   proxy_set_header Host api.openai.com;
   proxy_set_header Connection '';
   proxy_http_version 1.1;
   chunked_transfer_encoding off;
   proxy_buffering off;
   proxy_cache off;
   proxy_set_header X-Forwarded-For $remote_addr;
   proxy_set_header X-Forwarded-Proto $scheme;
 }
}

在 Python 代码中调用时,只需要预先设置 openai.api_base = "https://api.youraddress.com/v1" 即可。