1. 前言
本文学习使用Python调用OpenAI API的方法,基于openai python库 openai==0.27.8
注意:openai python库版本更新很快,本文并不适用更高版本openai python库。
参考文档:
2. 安装OpenAI客户端
1 | pip install openai==0.27.8 |
3. 命令行访问OpenAI
3.1. 命令行参数
1 | usage: openai [-h] [-V] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]] [-o ORGANIZATION] {api,tools,wandb} ... |
3.2. Hello world
1 | export OPENAI_API_KEY="sk-xxx" |

3.3. 测试OPENAI API是否畅通
1 | # 测试官方OPENAI API |
3.4. 可能的问题
3.4.1. 配置KEY问题
执行openai命令前,需要先配置KEY,否则会报错:
1 | Error: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details. |
或者,执行openai命令时,使用参数-k配置KEY。
3.4.2. 网络问题
执行可能会卡住一段时间后报错:
1 | [2023-08-05 08:55:26,852] Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f94afde5d30>: Failed to establish a new connection: [Errno 110] Connection timed out')': /v1/chat/completions |
也可能会直接报错:
1 | Error: Error communicating with OpenAI: ('Connection aborted.', ConnectionResetError(54, 'Connection reset by peer')) |
解决办法一:配置全局代理(推荐)
1 | export https_proxy=http://127.0.0.1:7890 http_proxy=http://127.0.0.1:7890 all_proxy=socks5://127.0.0.1:7890 |
解决方法二:使用OPENAI API代理
1 | openai -b "https://api.openai-forward.com/v1" api chat_completions.create -m gpt-3.5-turbo -g user "Hello world" |
解决办法三:执行命令时指定代理(验证时没有生效)
1 | openai -p http://127.0.0.1:7890 -k sk-xxx api chat_completions.create -m gpt-3.5-turbo -g user "Hello world" |
使用-p参数时,必须配合使用-k参数,否则报错:
1 | usage: openai [-h] [-V] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]] [-o ORGANIZATION] {api,tools,wandb} ... |
4. Python访问OpenAI
4.1. Hello world
1、新建文件 hello.py
1 | import os |
2、执行 hello.py
1 | python hello.py |

返回值json结构:
1 | { |
4.2. 可能的问题
4.2.1. 文件名问题
测试文件,不要命名为 openai.py ,否则会报错:
1 | AttributeError: partially initialized module 'openai' has no attribute 'ChatCompletion' (most likely due to a circular import) |