5.封装对话函数,实现多轮对话
# -*- coding: utf-8 -*- Created on 2026/5/26 15:45 creator er_nao File day63_chat_function.py Description 封装对话函数实现多轮对话 importrequestsfromtongyi_chat_utilsimportTONGYI_API_KEY,TONGYI_API_URL# 第一步封装对话函数 defchat_with_ai(message,historyNone):# 异常处理try:# 请求头headers{Authorization:fBearer{TONGYI_API_KEY},Content-Type:application/json}# 消息列表ifhistoryisNone:history[]# 把用户最新的问题加进去history.append({role:user,content:message})# 请求数据data{model:qwen-plus,input:{messages:history}}# 发送请求responserequests.post(TONGYI_API_URL,jsondata,headersheaders)resultresponse.json()ai_replyresult[output][text]# 把AI的回复也加入历史实现多轮history.append({role:assistant,content:ai_reply})returnai_reply,historyexceptExceptionase:returnf出错了{str(e)},history# 第二步测试多轮对话 if__name____main__:history[]# 对话历史# 第一轮reply1,historychat_with_ai(11等于几,history)print(你11等于几)print(AI,reply1)print(-*30)# 第二轮AI能记住上一轮reply2,historychat_with_ai(再加3等于几,history)print(你再加3等于几)print(AI,reply2)核心大白话知识点1. 什么是「封装函数」就是把重复使用的代码打包像一个工具。以后想调用 AI直接用工具不用再写几十行代码。2. 什么是「多轮对话」你11 等于几AI等于 2你再加 3 等于几AI等于 5这就是多轮对话AI记住了历史内容。