"""Menu-scoped business contracts and metadata retrieval. Contains no business-row cache.""" from __future__ import annotations from functools import lru_cache from pathlib import Path import json import math import re from app.modules.work_assistant.context_text import tokens @lru_cache(maxsize=1) def load_contracts() -> dict[str, dict]: document = json.loads(Path(__file__).with_name("module_skills.json").read_text(encoding="utf-8")) records = document["skills"] ids = [item["id"] for item in records] if len(ids) != len(set(ids)): raise ValueError("Duplicate module skill") return dict(zip(ids, records)) def _tokens(value: str) -> set[str]: return tokens(value) def _name_match(message: str, resource: dict) -> float: # Menu suffixes describe UI organization, not the user's business entity. # "部门" should match "部门管理" before unrelated fields mentioning a company. name = resource.get("name", "") stem = re.sub(r"(?:管理|列表|查询|统计|记录|信息|基础)+$", "", name) names = {name, stem, *resource.get("aliases", [])} return max((min(len(alias), 6) * 2 for alias in names if len(alias) >= 2 and alias in message), default=0) def resource_index(resources: list[dict]) -> list[dict]: return [{"id": resource["id"], "name": resource.get("name", resource["id"]), "module": resource.get("module_skill", {}).get("menu_path", "") or "、".join(resource.get("menu_paths", [])), "queryable": bool(resource.get("operations")), "aliases": resource.get("aliases", [])[:6], "related_resources": sorted({r.get("target") for r in resource.get("relations", {}).values() if r.get("target")}), "description": (resource.get("description") or resource.get("module_skill",{}).get("scope", ""))[:220]} for resource in resources] def retrieve_descriptions(message: str, resources: list[dict], previous_spec: dict, maximum=4) -> list[dict]: """Rank metadata only; the model can explicitly request any other authorized descriptor.""" if len(resources) <= maximum: return resources query = _tokens(message) documents = [] for resource in resources: strong = _tokens(" ".join([resource.get("name", ""), resource.get("module_skill", {}).get("menu_path", ""), *resource.get("menu_paths", []), *resource.get("aliases", [])])) weak = _tokens(resource.get("description", "") + " " + " ".join(str(v) for v in resource.get("fields", {}).values())) documents.append((resource, strong, weak)) frequency = {token: sum(token in strong or token in weak for _, strong, weak in documents) for token in query} old = {q.get("resource") for q in previous_spec.get("primary_queries", [])} ranked = [] for position, (resource, strong, weak) in enumerate(documents): score = sum(math.log(1+len(resources)/(1+frequency[token]))*(3 if token in strong else 1) for token in query if token in strong or token in weak) score += _name_match(message, resource) # Context is a hint, not a rule overriding a new topic. if resource["id"] in old: score += 1 ranked.append((score, -position, resource)) ranked.sort(key=lambda item: (item[0], item[1]), reverse=True) # Reserve candidates for each explicit sub-question before filling by global # relevance. A long first clause must not crowd out a second business goal. selected = [] clauses = [part.strip() for part in re.split(r"[,,;;。!?!?\n]|以及|同时|另外", message) if part.strip()] if len(clauses) > 1: for clause in clauses[:maximum]: terms = _tokens(clause) def clause_score(document): resource, strong, weak = document return _name_match(clause, resource) + sum(math.log(1 + len(resources) / (1 + frequency.get(term, 0))) * (3 if term in strong else 1) for term in terms if term in strong or term in weak) candidate = max(documents, key=clause_score) if clause_score(candidate) > 0 and candidate[0] not in selected: selected.append(candidate[0]) for _, _, resource in ranked: if len(selected) >= maximum: break if resource not in selected: selected.append(resource) for resource in resources: if resource["id"] in old and resource not in selected and len(selected) < maximum+2: selected.append(resource) return selected def guided_failure(payload, reason: str, previous_spec: dict | None = None): """Keep a resumable goal and offer useful next steps without disguising service errors as bad prompts.""" from app.modules.work_assistant.schemas import Plan if previous_spec is None: previous_spec = payload.dialogue_context.question_spec pending=previous_spec.get("pending_intent",{}) original = pending.get("original_question", payload.message) subject = pending.get("confirmed_subject", previous_spec.get("subject", {})) period = pending.get("confirmed_period", previous_spec.get("period", {})) base_queries = pending.get("base_queries", previous_spec.get("primary_queries", [])) selected = retrieve_descriptions(payload.message, payload.resources, previous_spec, maximum=3) names = list(dict.fromkeys(r.get("name", r["id"]) for r in selected)) if reason == "model_unavailable": text = "这次服务暂时未能完成处理,尚未查询业务数据。你的问题和已有条件已保留,稍后直接重试即可,无需重新组织问法。" else: choices = "、".join(names) text = ("这次查询条件未能正确处理,尚未完成数据查询。已保留原问题和查询条件,可以重试。" if reason == "query_not_resolved" else f"我先确认一下:你要了解的是{choices}中的哪一类信息?可以补充具体对象,或者说明想看列表、数量还是详细内容;已经说过的条件我会继续沿用。" if choices else "我先确认一下:你想查哪类记录,以及哪位人员或哪个项目?可以直接用自己的话补充,我会接着原问题查询。") return Plan(clarification=text, response_kind="clarification", dialogue_mode="followup", planner_version=2, resolved_question=payload.message, question_spec={"version":2,"question":payload.message,"response_kind":"clarification", "subject":subject,"period":period, "primary_queries":[],"pending_intent":{"original_question":original, "confirmed_subject":subject,"confirmed_period":period,"base_queries":base_queries, "candidate_resources":[r["id"] for r in selected],"reason":reason}}) def no_result_guidance(item, definition: dict) -> str: filters = definition.get("filters", {}) alternatives = [] if any(d.get("type") == "date" for d in filters.values()): alternatives.append("换一个时间范围") if any(d.get("values") for d in filters.values()): alternatives.append("调整业务状态") if any(key in filters for key in ("keyword", "name", "project_name", "person_name", "user_name")): alternatives.append("补充或调整名称关键词") if not alternatives: return "你可以继续说明要核对的具体记录,我会保留已经确认的条件;查询始终受当前账号权限限制。" return "接下来可以直接说要"+"、".join(alternatives)+",我会保留其他已确认条件,并在原权限范围内重新查询。"