OpenAI调用API报错 time out:HTTPSConnectionPool(host=‘api.openai.com‘, port=443)

114次阅读
没有评论

场景复现

代码如下(源自网络):

import openai

openai.api_key = 'sk-xxxx'
def chat_gpt(prompt):
     prompt = prompt
     model_engine = "text-davinci-003"
     completion = openai.Completion.create(
         engine=model_engine,
         prompt=prompt,
         max_tokens=1024,
         n=1,
         stop=None,
         temperature=0.5,
         timeout=1000,
     )

     response = completion.choices[0].text
     print(response)

chat_gpt("现在几点了")

执行报错:

OpenAI调用API报错 time out:HTTPSConnectionPool(host=‘api.openai.com‘, port=443)

APIConnectionError: Error communicating with OpenAI: HTTPSConnectionPool(host='api.openai.com', port=443): Max retries exceeded with url: /v1/chat/completions (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1125)')))

解决办法

1、urllib3降低版本到1.25.11

pip install urllib3==1.25.11

参考大佬文章:传送门

简单来说就是1.26.0版本的urllib3添加了HTTPS支持,但代理服务器不支持HTTPS,所以报错(pip走代理报错也差不多类似原因,具体请参考上文,有详细解读)

这个方法对部分人有用,但很不幸我是另一部分(哭)!

2、修改openai源码(亲测成功)

查看堆栈找到报错库的路径:

OpenAI调用API报错 time out:HTTPSConnectionPool(host=‘api.openai.com‘, port=443)

打开api_requestor.py,找到:

if not hasattr(_thread_context, "session")

分别在它上面和下面添加以下两行:

proxy = {
    'http': 'http://localhost:7890',
    'https': 'http://localhost:7890'
}


proxies=proxy

OpenAI调用API报错 time out:HTTPSConnectionPool(host=‘api.openai.com‘, port=443)

保存搞定,重新运行代码:

OpenAI调用API报错 time out:HTTPSConnectionPool(host=‘api.openai.com‘, port=443)

3、代码里设置环境变量(亲测成功)

添加以下代码:

import os

os.environ["http_proxy"] = "http://localhost:7890"
os.environ["https_proxy"] = "http://localhost:7890"

以上解决办法均来自网络,我只是个搬运工兼汇总~

文章转载遵循CC 4.0 BY-SA版权协议,来源于互联网: OpenAI调用API报错 time out:HTTPSConnectionPool(host=‘api.openai.com‘, port=443) | https://blog.csdn.net/as23751782/article/details/130143726

正文完
 0
评论(没有评论)