随笔 使用Nginx代理Gemini Chasing 2025-04-02 2026-04-30 记录一下使用Nginx代理Gemini,可以大陆访问和调用Gemini
主要有以下步骤:
Gemini相关
查找Gemini 官方文档
找到调用API中Openai兼容性这一块
Python为例 from openai import OpenAIclient = OpenAI( api_key="GEMINI_API_KEY" , base_url="https://generativelanguage.googleapis.com/v1beta/openai/" ) response = client.chat.completions.create( model="gemini-2.0-flash" , n=1 , messages=[ {"role" : "system" , "content" : "You are a helpful assistant." }, { "role" : "user" , "content" : "Explain to me how AI works" } ] ) print (response.choices[0 ].message)
创建Gemini API KEY
Nginx配置
sudo vim /etc/nginx/sites-available/default
在你已有的域名服务server下增加:
location /gemini/v1beta/openai/ { proxy_pass https://generativelanguage.googleapis.com/v1beta/openai/; proxy_set_header Host generativelanguage.googleapis.com; client_max_body_size 10M; # 记得设置nginx上传文件大小,不然图片理解功能会被卡住 proxy_buffering off; proxy_cache off; proxy_request_buffering off; # 保持长连接 proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; # 透传关键头信息 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # 调整超时(按需设置) proxy_read_timeout 3600s; # 长流式请求需要更长时间 }
上述配置实现了流式和非流式调用,亲测可用。调用地址则为: https://www.xx.com/gemini/v1beta/openai/ 替换为你自己域名即可。
附Python调用示例:
from openai import OpenAIclient = OpenAI( api_key="GEMINI_API_KEY" , base_url="https://www.xx.com/gemini/v1beta/openai/" ) response = client.chat.completions.create( model="gemini-2.0-flash" , n=1 , messages=[ {"role" : "system" , "content" : "You are a helpful assistant." }, { "role" : "user" , "content" : "Explain to me how AI works" } ], stream=Flase ) print (response.choices[0 ].message)
Chasing
A record of Life and Work
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Chasing's BLOG !