RAG-DEMO/src/10_generate_answer.py

48 lines
1.2 KiB
Python

from __future__ import annotations
import argparse
import json
from typing import Any
from graphrag_platform.cli import stage_main
from graphrag_platform.runtime import StageContext
from graphrag_platform.stage_loader import load_stage
def run(
context: StageContext,
*,
question: str,
top_k: int | None = None,
) -> dict[str, Any]:
retrieval = load_stage(9).run(
context,
question=question,
top_k=top_k,
)
answer = context.llm.complete_text(
(
"Answer only from the supplied GraphRAG context. Cite supporting sources "
"using [S1], [S2], and so on. If the context does not support an answer, "
"state that clearly. Do not invent citations."
),
json.dumps(retrieval, ensure_ascii=False),
)
return {
"question": question,
"answer": answer,
"sources": retrieval["sources"],
}
def run_from_args(
context: StageContext, args: argparse.Namespace
) -> dict[str, Any]:
if not args.question:
raise ValueError("--question is required for stage 10")
return run(context, question=args.question, top_k=args.top_k)
if __name__ == "__main__":
stage_main(10, run_from_args)