104 lines
5.9 KiB
Python
104 lines
5.9 KiB
Python
"""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
|
|
|
|
|
|
@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]:
|
|
words = set(re.findall(r"[a-zA-Z][a-zA-Z0-9_]+", value.lower()))
|
|
for run in re.findall(r"[\u4e00-\u9fff]+", value):
|
|
words.update(run[i:i+2] for i in range(len(run)-1))
|
|
return words
|
|
|
|
|
|
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")),
|
|
"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)
|
|
# 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)
|
|
selected = [item[2] for item in ranked[:maximum]]
|
|
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)+",我会保留其他已确认条件,并在原权限范围内重新查询。"
|