An Example of Using Google Gemini
When using Gemini from mainland China, it is inaccessible. This article provides a way to make API calls in Python by routing traffic through a proxy IP.
The official Gemini documentation is at: https://ai.google.dev/gemini-api/docs?hl=zh-cn
The methods Baidu Search tells you about are all crude uses of global configuration.
Below is the general approach that search engines suggest:
os.environ['HTTP_PROXY'] = '127.0.0.1:7897'
os.environ['HTTPS_PROXY'] = '127.0.0.1:7897'The problem with this approach is that if your business logic also calls other AIs or has network access tasks, all requests will end up going through the proxy.
For example, I might first use Playwright or Requests for some automation tasks, downloading a piece of content, and then use Gemini — which causes the download tasks to go through the proxy.
Installing and using Gemini in Python
- Install the dependencies
pip install -U google-genai- Complete code
client = genai.Client(api_key=config.GOOGLE_GEMINI_API_KEY)
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="who are you",
# config=types.GenerateContentConfig(
# max_output_tokens=500,
# temperature=0.1
# )
)
print(response.text)All non-Google requests bypass the proxy and connect directly
-
The principle: configure NO_PROXY properly, and every domain you need must be configured
-
Complete code
os.environ['HTTP_PROXY'] = config.PROXY
os.environ['HTTPS_PROXY'] = config.PROXY
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,local,.local,10.*,192.168.*,.ipinfo.io'
client = genai.Client(api_key=config.GOOGLE_GEMINI_API_KEY)
print(config.GOOGLE_GEMINI_API_KEY)
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="who are you",
# config=types.GenerateContentConfig(
# max_output_tokens=500,
# temperature=0.1
# )
)
print(response.text)