OpenAI>=1.0.0中ChatCompletion无法使用,Mac环境下如何替换?
问题描述
开发GPT内容生成系统,Mac环境下无法升级/降级OpenAI库,原代码调用openai.ChatCompletion.create接口报错,提示该接口在openai>=1.0.0版本中已不再支持,尝试pip升级、降级操作均无效,需替换ChatCompletion相关调用以适配当前OpenAI版本。
原代码
import os import openai # Set the API key from an environment variable openai.api_key = os.environ.get("api key ") # Prompt GPT for content generation prompt = "Write a blog post introducing an automated marketing platform for small businesses." response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "user", "content": prompt} ], max_tokens=500, temperature=0.7, ) # Print the generated content print(response.choices[0].message.content)
报错信息
Traceback (most recent call last): File "/Users/macbook/marketing-automation/gpt_content_generation.py", line 9, in <module> response = openai.ChatCompletion.create( File "/Users/macbook/marketing-automation/env/lib/python3.9/site-packages/openai/lib/_old_api.py", line 39, in __call__ raise APIRemovedInV1(symbol=self._symbol) openai.lib._old_api.APIRemovedInV1: You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.
官方提示信息
You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface. Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28` A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742
适配方案
直接修改代码适配OpenAI 1.x版本的API即可,核心改动如下:
- 改用
OpenAI客户端实例初始化 - 调用
chat.completions.create替代旧的ChatCompletion.create - 响应解析逻辑与旧版一致,无需额外调整
修改后的代码:
import os from openai import OpenAI # 初始化OpenAI客户端 client = OpenAI(api_key=os.environ.get("api key")) prompt = "Write a blog post introducing an automated marketing platform for small businesses." response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "user", "content": prompt} ], max_tokens=500, temperature=0.7, ) # 打印生成内容 print(response.choices[0].message.content)
若环境变量读取API Key存在问题,可临时直接赋值(不推荐生产环境使用):
client = OpenAI(api_key="your-actual-api-key")
内容的提问来源于stack exchange,提问作者Divine
相关产品推荐
相关产品推荐

