# -*- coding: utf-8 -*- Created on 2026/6/2 9:44 creator er_nao File day77_role_prompt_template.py Description 角色 Prompt 模板 importrequestsimporttimefromconfigimportTONGYI_API_KEY,TONGYI_API_URL# 核心角色 Prompt 模板函数 defget_role_prompt(role_name): 角色模板库输入角色名返回完整的角色Prompt role_template{# 学习角色Python老师:你是一位Python零基础老师用大白话讲解不使用专业术语回答简洁易懂。,# 工作角色专业翻译:你是专业中英翻译官只输出翻译结果不添加任何多余解释、文字和符号。,# 技术角色代码助手:你是专业代码助手只输出可运行代码附带简洁注释不废话。,# 生活角色美食推荐官:你是美食推荐官根据需求推荐3个菜品简洁不啰嗦。,# 默认角色默认:你是一个友好、简洁、专业的AI助手。}# 返回对应角色的Promptreturnrole_template.get(role_name,role_template[默认])# 历史消息拼接 defconcat_history(history,new_question):msg_listhistory.copy()msg_list.append({role:user,content:new_question})returnmsg_list# AI调用函数 defai_chat(messages,temperature0.6,max_retry3):forretryinrange(max_retry):try:headers{Authorization:fBearer{TONGYI_API_KEY},Content-Type:application/json}data{model:qwen-plus,input:{messages:messages},temperature:temperature}resrequests.post(TONGYI_API_URL,headersheaders,jsondata)resultres.json()returnresult[output][text]exceptExceptionase:print(f第{retry1}次重试...)time.sleep(1)return调用失败# 带角色的对话函数 defchat_with_role(user_input,role_name,historyNone):ifhistoryisNone:history[]# 1. 获取角色模板今天核心role_promptget_role_prompt(role_name)# 2. 拼接system角色 历史 用户问题messages[{role:system,content:role_prompt}]messages.extend(history)messages.append({role:user,content:user_input})# 3. 获取AI回答ai_replyai_chat(messages)# 4. 更新历史history.append({role:user,content:user_input})history.append({role:assistant,content:ai_reply})returnai_reply,history# 测试 if__name____main__:history[]print( 角色Python老师 )reply,historychat_with_role(什么是变量,Python老师,history)print(AI,reply)print(\n 角色专业翻译 )reply,historychat_with_role(I love coding,专业翻译,history)print(AI,reply)