Files
DeepTutor/benchmark/data_generation/request_pipeline.py
2026-11-07 23:17:54 +08:00

379 lines
12 KiB
Python

#!/usr/bin/env python3
"""
Request Generation Pipeline
Generate evaluation requests from existing benchmark task entries:
- one solve request per profile
- one question request per profile (generated by LLM from topic, in English)
Input:
benchmark/data/generated/benchmark_<timestamp>/*.json
Output:
benchmark/data/generated/requests_<timestamp>/
- <profile_entry_id>.json
- _all_requests.jsonl
- _summary.json
"""
from __future__ import annotations
import argparse
import asyncio
import json
import logging
import sys
from datetime import datetime
from pathlib import Path
from typing import Any
import yaml
# Ensure project root is importable when script is executed directly.
_THIS_FILE = Path(__file__).resolve()
_PROJECT_ROOT_FOR_IMPORT = _THIS_FILE.parents[2]
if str(_PROJECT_ROOT_FOR_IMPORT) not in sys.path:
sys.path.insert(0, str(_PROJECT_ROOT_FOR_IMPORT))
from benchmark.data_generation.llm_utils import call_llm
logger = logging.getLogger("benchmark.request_pipeline")
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
DEFAULT_CONFIG = PROJECT_ROOT / "benchmark" / "config" / "benchmark_config.yaml"
def _load_config(path: Path) -> dict[str, Any]:
with open(path, encoding="utf-8") as f:
return yaml.safe_load(f) or {}
def _normalize_space(text: str) -> str:
return " ".join((text or "").strip().split())
def _clean_llm_text(text: str) -> str:
cleaned = _normalize_space(text)
if cleaned.startswith("```") and cleaned.endswith("```"):
cleaned = _normalize_space(cleaned.strip("`"))
cleaned = cleaned.strip().strip('"').strip("'")
return cleaned
def _to_profile_level(profile: dict[str, Any]) -> str:
profile_id = str(profile.get("profile_id", "")).lower()
if "beginner" in profile_id:
return "beginner"
if "advanced" in profile_id:
return "advanced"
return "intermediate"
def _pick_profile_topic(entries: list[dict[str, Any]]) -> str:
titles: list[str] = []
for entry in entries:
task = entry.get("task", {}) or {}
title = _normalize_space(str(task.get("title", "")))
if title and title not in titles:
titles.append(title)
if not titles:
return "the current study topic"
if len(titles) == 1:
return titles[0]
return " | ".join(titles[:3])
def _build_solve_query(profile: dict[str, Any], topic: str, entries: list[dict[str, Any]]) -> str:
# Prefer an existing initial message only when it already appears to be English.
for entry in entries:
task = entry.get("task", {}) or {}
initial_message = _normalize_space(str(task.get("initial_message", "")))
if initial_message and initial_message.isascii():
return initial_message
level = _to_profile_level(profile)
if level == "beginner":
depth = "Please keep it foundational and concrete."
elif level == "advanced":
depth = "Please include concise formal reasoning."
else:
depth = "Please explain step by step with one concrete example."
return (
f"I am studying {topic} and need help solving a representative problem from this topic. "
f"{depth}"
)
async def _build_question_query_with_llm(profile: dict[str, Any], topic: str) -> str:
level = _to_profile_level(profile)
if level == "beginner":
level_hint = "beginner-level, simple and foundational"
elif level == "advanced":
level_hint = "advanced-level, slightly challenging"
else:
level_hint = "intermediate-level, moderate difficulty"
system_prompt = (
"You are generating realistic student requests for benchmark evaluation. "
"Return exactly one short request sentence in English only."
)
user_prompt = (
"Write one realistic student request asking a tutor to generate exactly one practice question.\n"
f"Topic: {topic}\n"
f"Difficulty preference: {level_hint}\n"
"Constraints:\n"
"- English only\n"
"- Do not mention benchmark, evaluation, profile, or gaps\n"
"- Ask for exactly one question\n"
"- Ask not to reveal the answer yet\n"
"Output only the request sentence."
)
try:
query = await call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
temperature=0.3,
max_tokens=128,
)
cleaned = _clean_llm_text(query)
if cleaned:
return cleaned
except Exception as e:
logger.warning("LLM generation failed for question request, using fallback template: %s", e)
# Safe fallback in English
return (
f"I just studied {topic}. Please give me exactly one practice question at {level_hint} "
"difficulty, and do not show the answer yet."
)
def _group_entries_by_profile(entries: list[dict[str, Any]]) -> dict[tuple[str, str], list[dict[str, Any]]]:
groups: dict[tuple[str, str], list[dict[str, Any]]] = {}
for entry in entries:
kb_name = str(entry.get("kb_name", ""))
profile = entry.get("profile", {}) or {}
profile_id = str(profile.get("profile_id", "unknown"))
key = (kb_name, profile_id)
groups.setdefault(key, []).append(entry)
return groups
async def _build_request_record_for_profile(
kb_name: str,
profile_id: str,
entries: list[dict[str, Any]],
) -> dict[str, Any]:
profile = entries[0].get("profile", {}) or {}
topic = _pick_profile_topic(entries)
question_query = await _build_question_query_with_llm(profile, topic)
profile_entry_id = f"{kb_name}_{profile_id}"
task_ids = []
for entry in entries:
task = entry.get("task", {}) or {}
task_id = str(task.get("task_id", ""))
if task_id:
task_ids.append(task_id)
return {
"profile_entry_id": profile_entry_id,
"kb_name": kb_name,
"profile_id": profile_id,
"topic": topic,
"source_task_ids": sorted(set(task_ids)),
"solve_request": {
"query": _build_solve_query(profile, topic, entries),
},
"question_request": {
"query": question_query,
},
}
def _discover_latest_benchmark_dir(base_output_dir: Path) -> Path:
candidates = [
p for p in base_output_dir.glob("benchmark_*")
if p.is_dir() and p.name[10:].replace("_", "").isdigit()
]
if not candidates:
raise FileNotFoundError(
f"No benchmark_* directories found under: {base_output_dir}"
)
return max(candidates, key=lambda p: p.stat().st_mtime)
def _load_entries(input_dir: Path, limit: int) -> list[dict[str, Any]]:
files = sorted(
p for p in input_dir.glob("*.json")
if not p.name.startswith("_")
)
if limit > 0:
files = files[:limit]
if not files:
raise ValueError(f"No entry JSON files found in: {input_dir}")
entries: list[dict[str, Any]] = []
for path in files:
with open(path, encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
entries.append(data)
else:
logger.warning("Skip non-dict entry file: %s", path)
return entries
def _save_requests(output_dir: Path, records: list[dict[str, Any]]) -> None:
output_dir.mkdir(parents=True, exist_ok=True)
# Save one request file per profile
for rec in records:
profile_entry_id = str(rec.get("profile_entry_id", "unknown"))
out_path = output_dir / f"{profile_entry_id}.json"
with open(out_path, "w", encoding="utf-8") as f:
json.dump(rec, f, ensure_ascii=False, indent=2)
# Save combined JSONL
jsonl_path = output_dir / "_all_requests.jsonl"
with open(jsonl_path, "w", encoding="utf-8") as f:
for rec in records:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
def _save_summary(
output_dir: Path,
*,
input_dir: Path,
timestamp: str,
num_profiles: int,
num_input_entries: int,
) -> Path:
summary = {
"timestamp": timestamp,
"input_dir": str(input_dir),
"output_dir": str(output_dir),
"num_input_entries": num_input_entries,
"num_profiles": num_profiles,
}
summary_path = output_dir / "_summary.json"
with open(summary_path, "w", encoding="utf-8") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
return summary_path
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Generate solve/question requests from benchmark task entries."
)
parser.add_argument(
"--config",
default=str(DEFAULT_CONFIG),
help=f"Benchmark config path (default: {DEFAULT_CONFIG})",
)
parser.add_argument(
"--input-dir",
default=None,
help=(
"Input benchmark entry directory (e.g. benchmark/data/generated/benchmark_YYYYMMDD_HHMMSS). "
"If omitted, auto-pick latest benchmark_* directory."
),
)
parser.add_argument(
"--output-dir",
default=None,
help=(
"Output directory. If omitted, writes to "
"benchmark/data/generated/requests_<timestamp>."
),
)
parser.add_argument(
"--limit",
type=int,
default=0,
help="Only process first N entries (0 = all).",
)
return parser.parse_args()
async def _generate_records(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
groups = _group_entries_by_profile(entries)
logger.info("Grouped into %d profiles", len(groups))
records: list[dict[str, Any]] = []
for (kb_name, profile_id), profile_entries in sorted(groups.items()):
rec = await _build_request_record_for_profile(
kb_name=kb_name,
profile_id=profile_id,
entries=profile_entries,
)
records.append(rec)
return records
async def async_main() -> None:
args = _parse_args()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
)
cfg_path = Path(args.config)
if not cfg_path.is_absolute():
cfg_path = (PROJECT_ROOT / cfg_path).resolve()
cfg = _load_config(cfg_path)
base_output_dir = Path(cfg.get("output", {}).get("output_dir", "./benchmark/data/generated"))
if not base_output_dir.is_absolute():
base_output_dir = (PROJECT_ROOT / base_output_dir).resolve()
if args.input_dir:
input_dir = Path(args.input_dir)
if not input_dir.is_absolute():
input_dir = (PROJECT_ROOT / input_dir).resolve()
else:
input_dir = _discover_latest_benchmark_dir(base_output_dir)
if not input_dir.exists():
raise FileNotFoundError(f"Input dir not found: {input_dir}")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
if args.output_dir:
output_dir = Path(args.output_dir)
if not output_dir.is_absolute():
output_dir = (PROJECT_ROOT / output_dir).resolve()
else:
output_dir = base_output_dir / f"requests_{timestamp}"
entries = _load_entries(input_dir, args.limit)
logger.info("Loaded %d benchmark task entries from %s", len(entries), input_dir)
records = await _generate_records(entries)
_save_requests(output_dir, records)
summary_path = _save_summary(
output_dir,
input_dir=input_dir,
timestamp=timestamp,
num_profiles=len(records),
num_input_entries=len(entries),
)
print("\nDone.")
print(f"Input dir : {input_dir}")
print(f"Output dir: {output_dir}")
print(f"Summary : {summary_path}")
print(f"Profiles : {len(records)}")
print(f"Input tasks: {len(entries)}")
def main() -> None:
asyncio.run(async_main())
if __name__ == "__main__":
main()