运行前需设置环境变量:
export OPENAI_API_ORIGAN=org-你的组织id
export OPENAI_API_KEY=sk-IlhlSea你的apikey
更多参数说明:https://platform.openai.com/docs/api-reference/chat
运行效果:
基于stream流式返回,逐字打印回答内容
实现代码:
# chatgpt聊天
import openai
import sysdef doChat(quest):completion = openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=[{"role": "user", "content": quest}],stream=True)for i,response in enumerate(completion):objcontent = response.choices[0].deltaif hasattr(objcontent, 'content'):msg = objcontent.contentsys.stdout.write(msg)sys.stdout.flush()else:continuewhile True:print('(请输入你的问题:)')quest = input()doChat(quest)