【记录】OpenAI|Python调用GPT API的开发环境及代码(2024/06/21实测)
创始人
2024-11-04 09:10:54

本文默认读者已经有API Keys,并默认读者对Python环境较为熟悉,对相关内容不予介绍。
更新时间:2024/03/21

国内安装的时候偶尔会出现各种问题,
这篇记录是记录当下可用的一个方式。

文章目录

    • 近期更新(2024/06/21)
    • 安装(2024/03/21)
      • 若有Anaconda
      • 若只有Python环境
    • 使用
      • 获取样例
      • 设置API Keys
      • 设置代理
      • 可运行的代码

近期更新(2024/06/21)

现在openai更新了,python高版本也支持了,直接运行这行指令试试吧:

pip install openai --upgrade 

安装(2024/03/21)

参考:python 安装openai的踩坑史

官网的介绍是pip install openai。不过它没说Python版本最好<=3.8。

若Python版本过高,到达了3.11,会出现以下报错:

ImportError: cannot import name 'OpenAI' from 'openai' 

因此请直接使用Python==3.8。

若有Anaconda

安装完整过程推荐:

conda create -n openai-demo python=3.8 conda activate openai-demo pip install openai==1.14.2 # 或者conda install openai 

若openai装不上就换国内清华的源,或者关掉代理。

若只有Python环境

Python官网下一个Python3.8,
然后在安装路径进行后续操作:

pip install openai==1.14.2 

经验之谈:
建议装VScode配合Python插件去管理并切换Python环境,
不建议直接莽改系统环境变量。

使用

获取样例

为了使我们的GPT API返回的结果更符合我们的需求,我们可以对GPT的角色进行自定义。而GPT自带非常多种类的自定义模板,其网址是:Prompt Example。

选用你想要的角色即可,例如我需要内容提取,就选了一种内容提取的模板,然后复制了代码。
在这里插入图片描述
我复制的代码如下:

from openai import OpenAI client = OpenAI()  response = client.chat.completions.create(   model="gpt-3.5-turbo",   messages=[     {       "role": "system",       "content": "You will be provided with unstructured data, and your task is to parse it into CSV format."     },     {       "role": "user",       "content": "There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy. There are also loheckles, which are a grayish blue fruit and are very tart, a little bit like a lemon. Pounits are a bright green color and are more savory than sweet. There are also plenty of loopnovas which are a neon pink flavor and taste like cotton candy. Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them."     }   ],   temperature=0.7,   max_tokens=64,   top_p=1 ) 

这个时候的代码还是不能运行的,
还需要设置以下两个内容。

设置API Keys

API Key可以设置为系统环境变量,具体方式是新建一个名为OPENAI_API_KEY的环境变量,如下图:
在这里插入图片描述

也可以写在代码里面:

OpenAI(api_key='') 

我选择直接修改环境变量。

设置代理

参考:Nodejs和python 设置 openai 的API正向代理和反向代理入口链接连接方式,用于国内访问openAI接口

如果不设置代理,你将会看到任何请求都返回Connection error:
在这里插入图片描述

设置的方式是在Python中加四行代码:

# Set the proxy URL and port proxy_url = 'http://127.0.0.1' proxy_port = '10809'  # Set the http_proxy and https_proxy environment variables os.environ['http_proxy'] = f'{proxy_url}:{proxy_port}' os.environ['https_proxy'] = f'{proxy_url}:{proxy_port}' 

具体URL和端口由你使用的代理决定。

可运行的代码

设置完成后,完整代码如下:

from openai import OpenAI import os  # Set the proxy URL and port proxy_url = 'http://127.0.0.1' proxy_port = '8080' # !!!please replace it with your own port  # Set the http_proxy and https_proxy environment variables os.environ['http_proxy'] = f'{proxy_url}:{proxy_port}' os.environ['https_proxy'] = f'{proxy_url}:{proxy_port}'  client = OpenAI()  response = client.chat.completions.create(   model="gpt-3.5-turbo",   messages=[     {       "role": "system",       "content": "You will be provided with unstructured data, and your task is to parse it into CSV format."     },     {       "role": "user",       "content": "There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy. There are also loheckles, which are a grayish blue fruit and are very tart, a little bit like a lemon. Pounits are a bright green color and are more savory than sweet. There are also plenty of loopnovas which are a neon pink flavor and taste like cotton candy. Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them."     }   ],   temperature=0.7,   max_tokens=64,   top_p=1 )  print(response.choices[0].message.content) 

代码运行结果:

在这里插入图片描述

本账号所有文章均为原创,欢迎转载,请注明文章出处:https://blog.csdn.net/qq_46106285/article/details/136923724。百度和各类采集站皆不可信,搜索请谨慎鉴别。技术类文章一般都有时效性,本人习惯不定期对自己的博文进行修正和更新,因此请访问出处以查看本文的最新版本。

相关内容

热门资讯

裸辞做“一人公司”,我后悔了 去年这个时候,一位以色列程序员正在东南亚旅行。他顺手把一个在脑子里转了很久的想法做成了产品,一个让任...
南京建成国内首个Pre-6G试... 4月21日,2026全球6G技术与产业生态大会在南京开幕。全息互动技术展台前,一名远在北京的工作人员...
超梵求职受邀参加“2025抖音... 超梵求职受邀参加“2025抖音巨量引擎成人教育行业生态大会”,探讨分享优质内容传播,服务万千学员。 ...
摩托罗拉Razr 2026(R... IT之家 4 月 22 日消息,摩托罗拉宣布新一代 Razr 折叠手机将于 4 月 29 日在美国发...
库克卸任,特纳斯领航:苹果新纪... 苹果首席执行官蒂姆·库克将卸任,硬件工程主管约翰·特纳斯将接任,苹果公司今天宣布此事。 库克将在夏季...