File size: 1,409 Bytes
0cde401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 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