# -*- 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,history=None):# 异常处理try:# 请求头headers={"Authorization":f"Bearer{TONGYI_API_KEY}","Content-Type":"application/json"}# 消息列表ifhistoryisNone:history=[]# 把用户最新的问题加进去history.append({"role":"user","content":message})# 请求数据data={"model":"qwen-plus","input":{"messages":history}}# 发送请求response=requests.post(TONGYI_API_URL,json=data,headers=headers)result=response.json()ai_reply=result["output"]["text"]# 把AI的回复也加入历史(实现多轮)history.append({"role":"assistant","content":ai_reply})returnai_reply,historyexceptExceptionase:returnf"出错了:{str(e)}",history# ===================== 第二步:测试多轮对话 =====================if__name__=="__main__":history=[]# 对话历史# 第一轮reply1,history=chat_with_ai("1+1等于几",history)print("你:1+1等于几")print("AI:",reply1)print("-"*30)# 第二轮(AI能记住上一轮)reply2,history=chat_with_ai("再加3等于几",history)print("你:再加3等于几")print("AI:",reply2)核心大白话知识点
1. 什么是「封装函数」?
就是把重复使用的代码打包,像一个工具。
以后想调用 AI,直接用工具,不用再写几十行代码。
2. 什么是「多轮对话」?
你:1+1 等于几
AI:等于 2
你:再加 3 等于几
AI:等于 5
这就是多轮对话,AI记住了历史内容。