8.角色 Prompt 模板

python 复制代码
# -*- coding: utf-8 -*-
"""
@Created on : 2026/6/2 9:44
@creator : er_nao
@File :day77_role_prompt_template.py
@Description :角色 Prompt 模板
"""
import requests
import time
from config import TONGYI_API_KEY, TONGYI_API_URL


# =====================  核心:角色 Prompt 模板函数 =====================
def get_role_prompt(role_name):
    """
    角色模板库:输入角色名,返回完整的角色Prompt
    """
    role_template = {
        # 学习角色
        "Python老师": "你是一位Python零基础老师,用大白话讲解,不使用专业术语,回答简洁易懂。",

        # 工作角色
        "专业翻译": "你是专业中英翻译官,只输出翻译结果,不添加任何多余解释、文字和符号。",

        # 技术角色
        "代码助手": "你是专业代码助手,只输出可运行代码,附带简洁注释,不废话。",

        # 生活角色
        "美食推荐官": "你是美食推荐官,根据需求推荐3个菜品,简洁不啰嗦。",

        # 默认角色
        "默认": "你是一个友好、简洁、专业的AI助手。"
    }
    # 返回对应角色的Prompt
    return role_template.get(role_name, role_template["默认"])


# ===================== 历史消息拼接 =====================
def concat_history(history, new_question):
    msg_list = history.copy()
    msg_list.append({"role": "user", "content": new_question})
    return msg_list


# ===================== AI调用函数 =====================
def ai_chat(messages, temperature=0.6, max_retry=3):
    for retry in range(max_retry):
        try:
            headers = {
                "Authorization": f"Bearer {TONGYI_API_KEY}",
                "Content-Type": "application/json"
            }
            data = {
                "model": "qwen-plus",
                "input": {"messages": messages},
                "temperature": temperature
            }
            res = requests.post(TONGYI_API_URL, headers=headers, json=data)
            result = res.json()
            return result["output"]["text"]
        except Exception as e:
            print(f"第{retry + 1}次重试...")
            time.sleep(1)
    return "调用失败"


# ===================== 带角色的对话函数 =====================
def chat_with_role(user_input, role_name, history=None):
    if history is None:
        history = []

    # 1. 获取角色模板(今天核心)
    role_prompt = get_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_reply = ai_chat(messages)

    # 4. 更新历史
    history.append({"role": "user", "content": user_input})
    history.append({"role": "assistant", "content": ai_reply})

    return ai_reply, history


# ===================== 测试 =====================
if __name__ == "__main__":
    history = []

    print("===== 角色:Python老师 =====")
    reply, history = chat_with_role("什么是变量?", "Python老师", history)
    print("AI:", reply)

    print("\n===== 角色:专业翻译 =====")
    reply, history = chat_with_role("I love coding", "专业翻译", history)
    print("AI:", reply)
相关推荐
2401_8858850412 小时前
芬兰语音通知接口怎样对接?语音提醒接入流程
android·前端·python·php·语音识别
大风起兮云飞扬丶12 小时前
Java——枚举
java·开发语言
小灰灰搞电子13 小时前
Rust+Slint 实现高级动态消息提示框源码分享
开发语言·rust
Dev _13 小时前
Python解释器安装在系统级目录导致命令行用户‌没有权限‌向该目录写入文件
开发语言·python
qq_4069810313 小时前
大白话rust系列08 当变量遮蔽遇上引用,探究变量遮蔽的本质
开发语言·后端·rust
喵了几个咪13 小时前
GoWind ShortPlay 拆解:不用模型的推荐闭环——埋点回流、三路召回与已看去重
开发语言·后端·微服务·golang·gowind
谙弆悕博士13 小时前
用 C 写了个 Windows 聊天室,踩了几个多线程和控制台的坑
c语言·开发语言·c++·windows·网络编程·聊天室
Dev _13 小时前
PyCharm旧进程仍在后台运行,导致新实例无法启动或连接
ide·python·pycharm
Canmag 兴隆磁性13 小时前
回复磁导率 μ_R:永磁体在动态磁路中的关键参数
开发语言·学习·r语言·永磁材料·充磁·磁导率
CRMEB系统商城14 小时前
鲜花零售的预售与积分营销
开发语言·人工智能·科技·小程序·零售