使用Nginx搭建Openai接口反向代理
使用Debian海外云服务器搭建openai api服务的反向代理
为什么我反对使用 CF Worker / AI Gateway 去反代 OpenAI API
原因在于无论是Worker还是Gateway都无法隐藏我们的请求访问信息, 尤其是通过 Cf-Worker 这个头,cloudflare会把我 Worker 绑定的域名都卖掉。
要求
一台Debian系统的海外云服务器
一个域名
ssl证书
开始操作
# 安装nginx
apt install nginx -y
# 配置
server {
listen 443 ssl;
server_name [domain_name];
ssl_certificate [public_key.pem];
ssl_certificate_key [private_key.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 TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-128-CCM-8-SHA256:TLS13-AES-128-CCM-SHA256:EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+ECDSA+AES128:EECDH+aRSA+AES128:RSA+AES128:EECDH+ECDSA+AES256:EECDH+aRSA+AES256:RSA+AES256:EECDH+ECDSA+3DES:EECDH+aRSA+3DES:RSA+3DES:!MD5;
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;
}
}
#测试并启动
nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
nginx -s reload
2024/11/18 06:22:15 [notice] 500550#500550: signal process started测试访问
curl https://api-proxy.evanidea.top
{
"message": "Welcome to the OpenAI API! Documentation is available at https://platform.openai.com/docs/api-reference"
}使用python测试
from openai import OpenAI
OPENAI_API_KEY = "sk-xxxxx"
BASE_URL = "https://[domain_name]/v1"
client = OpenAI(base_url=BASE_URL, api_key=OPENAI_API_KEY)
completion = client.chat.completions.create(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "你是一个助手 公司业务管理"},
{
"role": "user",
"content": "你是一个公司的小助理,你被安排了公司业务的内容管理的工作。我会给你现在公司的业务介绍和业务下项目的负责人信息,你要根据给到你的信息,回答我的问题。如果你找不到对应的信息,请如实告诉我。",
},
],
)
print(completion.choices[0].message)