一、直接上源码
import os
import dashscope
THINKING_HATS_PROMPTS = {"white": "分析该话题的事实、数据和客观信息,请提供中立的总结。","red": "根据直觉和情感对该话题进行回应,请包括主观感受。","black": "对该话题进行批判性评价,识别潜在的风险、问题或弱点。","yellow": "乐观地评估该话题,强调潜在的好处和机会。","green": "围绕该话题生成创造性的想法和创新的解决方案。","blue": "组织并规划讨论,总结关键点并指导下一步行动。"
}
def generate_hat_response(text, hat_color):prompt = THINKING_HATS_PROMPTS.get(hat_color, "")if not prompt:raise ValueError(f"无效的帽子颜色: {hat_color}")messages = [{"role": "system", "content": prompt},{"role": "user", "content": text}]response = dashscope.Generation.call(api_key=os.getenv("DASHSCOPE_API_KEY"),model="qwen-plus",messages=messages,result_format="message")return response.get("output", {}).get("choices", [{}])[0].get("message", {}).get("content", "")
def extract_core_point(response):return response.split("\n", 1)[0] if response else "无核心观点"
def save_results_to_markdown(responses, output_file="thinkResult.md"):with open(output_file, "w", encoding="utf-8") as f:f.write("# 六顶思考帽分析结果\n\n")f.write("| 帽子 | 核心观点 |\n")f.write("|------|----------|\n")for hat_color, response in responses.items():hat_name = {"white": "白帽","red": "红帽","black": "黑帽","yellow": "黄帽","green": "绿帽","blue": "蓝帽"}.get(hat_color, "未知帽子")core_point = extract_core_point(response)f.write(f"| {hat_name} | {core_point} |\n")f.write("\n## 详细观点\n\n")for hat_color, response in responses.items():hat_name = {"white": "## 白帽","red": "## 红帽","black": "## 黑帽","yellow": "## 黄帽","green": "## 绿帽","blue": "## 蓝帽"}.get(hat_color, "## 未知帽子")f.write(f"{hat_name}\n\n{response}\n\n")
def six_thinking_hats_agent():print("请输入话题,输入两个回车键后开始分析:")topic_lines = []while True:line = input()if line == "":if len(topic_lines) == 0:breakelse:topic = "\n".join(topic_lines)breaktopic_lines.append(line)if not topic.strip():print("输入的话题不能为空!")returnprint(f"正在处理话题:{topic}\n")responses = {}for hat_color in THINKING_HATS_PROMPTS.keys():try:print(f"正在生成 {hat_color} 帽的回应...")response = generate_hat_response(topic, hat_color)responses[hat_color] = responseexcept Exception as e:responses[hat_color] = f"生成回应时出错:{e}"print("\n--- 六顶思考帽回应 ---\n")for hat_color, response in responses.items():hat_name = {"white": "[白帽]","red": "[红帽]","black": "[黑帽]","yellow": "[黄帽]","green": "[绿帽]","blue": "[蓝帽]"}.get(hat_color, "[未知帽子]")print(f"{hat_name} 回应:\n{response}\n")save_results_to_markdown(responses)print("结果已保存到 thinkResult.md 文件中。")if __name__ == "__main__":six_thinking_hats_agent()
二、执行效果