Download scripts/rag_query.py from NoahIsARider/SCUT-SS: direct link, hf CLI and curl.
- Browser
- Download file 5.31 kB
-
https://huggingface.co/datasets/NoahIsARider/SCUT-SS/resolve/main/scripts/rag_query.py
- Command line
-
hf download hf://datasets/NoahIsARider/SCUT-SS/scripts/rag_query.py
-
curl -L -o rag_query.py https://huggingface.co/datasets/NoahIsARider/SCUT-SS/resolve/main/scripts/rag_query.py
5.31 kB
| """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() | |