当 LLM 无法将声明与源 URL 绑定时,RAG 引用就会失败。 Scavio 的类型化 JSON 为每个检索到的片段提供一个链接字段,从而使引用步骤具有确定性。本教程将介绍构建过程。
前置条件
- Python 3.10+
- Scavio API 密钥
- LLM API 密钥
操作指南
步骤 1: 检索候选人
Scavio /搜索问题。
Python
import os, requests
H = {'x-api-key': os.environ['SCAVIO_API_KEY']}
def retrieve(q, n=8):
r = requests.post('https://api.scavio.dev/api/v1/search', headers=H, json={'query': q}).json()
return r.get('organic_results', [])[:n]步骤 2: 建立编号源列表
每个来源都有一个索引。
Python
def sources(results):
return [(i, r['link'], r.get('snippet', '')) for i, r in enumerate(results, start=1)]步骤 3: 使用引用标记提示 LLM
严格指导。
Text
# Prompt:
# 'Answer the question using ONLY the provided sources.
# Every claim must be followed by [N] where N is the source index.
# Sources:
# [1] {url}: {snippet}
# [2] {url}: {snippet}
# ...'步骤 4: 验证引用标记
显示用户之前进行正则表达式检查。
Python
import re
def validate(answer, n_sources):
cites = set(int(m) for m in re.findall(r'\[(\d+)\]', answer))
return cites and max(cites) <= n_sources步骤 5: 使用链接引用呈现答案
[1] 成为可点击的链接。
Python
def render(answer, sources):
out = answer
for i, url, _ in sources:
out = out.replace(f'[{i}]', f'[[{i}]]({url})')
return outPython 示例
Python
# Per query: 1 Scavio call + 1 LLM call. Cost ~$0.005-0.02 depending on LLM.JavaScript 示例
JavaScript
// Same in TS.预期输出
JSON
User-facing answer with clickable citations. Each citation links to the original source, satisfying RAG trust requirements.