【完美解决:openai.error.APIConnectionError: Error communicating with OpenAI:】

完美解决:openai.error.APIConnectionError: Error communicating with OpenAI: HTTPSConnectionPool(host=‘api.openai.com’, port=443)

报错原文如下:

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

解决方案:

步骤一:
查找python解释器对应openai安装包里的api_requestor.py

例如
D:\package\Anaconda3\envs\all\Lib\site-packages\openai\api_requestor.py

步骤二:
如下修改代码,增加“小魔法”

		if not hasattr(_thread_context, "session"):
           proxy = {
                       'http': 'http://localhost:7890',
                       'https': 'http://localhost:7890'
                   }
           _thread_context.session = _make_session()
           _thread_context.session_create_time = time.time()
       elif (
           time.time() - getattr(_thread_context, "session_create_time", 0)
           >= MAX_SESSION_LIFETIME_SECS
       ):
           _thread_context.session.close()
           _thread_context.session = _make_session()
           _thread_context.session_create_time = time.time()
       try:
           result = _thread_context.session.request(
               method,
               abs_url,
               headers=headers,
               data=data,
               files=files,
               stream=stream,
               timeout=request_timeout if request_timeout else TIMEOUT_SECS,
               # proxies=_thread_context.session.proxies,
               proxies=proxy,
           )

步骤三:
在调用openAI的代码顶部添加环境配置
例如:

import openai
import os

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

# Replace 'your-api-key' with your actual OpenAI API key
openai.api_key = 'your-api-key'

response = openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Which vitamin is supplied from only animal source:A.Vitamin C B. Vitamin B7 C.Vitamin B12 D. Vitamin D"},
    ]
)

print(response['choices'][0]['message']['content'])

调用测试时,请把api-key换成自己的秘钥

步骤四:
打开本机的小魔法,执行脚本

至此,问题解决

你可能感兴趣的:(代码报错,python,chatgpt)