1、安装openai依赖
pip install openai
2、编写聊天代码
# coding: utf-8
# author: liangshiqiang
# date : 2023年04月26日
import openai
openai.proxy = 'http://127.0.0.1:10809' # 翻墙代理
openai.api_key = 'xxxxxxxxxxxxx' # openai的key
messages = []
def add_message(content, role='user'):
"""
添加消息到上下文。每次发送消息给openai都要携带上下文以便openai理解
:param content: 上下文内容
:param role: 上下文的角色。一般是三个值:user, assistant, system
:return: None
"""
global messages
messages.append({
'role': role,
'content': content
})
print('您好啊,我是AI机器人,你现在可以开始提问了')
while True:
question = input()
add_message(question) # 询问的内容加入上下文
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
choices = response.get('choices') or []
if not choices:
print('没有找到你想要的内容,请重新描述')
continue
answer = choices[0].get('message', {}).get('content')
if not answer:
print('没有找到你想要的内容,请重新描述')
continue
add_message(answer, 'assistant') # 回答的内容加入上下文
print(answer)
3、运行: