# api/courseware/references.py """ Reference 规范:所有 RAG 生成内容必须附带引用。 - 本地 VDB: [Source: Filename/Page] - Web Search: [Source: URL] """ from typing import List, Dict, Any def format_ref_item(item: Dict[str, Any]) -> str: """单条引用格式化为 [Source: ...]。""" t = (item.get("type") or "").strip().lower() if t == "web" or item.get("url"): url = (item.get("url") or "").strip() if url: return f"[Source: {url}]" # 默认按本地 VDB source = (item.get("source") or item.get("source_file") or "uploaded").strip() page = (item.get("page") or "").strip() if page: return f"[Source: {source}/{page}]" return f"[Source: {source}]" def format_references(refs: List[Dict[str, Any]]) -> str: """将引用列表格式化为多行 [Source: ...],去重保持顺序。""" seen: set = set() lines: List[str] = [] for r in refs: s = format_ref_item(r) if s and s not in seen: seen.add(s) lines.append(s) return "\n".join(lines) if lines else "" def append_references_to_content(content: str, refs: List[Dict[str, Any]]) -> str: """在正文末尾追加 References 小节。""" ref_block = format_references(refs) if not ref_block: return content.rstrip() return content.rstrip() + "\n\n## References\n\n" + ref_block