You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用ChatGPT遇Cloudflare拦截报错的解决求助

问题描述

按OpenAI官方文档编写Python代码调用ChatGPT功能,运行后触发openai.PermissionDeniedError,返回Cloudflare拦截页面。尝试更换OpenAI库版本、修改代码均无效,求解决方法。

代码示例

from openai import OpenAI

client = OpenAI(api_key='<我的API密钥>')

response = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Who won the world series in 2020?"},
    {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
    {"role": "user", "content": "Where was it played?"}
  ]
)

报错信息

报错返回Cloudflare拦截页面,核心提示:

抱歉,您已被阻止访问api.openai.com
该网站使用安全服务防护在线攻击,您的操作触发了安全机制。可能的触发原因包括提交特定词汇、SQL命令或格式错误的数据。

完整报错栈:

Traceback (most recent call last):
  File "C:\Users\danuk\AppData\Local\Programs\Python\Python312\1.py", line 5, in <module>
    response = client.chat.completions.create(
  File "C:\Users\danuk\AppData\Local\Programs\Python\Python312\Lib\site-packages\openai\_utils\_utils.py", line 275, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\danuk\AppData\Local\Programs\Python\Python312\Lib\site-packages\openai\resources\chat\completions.py", line 663, in create
    return self._post(
  File "C:\Users\danuk\AppData\Local\Programs\Python\Python312\Lib\site-packages\openai\_base_client.py", line 1200, in post
    return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
  File "C:\Users\danuk\AppData\Local\Programs\Python\Python312\Lib\site-packages\openai\_base_client.py", line 889, in request
    return self._request(
  File "C:\Users\danuk\AppData\Local\Programs\Python\Python312\Lib\site-packages\openai\_base_client.py", line 980, in _request
    raise self._make_status_error_from_response(err.response) from None
openai.PermissionDeniedError: <Cloudflare拦截HTML页面内容>
解决办法
  • 配置合规代理:Cloudflare拦截大多因IP地区受限,需使用可访问OpenAI API的代理/VPN,并在客户端中配置代理:
    client = OpenAI(
        api_key='你的API密钥',
        proxies={
            "http": "http://代理地址:端口",
            "https": "http://代理地址:端口",
        }
    )
    
  • 验证API密钥有效性:登录OpenAI后台确认密钥未过期、账户有可用余额,且密钥权限包含chat.completions接口调用权限。
  • 添加自定义请求头:模拟浏览器请求头,避免被识别为异常请求:
    client = OpenAI(
        api_key='你的API密钥',
        headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
        }
    )
    
  • 控制请求频率:短时间内多次调用可能触发反爬机制,添加time.sleep()控制请求间隔,避免频繁请求。
  • 检查网络环境:确保网络稳定,本地防火墙或安全软件未拦截API请求。

内容的提问来源于stack exchange,提问作者Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 00:23:16