Skip to content

示例 02 RAG 接口与评测最小闭环

本示例对应主线第 4-5 章《检索增强入门 / 进阶》。目标是给你一个最小可解释的 RAG 闭环:

  • 输入问题。
  • 检索证据。
  • 生成带引用的回答。
  • 前端按结构展示答案与引用。
  • 保留最小评测数据结构,方便后续回归。

1. 接口目标

示例场景:企业制度问答。 请求:用户问“年假最晚什么时候提交申请?” 响应需要包含:

  • 回答正文。
  • 引用列表。
  • 置信度。
  • 是否需要人工复核。

2. Python 服务端最小接口

python
from typing import Any


def retrieve(question: str) -> list[dict[str, Any]]:
    return [
        {
            "doc_id": "leave_policy_v2",
            "title": "员工休假制度 V2",
            "quote": "年假申请原则上需至少提前 3 个工作日提交。",
        }
    ]


def answer_with_rag(question: str) -> dict[str, Any]:
    citations = retrieve(question)
    if not citations:
        return {
            "answer": "根据当前资料无法确认。",
            "citations": [],
            "confidence": "low",
            "need_human_review": True,
        }

    return {
        "answer": "根据当前制度,年假申请原则上需至少提前 3 个工作日提交。",
        "citations": citations,
        "confidence": "high",
        "need_human_review": False,
    }

3. 前端响应结构与回答卡片

3.1 TypeScript 接口

ts
export interface Citation {
  doc_id: string;
  title: string;
  quote: string;
}

export interface RagAnswer {
  answer: string;
  citations: Citation[];
  confidence: 'high' | 'medium' | 'low';
  need_human_review: boolean;
}

3.2 回答卡片结构建议

页面建议包含:

  • 回答正文。
  • 置信度标签。
  • 引用展开区。
  • need_human_review 时的风险提示。
  • “这个回答是否有帮助”的反馈入口。

4. 最小评测样本结构

json
{
  "id": "leave_001",
  "question": "年假最晚什么时候提交申请?",
  "expected_answer": "至少提前 3 个工作日提交",
  "allowed_docs": ["leave_policy_v2"],
  "must_refuse": false,
  "tags": ["hr", "policy"]
}

5. 最小评测检查项

每条样本至少检查:

  • 回答是否命中关键结论。
  • 是否引用了允许的文档。
  • 文本是否和引用一致。
  • 不确定时是否能进入人工复核或拒答。

6. 前端截图建议

建议保留:

  • 正常回答 + 引用展开态。
  • need_human_review=true 风险态。
  • 反馈提交后的结果态。
  • 评测结果表格或截图。