运行前需设置环境变量:
export OPENAI_API_ORIGAN=org-你的组织id
export OPENAI_API_KEY=sk-IlhlSea你的apikey
更多参数说明:https://platform.openai.com/docs/api-reference/chat
运行效果:
实现代码:
# chatgpt聊天
import openai
import sys
def 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].delta
if hasattr(objcontent, 'content'):
msg = objcontent.content
sys.stdout.write(msg)
sys.stdout.flush()
else:
continue
while True:
print('(请输入你的问题:)')
quest = input()
doChat(quest)