一个计算机技术爱好者与学习者

0%

好好学Python:Python调用OpenAI API

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
usage: openai [-h] [-V] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]] [-o ORGANIZATION] {api,tools,wandb} ...

positional arguments:
{api,tools,wandb}
api Direct API calls
tools Client side tools for convenience
wandb Logging with Weights & Biases

optional arguments:
-h, --help show this help message and exit
-V, --version show program's version number and exit
-v, --verbose Set verbosity.
-b API_BASE, --api-base API_BASE
What API base url to use.
-k API_KEY, --api-key API_KEY
What API key to use.
-p PROXY [PROXY ...], --proxy PROXY [PROXY ...]
What proxy to use.
-o ORGANIZATION, --organization ORGANIZATION
Which organization to run as (will use your default organization if not specified)

3.2. Hello world

1
2
3
export OPENAI_API_KEY="sk-xxx"

openai api chat_completions.create -m gpt-3.5-turbo -g user "Hello world"

3.3. 测试OPENAI API是否畅通

1
2
3
4
5
# 测试官方OPENAI API
openai api chat_completions.create -m gpt-3.5-turbo -g user "Hello world"

# 测试OPENAI API代理
openai -b "https://api.openai-forward.com/v1" api chat_completions.create -m gpt-3.5-turbo -g user "Hello world"

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
2
3
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 chat_completions.create -m gpt-3.5-turbo -g user "Hello world"

解决方法二:使用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
2
usage: openai [-h] [-V] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]] [-o ORGANIZATION] {api,tools,wandb} ...
openai: error: argument {api,tools,wandb}: invalid choice: 'gpt-3.5-turbo' (choose from 'api', 'tools', 'wandb')

4. Python访问OpenAI

4.1. Hello world

1、新建文件 hello.py

1
2
3
4
5
6
7
8
9
10
import os
import openai

# openai.api_base = os.getenv("OPENAI_API_BASE")
# openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_base = 'https://api.openai.com/v1'
openai.api_key = 'sk-xxx'

chat_completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}])
print(chat_completion)

2、执行 hello.py

1
python hello.py

返回值json结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"id": "chatcmpl-7ksejsnNZEmq7Q0YPGQ1iRa1x5LHf",
"object": "chat.completion",
"created": 1691407541,
"model": "gpt-3.5-turbo-0613",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I assist you today?"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 9,
"total_tokens": 18
}
}

4.2. 可能的问题

4.2.1. 文件名问题

测试文件,不要命名为 openai.py ,否则会报错:

1
AttributeError: partially initialized module 'openai' has no attribute 'ChatCompletion' (most likely due to a circular import)
  • 本文作者: 好好学习的郝
  • 原文链接: https://www.voidking.com/dev-python-openai-api/
  • 版权声明: 本文采用 BY-NC-SA 许可协议,转载请注明出处!源站会即时更新知识点并修正错误,欢迎访问~
  • 微信公众号同步更新,欢迎关注~