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)
相关推荐
兵慌码乱39 分钟前
面向桌面端的资产管理系统分层架构设计与核心模块实现
python·系统架构·sqlite·pyqt5·数据库设计·桌面应用开发·mvc架构
hboot2 小时前
AI工程师第三课 - 机器学习基础
python·scikit-learn·kaggle
顾林海7 小时前
Agent入门阶段-编程基础-Python:流程控制
python·agent·ai编程
呱呱复呱呱9 小时前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽14 小时前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码14 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱1 天前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵1 天前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio1 天前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户0332126663671 天前
使用 Python 从零创建 Word 文档
python