campus-rag-backend / app /query_plan.py
github-actions[bot]
sync from github main b4107dd
9f57624
Raw History Blame Contribute Delete
26.7 kB
"""Ground a search plan in the user's words before running any retrieval."""
from __future__ import annotations
import re
from datetime import datetime, timezone, timedelta
from functools import lru_cache
import json
from typing import Literal
from pydantic import BaseModel, Field
from . import department_focus as departments
from .freshness import current_term, query_term, says_this_term
from .course_identity import PROFILE_REFERENCE, instructor_name, instructor_names, course_level, is_course_list, is_single_offering_question, resolve_course_question
from .document_focus import tuition_row_key
from .faculty import PERSON_FIELDS, PERSON_REFERENCE, PROFILE_FIELDS, ROSTER
from .query_transform import normalize_search_terms
KST = timezone(timedelta(hours=9))
TOPICS = re.compile(r"νœ΄ν•™|볡학|μ „κ³Ό|λ³΅μˆ˜μ „κ³΅|뢀전곡|μ‘Έμ—…|μˆ˜κ°•|곡결|μΆœμ„|성적|μž₯ν•™|λ“±λ‘κΈˆ|κ΅ν™˜ν•™μƒ|κ΅ν™˜μˆ˜ν•™|κΈ°μˆ™μ‚¬|μƒν™œκ΄€|λ„μ„œκ΄€|증λͺ…μ„œ|상담센터|λ³΄κ±΄μ§„λ£Œμ†Œ|μ™€μ΄νŒŒμ΄|μ·¨μ—…|κ°•μ˜κ³„νš|ꡐ재|(?<!인)곡지(?!λŠ₯)|μΊ‘μŠ€ν†€|학생증|μ…”ν‹€[ \t]*λ²„μŠ€")
REFERENT = re.compile(r"κ±°κΈ°|κ·Έκ³³|κ·Έκ±°|그것|ν•΄λ‹Ή\s*(?:μ‹ μ²­|ν”„λ‘œκ·Έλž¨)|κ·Έ\s*(?:μ‹ μ²­|ν”„λ‘œκ·Έλž¨|μž₯ν•™κΈˆ|λΆ€μ„œ)")
_GENERIC_OFFICE = re.compile(r"(?<![κ°€-힣A-Za-z])(?:ν•™λΆ€|ν•™κ³Ό|전곡)\s*사무싀")
_CONTACT_RE = re.compile(r"μ „ν™”\s*번호|μ—°λ½μ²˜")
SCHOOL_ALIASES = {"λΆ€κ²½λŒ€": "λΆ€κ²½λŒ€ν•™κ΅", "μ œμ£ΌλŒ€": "μ œμ£ΌλŒ€ν•™κ΅", "λΆ€μ‚°λŒ€": "λΆ€μ‚°λŒ€ν•™κ΅", "μ°½μ›λŒ€": "μ°½μ›λŒ€ν•™κ΅", "μΆ©λΆλŒ€": "μΆ©λΆλŒ€ν•™κ΅"}
AUDIENCES = {"외ꡭ인": ("외ꡭ인", "μœ ν•™μƒ", "international student"), "내ꡭ인": ("내ꡭ인",),
"λŒ€ν•™μ›": ("λŒ€ν•™μ›", "석사", "박사"), "ν•™λΆ€": ("학뢀생", "ν•™λΆ€κ³Όμ •"),
"μ‹ μž…μƒ": ("μ‹ μž…μƒ", "μ‹ μž…ν•™"), "νŽΈμž…μƒ": ("νŽΈμž…μƒ", "νŽΈμž…ν•™"),
"μž¬ν•™μƒ": ("μž¬ν•™μƒ",), "νœ΄ν•™μƒ": ("νœ΄ν•™μƒ",)}
PROGRAM_CONTEXTS = {"ν˜„μž₯μ‹€μŠ΅": r"ν˜„μž₯μ‹€μŠ΅|μ‹€μŠ΅μƒ|μ›Œν„Έλ£¨\s*(?:ν˜•\s*)?μ½”μ—…", "ꡐλ₯˜ν”„λ‘œκ·Έλž¨": r"학점\s*ꡐλ₯˜|ꡐλ₯˜\s*μˆ˜ν•™|ꡐλ₯˜\s*ν”„λ‘œκ·Έλž¨|λŒ€ν•™μƒ\s*ꡐλ₯˜",
"κ΅ν™˜ν•™μƒ": r"κ΅ν™˜ν•™μƒ|κ΅ν™˜\s*μˆ˜ν•™", "ν•œκ΅­μ–΄μ—°μˆ˜": r"ν•œκ΅­μ–΄\s*μ—°μˆ˜",
"λŒ€νšŒμ°Έκ°€": r"κ²½μ§„λŒ€νšŒ|κ²½μ—°λŒ€νšŒ|곡λͺ¨μ „", "μ„±κ³Όλ°œν‘œνšŒ": r"μ„±κ³Ό\s*λ°œν‘œνšŒ",
"ν•΄μ™Έμ—°μˆ˜": r"ν•΄μ™Έ\s*μ—°μˆ˜|μ–΄ν•™\s*μ—°μˆ˜",
"감염병": r"μ½”λ‘œλ‚˜|λ°±μ‹ |감염병"}
GRADE_RE = re.compile(r"(?<!\d)([1-6])\s*ν•™λ…„(?!도)")
ADMISSION_RE = re.compile(r"(?<!\d)(20\d{2}|\d{2})\s*(?:ν•™λ²ˆ|(?:학년도|λ…„)\s*(?:μ‹ μž…ν•™|μž…ν•™))")
def _admission_years(text: str) -> list[int]:
years = []
for match in ADMISSION_RE.finditer(text):
year = int(match[1])
if year < 100:
year += 2000 if year <= datetime.now(KST).year % 100 else 1900
years.append(year)
return years
class Target(BaseModel):
school: str = "λΆ€κ²½λŒ€ν•™κ΅"
subject: str | None = None
department: str | None = None
department_id: str | None = None
audiences: list[str] = Field(default_factory=list)
contexts: list[str] = Field(default_factory=list)
grade: int | None = None
admission_year: int | None = None
instructor: str | None = None
level: str | None = None
class Conditions(BaseModel):
kind: Literal["search", "latest", "open", "courses"] = "search"
limit: int | None = Field(default=5, ge=1, le=20)
order_by: Literal["relevance", "published_at_desc", "course_name"] = "relevance"
as_of: datetime = Field(default_factory=lambda: datetime.now(KST))
year: int | None = None
term: str | None = None
topic: str | None = None
class SearchTask(BaseModel):
text: str
purpose: Literal["general", "eligibility", "procedure", "deadline", "contact", "assessment", "textbook", "weekly", "prerequisites", "instructor", "course_list"] = "general"
target: Target = Field(default_factory=Target)
conditions: Conditions = Field(default_factory=Conditions)
required_conditions: list[str] = Field(default_factory=list)
class QuestionPlan(BaseModel):
route: Literal["search", "clarification", "small_talk", "refused"] = "search"
tasks: list[SearchTask] = Field(default_factory=list, max_length=3)
missing_fields: list[str] = Field(default_factory=list)
clarification: str | None = None
response_format: str | None = None
resolved_question: str = ""
comparison_targets: list[str] = Field(default_factory=list)
@property
def queries(self) -> list[str]:
return [task.text for task in self.tasks]
@lru_cache(maxsize=1)
def department_catalog() -> tuple[dict, ...]:
path = departments._registry_path()
if path is None:
return ()
return tuple(json.loads(path.read_text(encoding="utf-8")).get("departments", []))
def department_identity(text: str) -> tuple[str | None, str | None]:
normalized = departments.normalize(text)
aliases = [name for alias, names in departments.ALIASES.items() if alias in normalized for name in names]
names = aliases + [name for name in departments.DEPARTMENT_NAMES if departments.normalize(name) in normalized]
if not names:
# Students say "컴퓨터곡학과"/"μ „μžκ³΅ν•™κ³Ό"; the registry has 컴퓨터곡학전곡/μ „μžκ³΅ν•™μ „κ³΅.
# 2026-11-11: unresolved, the department search ranked other departments'
# κ΅μˆ˜μ§„ pages first and "컴퓨터곡학과 κ΅μˆ˜λ‹˜ λͺ©λ‘" found nothing.
names = [name for name in departments.DEPARTMENT_NAMES
if departments._stem(name) != name and departments.normalize(departments._stem(name)) + "κ³Ό" in normalized]
if names:
names = [max(names, key=lambda name: len(departments._stem(name)))]
if not names:
return None, None
name = max(names, key=len) if not aliases else aliases[-1]
for entry in department_catalog():
labels = [entry.get("name"), entry.get("department"), *(entry.get("majors") or [])]
if any(departments.normalize(name) in departments.normalize(str(label or "")) for label in labels):
return name, entry.get("dataset")
return name, None
def _subject_names(text: str) -> set[str]:
return set(TOPICS.findall(normalize_search_terms(text)))
def _explicit_departments(text: str) -> list[str]:
normalized = departments.normalize(text)
names = [name for name in departments.DEPARTMENT_NAMES if departments.normalize(name) in normalized]
names.extend(alias for alias in departments.ALIASES if alias in normalized)
names = [name for name in names if not any(
name != other and departments.normalize(name) in departments.normalize(other) for other in names)]
return sorted(set(names), key=lambda name: normalized.index(departments.normalize(name)))
def _mentions_entity(query: str, entity: str) -> bool:
# Only explicit aliases may expand. A quoted title mentioning a department
# must still match the whole title; an AI course is not the AI major.
# The alias itself counts too: "컴곡 μ΅œμ‹  곡지" mentions 컴곡, but comparing
# only its expansions dropped every sub-query and merged a compound question
# back into one ("컴곡 곡지 3κ°œμ™€ λ„μ„œκ΄€ μ „ν™”λ²ˆν˜Έ", 2026-11-12).
variants = (entity, *departments.ALIASES.get(entity, ()))
variants = tuple(departments.normalize(value) for value in variants)
return departments.mentions(query, variants)
def _names_department(text: str, department: str) -> bool:
"""Whether the user's own words name `department`, also as 컴곡 or 컴퓨터곡학과."""
normalized = departments.normalize(text)
if departments.normalize(department) in normalized:
return True
if any(alias in normalized and department in names for alias, names in departments.ALIASES.items()):
return True
stem = departments._stem(department)
return stem != department and departments.normalize(stem) + "κ³Ό" in normalized
def _ground_queries(original: str, queries: list[str], plan: QuestionPlan) -> list[str]:
"""Keep explicit names and both sides of a department comparison in search.
This is a conservative guard for registry names, university names and quoted
titles, not a general named-entity recognizer. Unsafe rewrites use the user text.
"""
names = _explicit_departments(original)
comparison = len(names) > 1 and re.search(r"비ꡐ|차이|같은|κ°™λ‚˜μš”|동일|λ‹€λ₯Έ|λ‹€λ₯΄", original)
if comparison:
plan.comparison_targets = names
covered = all(any(_mentions_entity(query, name) and not any(
_mentions_entity(query, other) for other in names if other != name) for query in queries) for name in names)
# Several explicit years can refer to different sides. Do not assign them
# to both sides by rewriting the full question mechanically.
years = set(re.findall(r"(?<!\d)(?:20\d{2}|\d{2})\s*(?:ν•™λ²ˆ|학년도|λ…„)", original))
if not covered and len(names) <= 3 and len(years) <= 1:
queries = []
for name in names:
query = original
for other in names:
if other != name:
query = re.sub(re.escape(other) + r"(?:κ³Ό|와|의|은|λŠ”)?", " ", query)
query = re.sub(re.escape(name) + r"(?:κ³Ό|와|의|은|λŠ”)?", name + " ", query)
query = re.sub(r"(?:이|κ°€)?\s*(?:κ°™μ€κ°€μš”|κ°™λ‚˜μš”|λ™μΌν•œκ°€μš”|λ‹€λ₯Έκ°€μš”|λ‹€λ₯΄λ‚˜μš”)[?!.]*$", "", query)
queries.append(re.sub(r"\s+", " ", query).strip())
institutions = re.findall(r"(?<![κ°€-힣A-Za-z])([κ°€-힣A-Za-zΒ·]{2,}(?:λŒ€ν•™κ΅|λŒ€ν•™|λŒ€))(?=의|에|와|κ³Ό|\s|[,?!]|$)", original)
quoted = re.findall(r'["β€œβ€˜]([^"”’\n]{2,100})["”’]', original)
anchors = [*names, *institutions, *quoted]
if any(not any(_mentions_entity(query, anchor) for query in queries) for anchor in anchors):
return [original]
people = instructor_names(original)
if people and PROFILE_FIELDS.search(original):
rewritten_people = {name for query in queries for name in instructor_names(query)}
if not people <= rewritten_people:
return [original]
topics = _subject_names(original)
if len(topics) == 1 and not names and not institutions and not quoted:
# E.g. "μ…”ν‹€λ²„μŠ€ λ…Έμ„ " / "였늘 μ‹€μ‹œκ°„ 도착 μ‹œκ°„": each sub-query
# needs its subject, not just the generation prompt that sees both.
topic = next(iter(topics))
queries = [query if topic in normalize_search_terms(query) else f"{topic} {query}" for query in queries]
return queries
def resolve_context(question: str, history: list[dict]) -> tuple[str, bool]:
"""Use only a user's explicit, unique subject; never an assistant's guess."""
course_question = resolve_course_question(question, history)
if course_question != question:
return course_question, False
previous = next((t.get("content", "") for t in reversed(history) if t.get("role") == "user"), "")
if PERSON_REFERENCE.search(question) and (PROFILE_FIELDS.search(question) or PERSON_FIELDS.search(question)):
if not instructor_names(question):
if len(instructor_names(previous)) == 1:
return question + " / " + previous, False
return question, True
if ROSTER.search(question) and not PERSON_REFERENCE.search(question) and _explicit_departments(question):
return question, False
if _GENERIC_OFFICE.search(question) and not _explicit_departments(question):
if len(_explicit_departments(previous)) == 1:
return question + " / " + previous, False
slot_answer = re.search(r"μž¬ν•™μƒ|μ‹ μž…μƒ|νŽΈμž…μƒ|λŒ€ν•™μ›|외ꡭ인|\d+\s*(?:ν•™κΈ°|λΆ„λ°˜|ν•™λ…„)|컴곡|[κ°€-힣]+(?:ν•™κ³Ό|전곡)", question)
if previous and slot_answer and not TOPICS.search(question) and len(_subject_names(previous)) == 1:
return question + " / " + previous, False
referential = bool(REFERENT.search(question))
contact = bool(_CONTACT_RE.search(question))
generic = (contact or bool(re.search(r"μ‹ μ²­|κΈ°ν•œ|마감|μ–Έμ œκΉŒμ§€", question))) and not TOPICS.search(question)
if not (referential or generic):
return question, False
# Named offices, departments and courses are already subjects.
name = re.search(r"[κ°€-힣A-Za-zΒ·]+(?:μ„Όν„°|사무싀|ν•™κ³Ό|전곡|ν•™λΆ€|ν”„λ‘œκ·Έλž¨|μž₯ν•™κΈˆ|λ³ΈλΆ€|[κ³Όμ²˜κ΄€μ›νŒ€])", question)
if name and not referential:
return question, False
residual = re.sub(r"\d+\s*ν•™λ…„(?:인데|인|이야|μž…λ‹ˆλ‹€)?|μ €λŠ”|μ œκ°€|μ €|μ‹ μ²­|κΈ°ν•œ|κΈ°κ°„|마감|μ–Έμ œ(?:κΉŒμ§€)?(?:μ˜ˆμš”|μ—μš”|μΈκ°€μš”|μž…λ‹ˆκΉŒ|μ•Ό|μ£ )?|κΉŒμ§€μ•Ό|κΉŒμ§€|μ „ν™”\s*번호|μ—°λ½μ²˜|μ•Œλ €\s*쀘|μ•Œλ €μ£Όμ„Έμš”|뭐|무엇|μ–΄λ–€|ν• \s*수|μžˆμ–΄μš”|κ°€λŠ₯ν•œμ§€|κ°€λŠ₯ν•΄|ν•΄μš”|[?!.\s]", "", question)
if len(residual) >= 2 and not referential:
# An unfamiliar programme name should be resolved by the planner,
# rather than rejected merely because it is absent from TOPICS.
return question, False
subjects = _subject_names(previous)
# 'λ„μ„œκ΄€ μ „ν™”λ²ˆν˜Έμ™€ 증λͺ…μ„œ λ°œκΈ‰' contains two possible referents.
place = bool(re.search(r"λ„μ„œκ΄€|λ³΄κ±΄μ§„λ£Œμ†Œ|상담센터|[κ°€-힣]+(?:사무싀|μ„Όν„°|ν•™κ³Ό|λ³ΈλΆ€|κ³Ό|처|κ΄€|νŒ€)", previous))
broad_scholarship = subjects == {"μž₯ν•™"} and not re.search(r"[κ°€-힣]{2,}μž₯ν•™κΈˆ", previous)
if previous and len(subjects) == 1 and not broad_scholarship and (not contact or place):
return question + " / " + previous, False
return question, True
def target_for(text: str) -> Target:
school = next((full for alias, full in SCHOOL_ALIASES.items() if alias in text), None)
explicit = re.search(r"([κ°€-힣]+λŒ€ν•™κ΅)", text)
if explicit:
school = explicit[1].removeprefix("ꡭ립")
name, identity = department_identity(text)
subject = re.search(r"[κ°€-힣A-Za-z0-9Β·]+(?:μž₯ν•™κΈˆ|ν”„λ‘œκ·Έλž¨|μ„Όν„°|λ„μ„œκ΄€)", text)
if not subject and not TOPICS.search(text):
subject = re.search(r"[κ°€-힣A-Za-zΒ·]{2,}(?:λ³ΈλΆ€|사무싀|κ³Ό|처|κ΄€|νŒ€)", text)
grade = GRADE_RE.search(text)
admissions = _admission_years(text)
admission_year = admissions[0] if admissions else None
return Target(school=school or "λΆ€κ²½λŒ€ν•™κ΅", subject=subject[0] if subject else next(iter(sorted(_subject_names(text), key=len, reverse=True)), None),
department=name, department_id=identity, grade=int(grade[1]) if grade else None, admission_year=admission_year,
audiences=[key for key, words in AUDIENCES.items() if any(w in text.lower() for w in words)],
contexts=[key for key, pattern in PROGRAM_CONTEXTS.items() if re.search(pattern, text)],
instructor=instructor_name(text), level=course_level(text))
def purpose_for(text: str) -> str:
text = normalize_search_terms(text)
if is_course_list(text):
return "course_list"
for purpose, pattern in (("contact", r"μ „ν™”λ²ˆν˜Έ|μ—°λ½μ²˜"), ("prerequisites", r"μ„ μˆ˜\s*κ³Όλͺ©"),
("assessment", r"평가\s*(?:λΉ„μœ¨|방법)|배점"), ("textbook", r"ꡐ재"),
("weekly", r"μ£Όμ°¨|주별"), ("instructor", r"λ‹΄λ‹Ή\s*ꡐ수"),
("eligibility", r"자격|지원\s*쑰건"), ("deadline", r"μ–Έμ œ|마감|κΈ°ν•œ"),
("procedure", r"방법|절차|μ–΄λ–»κ²Œ")):
if re.search(pattern, text):
return purpose
return "general"
def conditions_for(text: str) -> Conditions:
kind = "search"
if is_course_list(text):
kind = "courses"
elif re.search(r"곡지|κ²Œμ‹œκΈ€|κ²Œμ‹œλ¬Ό", text) and re.search(r"졜근|μ΅œμ‹ |λ§ˆμ§€λ§‰|μƒˆλ‘œ", text):
kind = "latest"
elif re.search(r"(?:였늘|μ§€κΈˆ|ν˜„μž¬).{0,30}(?:μ‹ μ²­\s*κ°€λŠ₯|μ‹ μ²­ν• \s*수|λͺ¨μ§‘\s*쀑|μ ‘μˆ˜\s*쀑)|(?:μ‹ μ²­\s*κ°€λŠ₯|λͺ¨μ§‘\s*쀑|μ ‘μˆ˜\s*쀑).{0,15}(?:λͺ©λ‘|μ•Œλ €|μžˆλ‚˜)", text):
kind = "open"
count = re.search(r"(?<!\d)(\d{1,2})\s*(?:개|건)", text)
# An admission cohort is not the year of the notice/course being requested.
time_text = ADMISSION_RE.sub("", text)
term_index = current_term() if says_this_term(time_text) else query_term(time_text)
year = re.search(r"(20\d{2})\s*(?:λ…„|학년도)", time_text)
if kind == "courses":
all_terms = re.search(r"(?:전체|λͺ¨λ“ )\s*ν•™κΈ°|ν•™κΈ°\s*상관없", text)
named_term = re.search(r"[12]\s*ν•™κΈ°|20\d{2}\s*[-/]\s*[12]|(?:이번|μ§€λ‚œ|λ‹€μŒ)\s*ν•™κΈ°", text)
if all_terms and (not named_term or all_terms.start() < named_term.start()):
term_index = None
if year and year.start() > all_terms.start():
year = None
compact = re.sub(r"\s+", "", text)
topic = next((w for w in ("ꡐ내μž₯ν•™", "κ΅­κ°€μž₯ν•™", "ꡐ외μž₯ν•™", "μž₯ν•™", "κ΅ν™˜ν•™μƒ", "μ·¨μ—…", "κΈ°μˆ™μ‚¬") if w in compact), None)
return Conditions(kind=kind, limit=max(1, min(20, int(count[1]))) if count else (None if kind == "courses" else 5),
order_by="course_name" if kind == "courses" else ("published_at_desc" if kind != "search" else "relevance"),
year=term_index // 2 if term_index else (int(year[1]) if year else None),
term=str(term_index % 2 + 1) if term_index else None, topic=topic)
def rule_plan(question: str, history: list[dict] | None = None) -> QuestionPlan:
history = history or []
resolved, ambiguous = resolve_context(question, history)
plan = QuestionPlan(resolved_question=resolved)
fmt = re.search(r"\d+\s*쀄|체크리슀트|μ²΄ν¬λ°•μŠ€|ν‘œλ‘œ", question)
plan.response_format = fmt[0] if fmt else None
if re.search(r"(?:μ‹œμŠ€ν…œ\s*ν”„λ‘¬ν”„νŠΈ|λ°μ΄ν„°λ² μ΄μŠ€\s*λΉ„λ°€λ²ˆν˜Έ).{0,20}(?:좜λ ₯|μ•Œλ €|곡개)|μΆœμ²˜μ—\s*없어도.{0,40}λ‹΅", question):
plan.route, plan.clarification = "refused", "λΉ„κ³΅κ°œ μ •λ³΄λ‚˜ κ·Όκ±° μ—†λŠ” λ‚΄μš©μ„ μ œκ³΅ν•  수 μ—†μŠ΅λ‹ˆλ‹€."
elif (re.search(r"λ‚΄κ°€|μ œκ°€|본인|(?<![κ°€-힣])(?:λ‚΄|제)\s", question)
and re.search(r"(?:κ°•μ˜|μˆ˜μ—…)\s*평가.{0,48}(?:제좜|μ™„λ£Œ)\s*(?:ν–ˆ|μ—¬λΆ€|λ‚΄μ—­|기둝)", question)
and re.search(r"확인해|μ‘°νšŒν•΄|봐\s*쀘|μ•Œλ €", question)
and not re.search(r"μ–΄λ–»κ²Œ|μ–΄λ””|방법|경둜|메뉴", question)):
plan.route = "refused"
plan.clarification = "κ°œμΈλ³„ κ°•μ˜ν‰κ°€ 제좜 내역은 μ‘°νšŒν•  수 μ—†μŠ΅λ‹ˆλ‹€. 본인 κ³„μ •μœΌλ‘œ 학ꡐ ν¬ν„Έμ—μ„œ 직접 확인해 μ£Όμ„Έμš”."
elif _GENERIC_OFFICE.search(resolved) and not _explicit_departments(resolved) and not TOPICS.search(resolved):
plan.route, plan.missing_fields = "clarification", ["department"]
plan.clarification = "μ–΄λŠ 학뢀·학과·전곡 μ‚¬λ¬΄μ‹€μ˜ μ—°λ½μ²˜κ°€ ν•„μš”ν•˜μ‹ κ°€μš”?"
elif ambiguous:
plan.route, plan.missing_fields = "clarification", ["subject"]
if PERSON_REFERENCE.search(question):
plan.clarification = "μ–΄λŠ κ΅μˆ˜λ‹˜μ„ λ§μ”€ν•˜μ‹œλŠ”μ§€ μ„±ν•¨μ΄λ‚˜ μ†Œμ†μ„ μ•Œλ €μ£Όμ„Έμš”."
else:
plan.clarification = "μ–΄λŠ λΆ€μ„œλ‚˜ μ‹œμ„€μ˜ μ „ν™”λ²ˆν˜Έκ°€ ν•„μš”ν•˜μ‹ κ°€μš”?" if _CONTACT_RE.search(question) else "μ–΄λ–€ μ‹ μ²­μ΄λ‚˜ ν”„λ‘œκ·Έλž¨μ— λŒ€ν•΄ λ¬ΌμœΌμ‹œλŠ” κ±΄κ°€μš”?"
elif re.search(r"κΈ°μˆ™μ‚¬|μƒν™œκ΄€", resolved) and re.search(r"자격|μ‹ μ²­\s*λŒ€μƒ|μž…μ‹€\s*λŒ€μƒ", resolved):
audiences = target_for(resolved).audiences
if not set(audiences) & {"μ‹ μž…μƒ", "νŽΈμž…μƒ", "μž¬ν•™μƒ", "λŒ€ν•™μ›", "ν•™λΆ€"}:
plan.route, plan.missing_fields = "clarification", ["audience"]
plan.clarification = "μ‹ μž…μƒΒ·μž¬ν•™μƒΒ·λŒ€ν•™μ›μƒ 쀑 μ–΄λŠ 학생 μœ ν˜•μ˜ κΈ°μˆ™μ‚¬ μ‹ μ²­ 자격이 κΆκΈˆν•˜μ‹ κ°€μš”?"
return plan
def finish_plan(plan: QuestionPlan, question: str, queries: list[str], payload: dict | None = None) -> QuestionPlan:
if plan.route != "search":
return plan
if (is_course_list(plan.resolved_question) or is_single_offering_question(plan.resolved_question)
or tuition_row_key(plan.resolved_question)
or (PROFILE_REFERENCE.search(plan.resolved_question) and len(instructor_names(plan.resolved_question)) == 1)):
# Exact catalogue lookups do not depend on a model's wording or omissions.
queries = [plan.resolved_question]
payload = None
if payload and payload.get("route") == "clarification" and isinstance(payload.get("missing_fields"), list):
missing = [f for f in payload["missing_fields"] if f in {"subject", "department", "audience", "year", "term", "section"}]
known_target = target_for(plan.resolved_question)
known_conditions = conditions_for(plan.resolved_question)
known = {"subject": known_target.subject, "department": known_target.department, "audience": known_target.audiences,
"year": known_conditions.year, "term": known_conditions.term,
"section": re.search(r"\d+\s*λΆ„λ°˜", plan.resolved_question)}
missing = [field for field in missing if not known[field]]
if missing and isinstance(payload.get("clarification"), str) and payload["clarification"].strip():
plan.route, plan.missing_fields, plan.clarification = "clarification", missing, payload["clarification"].strip()[:300]
return plan
if not queries:
queries = [plan.resolved_question]
original = plan.resolved_question or question
queries = _ground_queries(original, queries[:3], plan)
if not queries:
# A model cannot route a substantive university question to small talk.
if TOPICS.search(question) or ROSTER.search(original) or instructor_names(original):
queries = [plan.resolved_question]
else:
plan.route = "small_talk"
return plan
global_target = target_for(original)
if len(_explicit_departments(original)) > 1:
global_target.department, global_target.department_id = None, None
grades = set(GRADE_RE.findall(original))
cohorts = set(_admission_years(original))
if len(grades) > 1:
global_target.grade = None
if len(cohorts) > 1:
global_target.admission_year = None
global_conditions = conditions_for(original)
if len(queries) == 1:
rewritten = conditions_for(queries[0])
# A standalone rewrite cannot drop, substitute or invent a semester,
# notice year or admission cohort. Comparison tasks keep local dates.
requested_period = (global_conditions.year, global_conditions.term)
rewritten_period = (rewritten.year, rewritten.term)
if rewritten_period != requested_period or set(_admission_years(queries[0])) != cohorts:
queries = [original]
# Never adopt a department/student type invented by the planner.
for query in queries[:3]:
target = target_for(query)
if len(_explicit_departments(query)) > 1:
target.department, target.department_id = None, None
if target.department and target.department not in (global_target.department, None):
if not _names_department(original, target.department):
target.department, target.department_id = global_target.department, global_target.department_id
independent = re.search(r"λ„μ„œκ΄€|증λͺ…μ„œ|λ³΄κ±΄μ§„λ£Œμ†Œ|상담센터|학생증", query)
if not target.department and not independent:
target.department, target.department_id = global_target.department, global_target.department_id
if target.subject and departments.normalize(target.subject) not in departments.normalize(original):
target.subject = global_target.subject
if not any(name in original for name in (target.school, *(alias for alias, full in SCHOOL_ALIASES.items() if full == target.school))):
target.school = global_target.school
target.audiences = [a for a in target.audiences if a in global_target.audiences] or global_target.audiences
target.contexts = [c for c in target.contexts if c in global_target.contexts] or ([] if independent else global_target.contexts)
# Do not copy the first side's cohort/grade onto every comparison task.
local_grades = set(GRADE_RE.findall(query))
local_cohorts = set(_admission_years(query))
if not (len(grades) > 1 and len(local_grades) == 1 and local_grades <= grades):
target.grade = global_target.grade
if not (len(cohorts) > 1 and len(local_cohorts) == 1 and local_cohorts <= cohorts):
target.admission_year = global_target.admission_year
if target.instructor not in instructor_names(original):
target.instructor = global_target.instructor
target.level = global_target.level or target.level
conditions = conditions_for(query)
if (global_conditions.kind == "latest" and re.search(r"곡지|κ²Œμ‹œκΈ€|κ²Œμ‹œλ¬Ό", query)) or (
global_conditions.kind == "open" and (global_conditions.topic is None or global_conditions.topic in re.sub(r"\s+", "", query) or ("μž₯ν•™" in (global_conditions.topic or "") and "μž₯ν•™" in query))
):
conditions = global_conditions.model_copy(deep=True)
local_count = re.search(r"(?<!\d)(\d{1,2})\s*(?:개|건)", query)
if local_count:
conditions.limit = max(1, min(20, int(local_count[1])))
query = re.sub(r"\d+\s*쀄(?:둜)?|체크리슀트|μ²΄ν¬λ°•μŠ€|ν‘œλ‘œ", "", query).strip()
required = ["school"]
if target.department: required.append("department")
if target.audiences: required.append("audience")
if target.contexts: required.append("program_context")
if target.grade: required.append("grade")
if target.admission_year: required.append("admission_year")
if target.instructor: required.append("instructor")
if conditions.kind == "courses": required.extend(("year", "term", "level"))
if conditions.kind == "open": required.extend(("application_start", "application_end"))
if conditions.kind == "latest": required.extend(("published_at", "order", "limit"))
plan.tasks.append(SearchTask(text=query, purpose=purpose_for(query), target=target, conditions=conditions, required_conditions=required))
return plan