File size: 5,312 Bytes
1d8c46a | 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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | """Query the SCUT-SS RAG library.
python scripts/rag_query.py "软件测试的黑盒测试有哪些方法"
python scripts/rag_query.py "数据库范式" -k 5 --course "数据库系统"
python scripts/rag_query.py "解释一下 ATAM" --ask # needs LLM env vars
LLM env vars (optional, any OpenAI-compatible endpoint):
OPENAI_API_KEY / OPENAI_BASE_URL / OPENAI_MODEL
"""
import argparse
import json
import sys
import textwrap
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import llm # noqa: E402
from vectorstore import Index # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_INDEX = ROOT / "vectorstore"
PROMPT = """你是华南理工大学软件学院的学习助手。请只依据下面提供的资料回答问题;
资料里没有的内容请明确说明"资料中没有提到",不要编造。回答用中文,尽量给出要点式结构,
并在关键结论后标注来源(用 [1] [2] 对应资料编号)。
资料:
{context}
问题:{question}
"""
def retrieve(index, query, k, course=None):
hits = index.search(query, k=max(k * 6, 20))
if course:
hits = [h for h in hits if course in (h[0].get("course") or "")] or hits
return hits[:k]
def build_context(hits):
parts = []
for i, (chunk, score) in enumerate(hits, 1):
parts.append(
f"[{i}] 来源:{chunk['path']}|{chunk.get('section', '')}\nURL: {chunk.get('url', '')}\n{chunk['text']}\n"
)
return "\n".join(parts)
def ask_llm(prompt, provider=None, base_url=None, api_key=None, model=None):
"""Call a cloud model (any OpenAI-compatible endpoint). Returns (answer, conf) or (None, err)."""
try:
answer, conf = llm.chat(
[
{"role": "system", "content": "你是一个严谨的课程学习助手。"},
{"role": "user", "content": prompt},
],
provider=provider,
base_url=base_url,
api_key=api_key,
model=model,
)
return answer, conf
except Exception as exc: # noqa: BLE001
return None, llm.http_error_hint(exc)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("question")
ap.add_argument("-k", type=int, default=5)
ap.add_argument("--course", default=None, help="limit to one course, e.g. 软件测试")
ap.add_argument("--index", default=str(DEFAULT_INDEX))
ap.add_argument("--ask", action="store_true", help="call a cloud LLM with the retrieved context")
ap.add_argument("--provider", default=None, help="one of: " + ", ".join(llm.available_presets()))
ap.add_argument("--base-url", default=None)
ap.add_argument("--model", default=None)
ap.add_argument(
"--save-context",
default=None,
metavar="FILE",
help="dump question+context to a Markdown file so an external AI (IDE/chat) can read it",
)
ap.add_argument("--json", action="store_true")
args = ap.parse_args()
for _s in (sys.stdout, sys.stderr):
try:
_s.reconfigure(encoding="utf-8", errors="replace")
except Exception: # noqa: BLE001
pass
index = Index(args.index)
hits = retrieve(index, args.question, args.k, args.course)
if args.json:
print(json.dumps([{"score": s, **c} for c, s in hits], ensure_ascii=False, indent=2))
return
context = build_context(hits)
if args.save_context:
out = Path(args.save_context)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(
"# 请基于以下资料回答问题\n\n"
f"**问题**:{args.question}\n\n"
"**要求**:只依据下列资料作答;资料未覆盖的内容请明确说明「资料中没有提到」;"
"关键结论后标注来源编号 [1] [2]。\n\n"
"## 检索到的资料\n\n" + context,
encoding="utf-8",
)
print(f"上下文已写入 {out} —— 在 IDE / 聊天窗口里 @ 这个文件,让外部模型回答即可。")
if args.ask:
answer, conf = ask_llm(
PROMPT.format(context=context, question=args.question),
provider=args.provider,
base_url=args.base_url,
model=args.model,
)
if answer is None:
print(f"调用云端模型失败:{conf}\n下面是检索到的资料,可用 --save-context 导出后交给外部模型:\n")
else:
print(f"[{conf.get('provider') or 'custom'} | {conf['model']} @ {conf['base_url']}]\n")
print(answer)
print("\n" + "=" * 60 + "\n")
print(f"检索到 {len(hits)} 条资料(backend={index.meta['backend']}):\n")
for i, (chunk, score) in enumerate(hits, 1):
head = f"[{i}] {chunk['path']}" + (f" · {chunk['section']}" if chunk.get("section") else "")
print(head)
print(f" score={score:.4f} {chunk.get('url','')}")
print(textwrap.indent(textwrap.shorten(chunk["text"], 300, placeholder=" ..."), " "))
print()
if __name__ == "__main__":
main()
|