类别:人工智能 / 日期:2023-05-26 / 浏览:1123 / 评论:0
一、介绍
为了更容易地理解Python与ChatGPT的交互方式,本次使用Django搭建了一个简单的机器人聊天网站,包括了基本的注册和登录,保存用户聊天记录等功能。
二、项目
项目基于Django 4.2设计,直接使用sqlite数据库存储数据。
核心功能是接收用户的问题后调用OpenAI的接口,并将结果返回给用户。
对于登录的用户,可以保存用户的聊天记录。该记录会作为历史消息发送给接口,以保证返回用户的时候有正确的上下文。
对于未登录的用户,则不会保留记录,只对当前的问题进行回复。
三、代码
这里的核心代码是调用OpenAI的服务:
def ask_with_completion(message: str) -> str:
response = openai.Completion.create(
model="text-davinci-003",
prompt=message,
max_tokens=1000,
temperature=0,
)
print(response)
return response.choices[0].text.strip()
def ask_with_chat_completion(chat_history: List[ChatMessage], message):
msgs = [
{"role": "system", "content": "You are an AI chatbot"}
]
for item in chat_history:
msgs.append({"role": "user", "content": item.message})
msgs.append({"role": "assistant", "content": item.response})
msgs.append({"role": "user", "content": message})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=msgs,
temperature=0,
)
return response.choices[0].message.content.strip()
这里的Completion.create()方法请参考:https://platform.openai.com/docs/api-reference/completions/create
这里的ChatCompletion.create()方法请参考:https://platform.openai.com/docs/api-reference/chat-completions/create
处理用户的请求View代码如下:
class ChatBotView(View):
def get_history(self):
history = []
if self.request.user.is_authenticated:
history = ChatMessage.objects.filter(user=self.request.user).order_by('created_at')
return history
def get(self, request, *args, **kwargs):
return render(request, 'chatbot.html', {"history": self.get_history()})
def post(self, request, *args, **kwargs):
message = request.POST.get("message")
history = self.get_history()
if self.request.user.is_authenticated:
response = ask_with_chat_completion(history, message)
chat_message = ChatMessage(user=request.user, message=message, response=response,
created_at=datetime.datetime.now())
chat_message.save()
else:
response = ask_with_completion(message)
return JsonResponse({"message": message, "response": response})
对于未登录的用户,使用了ask_with_completion方法。对于已登录的用户,则使用了方法ask_with_chat_completion。
其中,ChatMessage模型存储了历史的用户对话记录,会传递到ask_with_chat_completion中,保证用户的上下文正确。
四、截图
下面是聊天界面的截图:
五、资料
该项目已经发布到本人GitHub上,有需要的可以自行获取:GitHub地址
发表评论 /