This commit is contained in:
zyp
2026-11-27 21:27:14 +08:00
parent b18c6efe92
commit 5f204764c9
12 changed files with 563 additions and 28 deletions
+48 -4
View File
@@ -6,6 +6,7 @@ import re
from pydantic import BaseModel, ConfigDict, Field
from .context_text import dialogue_turns, planning_objects
from .source_contracts import relation_conflict
class RouteDecision(BaseModel):
@@ -20,6 +21,7 @@ class RouteDecision(BaseModel):
answer_mode: Literal["records", "analysis"] = "analysis"
subject_mode: Literal["inherit", "self", "visibility"] = "inherit"
subject_evidence: str = Field(default="", max_length=100)
business_relation: Literal["unspecified", "applicant", "pending_approver", "approval_history", "creator", "assignee", "participant", "manager", "mixed"] = "unspecified"
INSTRUCTION = """你是工作助手的语义入口,理解完整问题及连续追问,决定下一步。只输出JSON。
@@ -27,6 +29,9 @@ conversation:一般知识、解释、建议、聊天、翻译、计算、润
identity:询问当前登录人的账号、部门、岗位、角色,后端会读取登录资料,reply留空,不选择部门或人员列表。
capabilities:询问你能做什么。navigation:询问系统页面入口或如何在本系统发起、填写某项业务,keyword填写业务名称,后端会按真实菜单提供入口。目录名称不包含页面按钮和操作手册,不能凭名称编造“顶部按钮”“任务中的审批链接”等操作路径。一般工作方法仍可直接解释,不能把通用做法说成当前系统的实际功能。
business:需要读取系统中实际业务事实、记录、统计、公司制度或基于系统数据分析/写作的问题。从目录选择能完成问题的最少来源,通常1个,多个独立问题才多选,最多4个resource ID。不要把名称相近的全部菜单都选上。reply留空,随后会查数据。多问题保留各自意图;同时询问账号与业务数据也走business。
先区分业务关系再选来源:本人申请/提交/发起的单据查询申请台账;等待我审核的是审批待办;我已经审批过的是审批历史。申请单处于待审批、已通过或被驳回,不会使申请人查询变成审批人待办查询。“我申请的请假通过了吗”仍查请假申请;请款和报销是不同申请类型。目录的business_role及scope说明是选源依据,不能仅按“审批”等词匹配。缺少申请或历史来源时说明具体缺口,绝不能拿待办数量代替申请/已处理数量。用户说“我提交的,不是审批的”等纠正时,纠正优先于旧查询,保留原业务类型及时间,必须重新选择与新关系一致的来源。
business_relation明确填写:申请人查询applicant,待我审批pending_approver,已经审批过approval_history,多种关系同时问mixed,其他问题unspecified。它描述用户要查询的关系,不是所选来源的关系;即使没有匹配来源也不能改变用户关系。
创建人用creator,任务实际责任人用assignee,参与人/参会人用participant,项目负责人用manager。query_contract.actor_relations限定来源实际支持的关系,relation_filters是后端核定的角色筛选。不把“我创建的任务”当成“分给我的任务”,不把“我主持的会议”当成“我参加的会议”。仅说“我的任务”可按任务责任人理解;没说关系的菜单记录数量用unspecified。查不到支持该关系的来源时说明具体缺口,不更换关系以凑结果。
业务仅要清单、数量、总额、登记状态或字段详情时answer_mode=records,后端直接呈现查询结果;需要原因分析、归纳总结、建议、判断或基于业务数据写作时answer_mode=analysis。
一句话含多个问题时必须覆盖每一问。business中还询问本人身份时skills加入current-user,询问入口加入system-navigation并给keyword,询问能力加入assistant-capabilities;仅“我的任务”不需要额外查询身份。
业务主体明确为本人时subject_mode=self;公司、全公司或账号可见范围用visibility,并在subject_evidence引用原句中的对应短语。未明确或多问题主体不同用inherit。此字段仅确定业务范围,不授予权限。
@@ -48,6 +53,7 @@ PLANNING_INSTRUCTION = """你是工作助手的业务查询规划器。理解用
日期直接使用calendar边界和目录time_bindings,写入每项查询自己的filters。多个子问题有不同日期时分别绑定,不设置共同的focus.period,不把今天会议的日期套到明天任务。不要自行添加工作日、已完成、未完成等未要求的过滤。下周不能使用只代表本周的状态值。
focus是可选的上下文变更:本人subject_action=self,明确姓名用named并填写subject_name,部门用department,公司/账号可见用visibility;明确选取已读记录用select和真实selected_source_id;只绑定focus_queries所指查询。scope只用mine或accessible;个人资源用mine。本人有self_filter时设true,切换他人时删除。公司范围不是本人参与。
新话题mode=new,追问mode=followup。追问保留对象、日期和仍适用的条件,明确变更覆盖旧值。日期已在各查询filters中时可省略focus.time_action;单一公共日期变更才设set和有效period。切换指标按metric_time_bindings换日期口径。用户取消条件用cleared_context_fields:[资源ID:字段]。
申请人、审批人和参与人是不同关系。以本轮纠正为准,申请台账不继承审批待办的固定状态;“我提交的”不表示“待我审批”。请款request_type=1、报销request_type=2(仅适用于目录登记的费用申请资源)。问本人申请的审批进度时保留全部申请状态以呈现结果,不只查已通过再把零条解释为未申请。已提交与草稿按目录submission_state区分。切换来源时保留仍适用的业务类型、日期和统计方式,丢弃旧来源独有的审批节点限制。
已读objects可用于定位记录,其原始数据会重新鉴权。已定位项目/会议的成员、任务等通过原记录detail加include查已登记关联;不能把ID套用到另一个资源。新的名称应重新检索,不继承旧record_id。能先检索定位就不要索要内部编号。旧assistant_reply仅用于理解指代,不能当本轮事实。
严格遵守fixed_predicates、limitations、business_boundaries和assessment_rules。质量/违规判断需requested_assessments,普通事实查询为空。缺判断依据时仍尽量查询可确认的事实,并用capability_gap说明具体缺口。未提供的业务不凭相似菜单凑答案;确实缺必要对象才clarification提出一个具体问题。
公司经营开票/回款未指定外部合作或特定菜单时按经营看板口径;明确指定菜单则用指定来源。项目进展以项目主体台账为准,不以归档替代验收。财务单位按字段原单位,未执行的查询不能在reply中宣称已有结果。
@@ -57,9 +63,7 @@ focus是可选的上下文变更:本人subject_action=self,明确姓名用na
def route_question(payload, previous_spec, invoke):
index = [{"id": r["id"], "name": r.get("name", r["id"]),
"aliases": r.get("aliases", [])[:4]}
for r in payload.resources]
index = capability_index(payload.resources)
previous = {key: previous_spec[key] for key in
("question", "subject", "period", "pending_intent") if key in previous_spec}
previous["resources"] = list(dict.fromkeys(q.get("resource") for q in previous_spec.get("primary_queries", [])))
@@ -76,6 +80,17 @@ def route_question(payload, previous_spec, invoke):
result = RouteDecision.model_validate(raw)
if not set(result.resources) <= {r["id"] for r in payload.resources}:
raise ValueError("Unregistered route resource")
if result.intent == 'business':
definitions = {r['id']: r for r in payload.resources}
incompatible = []
for resource in result.resources:
if relation_conflict(result.business_relation, definitions[resource]):
incompatible.append(resource)
if incompatible:
result.resources = [r for r in result.resources if r not in incompatible]
subject = {'applicant': '本人提交的申请记录', 'approval_history': '已处理的审批历史', 'pending_approver': '待本人审批的事项',
'creator': '按创建人查询的记录', 'assignee': '实际负责的任务', 'participant': '参与的记录', 'manager': '作为负责人管理的项目'}.get(result.business_relation, '所要求关系的记录')
result.capability_gap = f'本次可用来源未匹配到{subject},不能用其他关系的记录或零条待办代替。可在对应业务页面查看。'
result.skills = [s for s in result.skills if s in payload.allowed_skills]
if result.intent == "business" and not asks_identity(payload.message):
result.skills = [s for s in result.skills if s != "current-user"]
@@ -83,9 +98,22 @@ def route_question(payload, previous_spec, invoke):
raise ValueError("Empty conversational answer")
if result.subject_mode != "inherit" and (not result.subject_evidence or result.subject_evidence not in payload.message):
result.subject_mode = "inherit"
from .scope_guard import request_only_first_person
if result.subject_mode == 'self' and request_only_first_person(payload.message):
result.subject_mode = 'inherit'
return result
def capability_index(resources):
"""Expose business meaning before source selection, not just similar menu names."""
return [{"id": r["id"], "name": r.get("name", r["id"]),
"aliases": r.get("aliases", [])[:4],
"scope": r.get("scope_description", r.get("description", ""))[:180],
**({"query_contract": r["query_contract"]} if r.get("query_contract") else {}),
**({"business_role": r["business_role"]} if r.get("business_role") else {})}
for r in resources]
def asks_identity(message):
"""Gate an extra profile read, never route or authorize the business query.
@@ -100,7 +128,7 @@ def asks_identity(message):
def resource_description(resource):
"""Keep the executable contract; omit implementation and duplicate UI metadata."""
keys = {"id", "name", "description", "operations", "fields", "filters", "relations", "scope",
keys = {"id", "name", "description", "business_role", "query_contract", "operations", "fields", "filters", "relations", "scope",
"subject_filter", "subject_id_filter", "department_filter", "self_filter", "current_actor_scope",
"subject_context_filters", "time_policies", "field_units", "default_fields",
"record_name_filters", "parent_resource", "parent_filter", "subject_binding",
@@ -204,6 +232,19 @@ def complete_explicit_summary(plan, resources, question):
Does not compute numbers, drop predicates, pick an arbitrary amount field or
broaden a query. Ambiguous metrics remain for the normal planner to resolve.
"""
# A metric-only follow-up may preserve several explicit partitions (e.g.
# request types). Apply the same uniquely declared sum to each population.
metric_only = re.fullmatch(r'(?:再|那)?(?:按(?:这个|这些|该)类型)?(?:分别)?(?:汇总|合计|总计)(?:金额|费用)[呢??。\s]*', question)
if metric_only and plan.resource_queries and len({q.resource for q in plan.resource_queries}) == 1:
for query in plan.resource_queries:
definition = next((r for r in resources if r['id'] == query.resource), {})
sums = [name for name, label in definition.get('filters', {}).get('summary', {}).get('values', {}).items()
if name.endswith('_sum') and re.search(r'金额|费用|收入|支出', str(label))]
if len(sums) == 1 and not query.analysis and not query.include and query.operation != 'detail':
query.operation = 'list'
query.filters['summary'] = sums[0]
query.fields = []
return
if len(plan.resource_queries) != 1 or not re.search(r"合计|总计|总额|总金额|总收入|累计金额", question):
return
if re.search(r"不要|不用|不需要|无需|别|明细|逐笔|逐条|每笔|分别|对比|以及|同时|另外|和", question):
@@ -217,6 +258,9 @@ def complete_explicit_summary(plan, resources, question):
words = tokens(question) - {"合计", "总计", "总额", "总金", "金额"}
ranked = sorted(((len(tokens(str(label)) & words), name) for name, label in values.items()
if name.endswith("_sum")), reverse=True)
monetary = [name for name, label in values.items() if name.endswith('_sum') and re.search(r'金额|费用|收入|支出', str(label))]
if len(monetary) == 1 and re.search(r'多少钱|金额|总额', question):
ranked = [(1, monetary[0])]
if not ranked or ranked[0][0] == 0 or len(ranked) > 1 and ranked[0][0] == ranked[1][0]:
return
query.operation = "list"