RAG 相关性
使用“RAG 相关性”模板,在调用 LLM 之前检查检索到的片段是否回答了查询,并决定何时检索更多上下文。
目标: 不再把无关的片段发送给你的 LLM。针对查询为每个检索到的片段打分,保留有用的片段,当没有片段能回答问题时检索更多内容。
创建决策
模板 → RAG 相关性 → 创建决策:
| 部分 | 内容 |
|---|---|
| 状态 | query(字符串,必填),chunk(字符串,必填) |
relevant | probability——这个片段是否有助于回答查询? |
relevance | score——none、partial、direct |
retrieve_more | probability——系统是否应在回答之前检索更多上下文? |
| 策略 | 无——每个回答都返回 continue |
调用
curl -X POST https://api.dcision.io/v1/decisions/rag-relevance \
-H "Authorization: Bearer $DCISION_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"state": {
"query": "What is the refund window for annual plans?",
"chunk": "Annual plans can be refunded within 30 days of purchase."
}
}'{
"decision_id": "dec_Gt5Mv1Qz7Wp3Kx9Rc2Ln",
"execution_id": "exec_Bw8Ls4Ty2Dq6Hn9Vk1Zf",
"schema": "rag-relevance",
"version": 1,
"result": { "relevant": 0.96, "relevance": "direct", "retrieve_more": 0.08 },
"confidence": { "relevant": 0.92, "relevance": 0.865, "retrieve_more": 0.84 },
"scores": { "relevance": 2.91 },
"action": "continue",
"action_reason": { "type": "default" },
"metrics": { "latency_ms": 334, "engine": "jev", "model": "jev-1.13.0", "estimated_cost_usd": 0.00001092, "input_tokens": 260, "output_tokens": 30 }
}添加策略
该模板没有规则,因此行动始终是 continue。加上两条规则就能让行动变得有意义——丢弃无关片段,请求更多上下文:
[
{ "field": "relevance", "on": "output", "operator": "eq", "value": "none", "action": "block" },
{ "field": "retrieve_more", "on": "output", "operator": "gte", "value": 0.7, "action": "fallback" }
]据此行动
并行为检索到的片段打分——每个片段是一次决策——保留通过的片段,然后再调用 LLM:
async function relevantChunks(query, chunks) {
const decisions = await Promise.all(
chunks.map(async (chunk) => {
const response = await fetch("https://api.dcision.io/v1/decisions/rag-relevance", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.DCISION_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ state: { query, chunk: chunk.text } }),
});
return response.ok ? { chunk, decision: await response.json() } : { chunk, decision: null };
}),
);
const kept = decisions
.filter(({ decision }) => !decision || decision.action !== "block") // keep on errors
.sort((a, b) => (b.decision?.result.relevant ?? 0) - (a.decision?.result.relevant ?? 0));
const needMore = decisions.every(({ decision }) => decision?.action === "fallback");
return { kept: kept.map(({ chunk }) => chunk), needMore };
}调优
- 注意调用量:每个问题 10 个片段就是 10 次决策和 10 个请求。请同时规划检索规模和你的速率限制,并且只为检索器排名靠前的结果打分。
- 或者在一次调用中为固定大小的候选列表打分:把排名靠前的段落放进状态——
{ "query": …, "passages": [ … ] }——并为每个位置定义一个 probability 问题,例如passage_3:"Does `passages[3]` help answer `query`?"(每个决策最多 64 个问题)。整个候选列表只需一个请求、只计费一次决策;请让状态保持在 token 预算之内。 - 如果片段包含私密文档,关闭
storeInput。 - 在
context中描述语料库(“某薪资产品的内部帮助中心”),以便引擎判断部分匹配。 - 用
relevant排序,用relevance把关:概率用于给片段排序,级别用于丢弃无用的片段。如果想要单个数字,可以在复合指标中把它们结合起来。