"""大模型分析服务""" import json from openai import OpenAI from config import LLM_API_KEY, LLM_BASE_URL, LLM_MODEL # ====== 审计分析 Prompt 模板 ====== AUDIT_PROMPT_TEMPLATE = """你是一名经验丰富的医院内部审计专家。请对以下审计资料进行全面分析,并严格按照 JSON 格式输出结果。 {user_guidance_section} ## 审计资料 {content} {knowledge_section} ## 分析要求 1. 识别资料中的关键风险点 2. 判断合规性状况{compliance_hint} 3. 给出可操作的改进建议 4. 评估整体风险等级 5. {reference_hint} ## 输出格式(必须返回纯 JSON,不要包含 Markdown 代码块标记) {{ "analysis_type": "风险识别", "summary": "200字以内的核心分析摘要", "risk_level": "高/中/低/无", "findings": "逐条列出关键发现,每条用数字编号", "suggestions": "逐条列出改进建议,每条用数字编号", "references": "引用了知识库中的哪些制度/规范(如有),逐条列出;无则返回空字符串" }} """ KNOWLEDGE_PROMPT_HINT = """ ## 知识库参考材料 以下是与你本次审计相关的制度、规范和指南。请在分析时参考这些材料,并在"references"字段中注明引用了哪些制度条款。 {knowledge_content} """ def _get_client() -> OpenAI: """获取 OpenAI 客户端""" return OpenAI(api_key=LLM_API_KEY, base_url=LLM_BASE_URL) def analyze_audit_content(content: str, knowledge_context: str = "", user_guidance: str = "") -> dict: """调用大模型分析审计资料内容 Args: content: 审计资料正文内容 knowledge_context: 知识库参考材料文本(可选),为空则不引用知识库 user_guidance: 用户自定义指导文本(可选),如只分析某张表、指定输出风格等 """ if not LLM_API_KEY or LLM_API_KEY == "sk-your-api-key-here": return { "analysis_type": "风险识别", "summary": "【模拟分析】请先在 config.py 中配置 LLM_API_KEY 以启用真实分析。", "risk_level": "中", "findings": "1. 这是模拟分析结果,非真实大模型输出\n2. 请在 config.py 中配置 LLM_API_KEY 和 LLM_BASE_URL", "suggestions": "1. 配置大模型 API Key\n2. 重启服务后重试分析", "references": "" } # 构建知识库提示部分 if knowledge_context: knowledge_section = KNOWLEDGE_PROMPT_HINT.format(knowledge_content=knowledge_context) compliance_hint = "(对照知识库参考材料中的制度条款,逐条核对合规性)" reference_hint = "在 references 字段中注明分析时引用了知识库中的哪些制度、规范或指南" else: knowledge_section = "" compliance_hint = "" reference_hint = "如无知识库参考材料,references 字段返回空字符串" # 构建用户指导段(如果用户提供了指导文本) # 放在分析要求之后、输出格式之前,优先级最高 if user_guidance and user_guidance.strip(): user_guidance_section = ( "## ⚠️ 本次分析的特别指导(最高优先级,必须先读再分析)\n" "以下是用户对本次分析提出的特别要求。你必须主动、积极地按这些要求调整分析方向和输出风格," "而不是消极地说明哪些做不到:\n\n" + user_guidance.strip() + "\n\n" "执行原则(必须严格遵守):\n" "1. 如指导指定了分析范围(如某张工作表/某个字段/某段时间),就只分析该范围内的数据,严禁引用该范围以外的任何数据\n" "2. 如指导指定了风险类型(如单价异常/供应商集中度),就把该类风险作为分析重点\n" "3. 如指导指定了输出风格(如简短要点/表格/编号/散文),就严格按该风格输出\n" "4. 即便下方审计资料中包含其它工作表/其它范围的数据,也一律不得在 findings、summary、suggestions 中引用或提及\n" "5. 如用户指导与上述分析要求冲突,以本指导为准\n" "6. 不要在输出中说明'因用户要求只分析XX所以无法分析YY',而是直接按用户要求产出分析结果" ) else: user_guidance_section = "" user_guidance_section = "" prompt = AUDIT_PROMPT_TEMPLATE.format( content=content, knowledge_section=knowledge_section, user_guidance_section=user_guidance_section, compliance_hint=compliance_hint, reference_hint=reference_hint ) # === 临时调试日志(排查用户指导被忽略问题)=== try: import os as _os, datetime as _dt _log = _os.path.join(_os.path.dirname(__file__), "..", "_debug_prompt.log") with open(_log, "a", encoding="utf-8") as _f: _f.write("\n" + "="*70 + "\n") _f.write(f"[{_dt.datetime.now().isoformat()}]\n") _f.write(f"user_guidance 原文: [{user_guidance!r}]\n") _f.write(f"user_guidance_section 构建: [{user_guidance_section!r}]\n") _f.write(f"knowledge_context 长度: {len(knowledge_context)}\n") _f.write(f"content 长度: {len(content)}\n") _f.write(f"content 前200字: {content[:200]}\n") _f.write("---- 完整 prompt ----\n") _f.write(prompt + "\n") except Exception as _e: print(f"调试日志写入失败: {_e}") # === 调试日志结束 === try: client = _get_client() response = client.chat.completions.create( model=LLM_MODEL, messages=[ {"role": "system", "content": "你是一个专业的医院内部审计分析助手,始终以 JSON 格式返回分析结果。分析时应严格对照制度条款,给出有依据的结论。"}, {"role": "user", "content": prompt} ], temperature=0.3, response_format={"type": "json_object"} ) result_text = response.choices[0].message.content result = json.loads(result_text) def _ensure_str(val): """确保值为字符串(数组用换行连接)""" if isinstance(val, list): return "\n".join(str(v) for v in val) return str(val) if val is not None else "" # 确保字段完整 return { "analysis_type": result.get("analysis_type", "风险识别"), "summary": result.get("summary", ""), "risk_level": result.get("risk_level", "中"), "findings": _ensure_str(result.get("findings", "")), "suggestions": _ensure_str(result.get("suggestions", "")), "references": _ensure_str(result.get("references", "")), "raw_output": result_text } except Exception as e: return { "analysis_type": "风险识别", "summary": f"分析调用失败: {str(e)}", "risk_level": "中", "findings": f"调用大模型 API 时发生错误: {str(e)}", "suggestions": "检查 API Key 和网络连接后重试", "references": "", "raw_output": f"Error: {str(e)}" } # ====== 审计报告生成 ====== AUDIT_REPORT_PROMPT_TEMPLATE = """你是一名资深的医院内部审计专家,擅长撰写审计报告。请根据以下信息,撰写一份详尽、专业、规范的审计报告。 ## 审计项目信息 - 步骤名称:{step_name} - 所属项目:{project_name} - 所属年度:{year_name} - 项目大类:{category_name} ## 审计资料及分析结果 {docs_and_results} ## 报告要求 {report_desc} ## 知识库参考材料(医院内部制度、规范) {knowledge_content} ## 网络补充资料(行业最佳实践、法规要求) {web_content} ## 报告生成要求 1. 报告必须基于审计资料和大模型分析结果,客观反映审计发现 2. 报告应结合知识库中的内部制度要求和网络补充的外部法规/最佳实践 3. 报告应结构清晰、逻辑严密,结论有据可依 4. 报告应包含审计发现、风险评估、整改建议等核心内容 ## 输出格式(必须返回纯 JSON,不要包含 Markdown 代码块标记) {{ "title": "审计报告标题", "content": "完整的审计报告正文,使用 Markdown 格式,包含以下章节:\\n\\n## 一、审计概况\\n(审计依据、审计范围、审计时间等)\\n## 二、审计基本情况\\n(被审计事项的基本情况描述)\\n## 三、审计发现\\n(逐条列明发现的问题,引用审计资料和分析结果)\\n## 四、风险评估与定性\\n(对发现的问题进行风险评级和定性分析)\\n## 五、审计结论\\n(综合评价和审计意见)\\n## 六、整改建议\\n(逐条列出可操作的整改建议)\\n## 七、附录\\n(引用的审计资料清单、分析依据等)\\n\\n每个章节内容详实,不少于200字。", "references": "报告编制时参考的制度、法规和资料来源,逐条列出" }} """ def generate_audit_report( step_name: str, project_name: str, year_name: str, category_name: str, docs_and_results: str, report_desc: str, knowledge_content: str, web_content: str ) -> dict: """调用大模型生成审计报告 Args: step_name: 步骤名称 project_name: 项目名称 year_name: 年度 category_name: 大类名称 docs_and_results: 审计资料和分析结果汇总文本 report_desc: 报告要求和格式描述 knowledge_content: 知识库参考材料文本 web_content: 网络补充材料文本 """ if not LLM_API_KEY or LLM_API_KEY == "sk-your-api-key-here": return { "title": "【模拟报告】请先配置 LLM_API_KEY", "content": "请先在 config.py 中配置 LLM_API_KEY 以启用真实报告生成。", "references": "" } prompt = AUDIT_REPORT_PROMPT_TEMPLATE.format( step_name=step_name or "未指定", project_name=project_name or "未指定", year_name=year_name or "未指定", category_name=category_name or "未指定", docs_and_results=docs_and_results or "(无审计资料和分析结果)", report_desc=report_desc or "(无特殊要求,按标准审计报告格式编写)", knowledge_content=knowledge_content or "(未选择知识库,无内部制度参考材料)", web_content=web_content or "(无网络补充材料)" ) try: client = _get_client() response = client.chat.completions.create( model=LLM_MODEL, messages=[ {"role": "system", "content": "你是一名资深的医院内部审计专家,擅长撰写审计报告。报告应客观、详尽、规范,始终以 JSON 格式返回结果。"}, {"role": "user", "content": prompt} ], temperature=0.4, response_format={"type": "json_object"} ) result_text = response.choices[0].message.content result = json.loads(result_text) def _ensure_str(val): if isinstance(val, list): return "\n".join(str(v) for v in val) return str(val) if val is not None else "" return { "title": result.get("title", "审计报告"), "content": _ensure_str(result.get("content", "")), "references": _ensure_str(result.get("references", "")), "raw_output": result_text } except Exception as e: return { "title": "报告生成失败", "content": f"调用大模型 API 时发生错误: {str(e)}", "references": "", "raw_output": f"Error: {str(e)}" } # ====== 综合分析整合 Prompt ====== MERGE_PROMPT_TEMPLATE = """你是一名经验丰富的医院内部审计专家。现在有两份针对同一份审计资料的分析结果,一份是基于资料本身的直接分析,另一份是引用了知识库制度后的分析。请将两者的结果整合为一份更全面、更权威的综合分析报告。 ## 审计资料 {content} ## 直接分析结果(未引用知识库) - 分析摘要:{plain_summary} - 风险等级:{plain_risk} - 关键发现: {plain_findings} - 改进建议: {plain_suggestions} ## 引用知识库分析结果 - 分析摘要:{wiki_summary} - 风险等级:{wiki_risk} - 关键发现: {wiki_findings} - 改进建议: {wiki_suggestions} - 引用制度依据: {wiki_references} ## 整合要求 1. 合并两次分析的关键发现,去重并补充遗漏项 2. 综合两次的风险等级评估,给出最终等级(取较高者或说明理由) 3. 整合改进建议,确保可操作性和制度合规性 4. 保留知识库引用的制度依据 5. 摘要应概括两次分析的核心结论 ## 输出格式(必须返回纯 JSON,不要包含 Markdown 代码块标记) {{ "analysis_type": "综合分析", "summary": "200字以内的综合分析摘要", "risk_level": "高/中/低/无", "findings": "逐条列出整合后的关键发现,每条用数字编号", "suggestions": "逐条列出整合后的改进建议,每条用数字编号", "references": "引用了知识库中的哪些制度/规范,逐条列出;无则返回空字符串" }} """ def merge_analyses(content: str, plain_result: dict, wiki_result: dict) -> dict: """将直接分析结果和引用知识库分析结果整合为一份综合分析 Args: content: 原始审计资料内容 plain_result: 直接分析结果(不含知识库) wiki_result: 引用知识库的分析结果 """ if not LLM_API_KEY or LLM_API_KEY == "sk-your-api-key-here": return { "analysis_type": "综合分析", "summary": "【模拟分析】请先配置 LLM_API_KEY 以启用真实分析。", "risk_level": "中", "findings": "1. 模拟综合分析结果", "suggestions": "1. 配置大模型 API Key", "references": "", "raw_output": "" } prompt = MERGE_PROMPT_TEMPLATE.format( content=content[:3000], # 截断避免 token 超限 plain_summary=plain_result.get("summary", ""), plain_risk=plain_result.get("risk_level", ""), plain_findings=plain_result.get("findings", ""), plain_suggestions=plain_result.get("suggestions", ""), wiki_summary=wiki_result.get("summary", ""), wiki_risk=wiki_result.get("risk_level", ""), wiki_findings=wiki_result.get("findings", ""), wiki_suggestions=wiki_result.get("suggestions", ""), wiki_references=wiki_result.get("references", "") ) try: client = _get_client() response = client.chat.completions.create( model=LLM_MODEL, messages=[ {"role": "system", "content": "你是一个专业的医院内部审计分析助手,擅长整合多份分析报告,输出全面且不重复的结论。始终以 JSON 格式返回结果。"}, {"role": "user", "content": prompt} ], temperature=0.3, response_format={"type": "json_object"} ) result_text = response.choices[0].message.content result = json.loads(result_text) def _ensure_str(val): if isinstance(val, list): return "\n".join(str(v) for v in val) return str(val) if val is not None else "" return { "analysis_type": result.get("analysis_type", "综合分析"), "summary": result.get("summary", ""), "risk_level": result.get("risk_level", "中"), "findings": _ensure_str(result.get("findings", "")), "suggestions": _ensure_str(result.get("suggestions", "")), "references": _ensure_str(result.get("references", "")), "raw_output": result_text } except Exception as e: return { "analysis_type": "综合分析", "summary": f"整合分析失败: {str(e)}", "risk_level": "中", "findings": f"调用大模型 API 时发生错误: {str(e)}", "suggestions": "检查 API Key 和网络连接后重试", "references": "", "raw_output": f"Error: {str(e)}" } # ====== 审计实施方案生成 ====== AUDIT_PLAN_PROMPT_TEMPLATE = """你是一名资深的医院内部审计专家,擅长制定审计实施方案。请根据以下信息,制定一份详尽、专业、可操作的审计实施方案。 ## 审计项目描述 {project_desc} ## 知识库参考材料(医院内部制度、规范) {knowledge_content} ## 网络补充资料(行业最佳实践、法规要求) {web_content} ## 方案生成要求 1. 方案必须结合知识库中的内部制度要求和网络补充的外部法规/最佳实践 2. 方案应具有可操作性,明确审计范围、审计重点、审计方法 3. 方案应包含时间安排和人员分工建议 4. 方案应识别重点风险领域和关键控制点 ## 输出格式(必须返回纯 JSON,不要包含 Markdown 代码块标记) {{ "title": "审计实施方案标题", "content": "完整的审计实施方案正文,使用 Markdown 格式,包含以下章节:\\n\\n## 一、审计目的\\n## 二、审计范围\\n## 三、审计依据\\n## 四、审计重点和关键控制点\\n## 五、审计方法\\n## 六、审计时间安排\\n## 七、人员分工\\n## 八、审计风险及应对措施\\n## 九、审计质量保障措施\\n\\n每个章节内容详实,不少于200字。", "references": "方案编制时参考的制度、法规和资料来源,逐条列出" }} """ def generate_audit_plan(project_desc: str, knowledge_content: str, web_content: str) -> dict: """调用大模型生成审计实施方案 Args: project_desc: 审计项目描述 knowledge_content: 知识库参考材料文本 web_content: 网络补充材料文本 """ if not LLM_API_KEY or LLM_API_KEY == "sk-your-api-key-here": return { "title": "【模拟方案】请先配置 LLM_API_KEY", "content": "请先在 config.py 中配置 LLM_API_KEY 以启用真实方案生成。", "references": "" } prompt = AUDIT_PLAN_PROMPT_TEMPLATE.format( project_desc=project_desc, knowledge_content=knowledge_content or "(未选择知识库,无内部制度参考材料)", web_content=web_content or "(无网络补充材料)" ) try: client = _get_client() response = client.chat.completions.create( model=LLM_MODEL, messages=[ {"role": "system", "content": "你是一名资深的医院内部审计专家,擅长制定审计实施方案。方案应详尽、专业、具有可操作性,始终以 JSON 格式返回结果。"}, {"role": "user", "content": prompt} ], temperature=0.4, response_format={"type": "json_object"} ) result_text = response.choices[0].message.content result = json.loads(result_text) def _ensure_str(val): if isinstance(val, list): return "\n".join(str(v) for v in val) return str(val) if val is not None else "" return { "title": result.get("title", "审计实施方案"), "content": _ensure_str(result.get("content", "")), "references": _ensure_str(result.get("references", "")), "raw_output": result_text } except Exception as e: return { "title": "方案生成失败", "content": f"调用大模型 API 时发生错误: {str(e)}", "references": "", "raw_output": f"Error: {str(e)}" }