
国内服务器如何使用Nginx反向代理连接OpenAI
当你需要将流量从一个服务器转移到另一个服务器时,反向代理就会派上用场。Nginx 是一种轻量级、高性能的 Web 服务器/反向代理服务器。在本文中,我们将讨论如何在 Linux 系统中使用 Nginx 反向代理 OpenAI。
科学上网
首先国内服务是无法调用openai的api的,所以需要服务器配置好代理,这里不再赘述,我用的是clash,http代理地址是:
http://127.0.0.1:7890
安装 Nginx
请确认已安装好Nginx,如果没有,按下面的步骤安装,如已安装可忽略这步:
sudo apt-get update
sudo apt-get install nginx
这将从 Ubuntu 软件源安装 Nginx。
配置 Nginx
在配置文件中添加以下内容:
server {
listen 80; #http域名的话这里是80,https域名是443
server_name your_domain.com; #这里是你想反向代理的域名
location / {
rewrite ^(.*)$ "://api.openai.com$1";
rewrite ^(.*)$ "https$1" break;
proxy_set_header Proxy-Connection Keep-Alive;
proxy_set_header Host api.openai.com;
proxy_buffering off; #加上这个支持流式输出(也就是AI回复你时的打字机效果)
proxy_pass http://127.0.0.1:7890; #这里是代理地址
proxy_redirect ~^https?://api\.openai\.com(.*)$ http://$host$1;
}
}
重新启动 Nginx
在完成配置后,需要重启 Nginx 以使配置生效:
sudo nginx -s reload
如果是初次启动Nginx就执行这个:
sudo systemctl start nginx
测试反向代理
用curl测试:
ubuntu@VM-20-4-ubuntu:~$ curl http://your_domain.com/v1/completions \
> -H "Content-Type: application/json" \
> -H "Authorization: Bearer sk-xxxxxxxx" \
> -d '{
> "model": "text-davinci-003",
> "prompt": "Say this is a test",
> "max_tokens": 7,
> "temperature": 0
> }'
{"id":"cmpl-7GUg6U3QAABGWLH2KWrNRXDi","object":"text_completion","created":1684165530,"model":"text-davinci-003","choices":[{"text":"\n\nThis is indeed a test","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":5,"completion_tokens":7,"total_tokens":12}}
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果