This commit is contained in:
zyp
2026-11-25 20:46:42 +08:00
parent 066a5023b7
commit 1ae94dfb1f
17 changed files with 633 additions and 55 deletions
+69 -10
View File
@@ -11,14 +11,14 @@ import logging
import re
import time
from dataclasses import dataclass
from typing import Literal, TypedDict
from typing import Literal, TypedDict, get_args
from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
from app.core.config import get_settings
from app.modules.work_assistant.calendar import calendar_context, explicit_relative_period
from app.modules.work_assistant.calendar import calendar_context, explicit_date_bounds, explicit_relative_period, single_explicit_date_span
from app.modules.work_assistant.model_gateway import complete_json
from app.modules.work_assistant.schemas import Plan, PlanRequest
from app.modules.work_assistant.protocol import normalize_proposal
@@ -111,6 +111,7 @@ class TurnRuntime:
decision_mode: str = ""
confirmed_spec: dict | None = None
reference_model: object = None
catalog_read: bool = False
class RecordReferenceVerdict(BaseModel):
@@ -137,6 +138,40 @@ def check_record_reference(message, selected_name, invoke):
return verdict
def _restore_explicit_period(patch, queries, definitions, message):
"""Use literal date bounds if the model already bound them to the same business dates."""
if patch.date_from and patch.date_to:
return
span = patch.time_evidence if patch.time_evidence in message and explicit_date_bounds(patch.time_evidence) else single_explicit_date_span(message)
bounds = explicit_date_bounds(span)
if not bounds or (patch.date_from and patch.date_from != bounds[0]) or (patch.date_to and patch.date_to != bounds[1]):
return
literal = re.escape(span)
if re.search(r"(?:截至|截止到|早于|晚于)\s*" + literal + r"|" + literal + r"\s*(?:之前|以前|之后|以后|以来|起|[至到~~—–])", message):
return
indices = patch.focus_queries or ([0] if len(queries) == 1 else [])
if not indices or any(index < 0 or index >= len(queries) for index in indices):
return
selected_bases = set()
for index in indices:
query = queries[index]
definition = definitions.get(query.resource, {})
bindings = definition.get("time_bindings", {})
matches = {basis for basis, pair in bindings.items() if tuple(query.filters.get(key) for key in pair) == bounds}
if (not matches and len(bindings) == 1 and bounds[0] == bounds[1] == query.filters.get("date")
and definition.get("filters", {}).get("date", {}).get("type") == "date"):
matches = set(bindings)
if patch.time_basis:
matches.intersection_update({patch.time_basis})
if len(matches) != 1:
return
selected_bases.update(matches)
if len(selected_bases) == 1 and selected_bases <= set(get_args(FocusPatch.model_fields["time_basis"].annotation)):
patch.time_basis = selected_bases.pop()
patch.date_from, patch.date_to = bounds
patch.time_evidence = span
INSTRUCTION = """你是公司工作助手的主决策者。先理解用户真正目的和上下文,再决定直接回答、读取业务资料或澄清。只能返回符合schema的JSON。
一、决定行动
@@ -192,6 +227,18 @@ focus与plan是同级成员,scope只放在每个resource_queries元素中。
def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
context = runtime.context
payload = context.request
from app.modules.work_assistant.catalog_reads import catalog_read
direct = catalog_read(payload, context.previous_spec)
if direct:
plan, mode = direct
context.catalog_read = True
context.decision_mode = mode
resolved = (context.previous_spec["question"] if mode == "followup" and not explicit_relative_period(payload.message)
else payload.message)
return {"proposal": TurnProposal(intent="business", mode=mode, resolved_question=resolved, plan=plan).model_dump()}
if not get_settings().work_assistant_model_enabled:
return {"proposal": TurnProposal(mode="clarify", resolved_question=payload.message,
plan=Plan(clarification="智能问答模型当前未启用。", response_kind="clarification")).model_dump()}
visible = {r["id"] for r in payload.resources}
objects = [o for o in payload.context_objects if o.get("resource") in visible]
from app.modules.work_assistant.module_skills import retrieve_descriptions, resource_index
@@ -315,6 +362,8 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
if 0 <= index < len(candidate.plan.resource_queries):
definition = definitions.get(candidate.plan.resource_queries[index].resource, {})
known_periods.update(definition.get("time_periods", {}))
if patch.period not in known_periods:
_restore_explicit_period(patch, candidate.plan.resource_queries, definitions, payload.message)
if patch.period not in known_periods and not (patch.date_from and patch.date_to):
errors.append({"location": ["focus", "period"], "type": "unknown_time_period",
"allowed": sorted(known_periods),
@@ -368,13 +417,18 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
if not set(values) <= set(allowed):
errors.append({"location": location+[field], "type": "undeclared_query_member", "allowed": list(allowed)})
if "record_ids" in query.filters and "record_ids" in definition.get("filters",{}):
trusted={str(obj.get("id","")) for obj in objects if obj.get("resource")==query.resource}
try:
ids=json.loads(query.filters["record_ids"])
trusted={str(obj.get("id","")) for obj in objects if obj.get("resource")==query.resource}
valid=isinstance(ids,list) and 0<len(ids)<=20 and all(isinstance(value,str) and re.fullmatch(r"[a-zA-Z0-9_-]{1,64}",value) and (
value in trusted or re.search(r"(?<![A-Za-z0-9_-])"+re.escape(value)+r"(?![A-Za-z0-9_-])",payload.message)) for value in ids)
except (ValueError,TypeError):valid=False
if not valid:errors.append({"location":location+["filters","record_ids"],"type":"unverified_record_reference","allowed_ids":sorted(trusted)})
for name, value in query.filters.items():
choices = definition.get("filters", {}).get(name, {}).get("values", {})
if choices and str(value) not in choices:
errors.append({"location": location + ["filters", name], "type": "unknown_filter_value",
"allowed": choices, "message": "根据原问题选择该筛选项的已登记值,保留已明确的其他条件。"})
return candidate, errors
proposal, locations = parse(raw)
if locations:
@@ -382,9 +436,13 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
logger.warning("Assistant proposal contract mismatch fields=%s", locations)
if remaining < 2:
raise ValueError("Query contract mismatch")
relevant = {q.get("resource") for q in raw.get("plan", {}).get("resource_queries", []) if isinstance(q,dict)}
raw_plan = raw.get("plan")
raw_queries = raw_plan.get("resource_queries") if isinstance(raw_plan, dict) else None
relevant = {q["resource"] for q in raw_queries if isinstance(q, dict) and isinstance(q.get("resource"), str)} if isinstance(raw_queries, list) else set()
for error in locations:
relevant.update(error.get('alternatives', []))
if not relevant.intersection(visible):
relevant.update(resource["id"] for resource in selected_resources)
repaired = invoke(
INSTRUCTION + ANALYSIS_INSTRUCTIONS + "仅修复上一份规划的格式错误,保持用户原意和权限目录不变。按errors定位,不扩展查询范围。",
{"question": payload.message, "proposal": raw, "errors": locations,
@@ -553,7 +611,7 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
subject = _subject_from_object(patch.selected_source_id, payload)
elif patch.subject_action == "clear":
subject = {}
if subject.get('mode') == 'record' and context.reference_model:
if subject.get('mode') == 'record' and context.reference_model and not context.catalog_read:
selected = next((obj for obj in payload.context_objects if obj.get('source_id') == subject.get('source_id')), {})
selected_name = str(selected.get('fields', {}).get('name') or selected.get('title') or '')
parent = next((r for r in payload.resources if r['id'] == subject.get('resource')), {})
@@ -667,7 +725,8 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
continue
if field not in query.filters and field in old[0].get("filters",{}):
query.filters[field]=old[0]["filters"][field]
for index in patch.focus_queries:
# Catalog reads already carry the intended scope and predicates, including an exact count follow-up.
for index in (() if context.catalog_read else patch.focus_queries):
if index < 0 or index >= len(plan.resource_queries):
raise ValueError("查询对象尚未定位,请重试。")
query = plan.resource_queries[index]
@@ -806,7 +865,7 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
restored.fields = []
plan.resource_queries[index] = restored
scope_notes.append('关联明细沿用刚才的上级记录范围;明细若分页,仅能就实际展示的记录列出符合条件的项,不能推断全部数量。')
if context.reference_model:
if context.reference_model and not context.catalog_read:
for query in plan.resource_queries:
definition = definitions.get(query.resource, {})
relations = definition.get('relations', {})
@@ -844,7 +903,7 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
pair = definition.get("time_bindings", {}).get(basis)
if pair and all(key in query.filters for key in pair):
period = {"date_from": str(query.filters[pair[0]]), "date_to": str(query.filters[pair[1]]), "basis": basis, "label": ""}
plan.routing = "model"
plan.routing = "rules" if context.catalog_read else "model"
missing_rules = []
for reference in proposal.requested_assessments:
definition = next((r for r in payload.resources if r["id"] == reference.resource), {})
@@ -871,6 +930,8 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
"requested_assessments": [reference.model_dump() for reference in proposal.requested_assessments],
"query_time_scopes": {plan.resource_queries[index].query_id: value for index,value in query_time_scopes.items() if index<len(plan.resource_queries)},
"limitation": plan.clarification if plan.response_kind == "capability_gap" else ""}
if context.catalog_read and plan.resource_queries:
plan.question_spec["catalog_read"] = True
if proposal.intent == "conversation" and proposal.reply.strip() and not plan.resource_queries and plan.skill_ids == ["general-assistance"] and not plan.clarification:
plan.question_spec["direct_response"] = proposal.reply.strip()
if plan.response_kind=="clarification" or plan.clarification and not plan.resource_queries:
@@ -898,8 +959,6 @@ def plan_turn(payload: PlanRequest, *, invoke_model=None, invoke_reference_model
"""Checkpointed joint planning, without allowing an old answer to become new evidence."""
from app.modules.work_assistant.state_store import planning_session
if not get_settings().work_assistant_model_enabled:
return Plan(clarification="智能问答模型当前未启用。", planner_version=2)
model = invoke_model or complete_json
try:
with planning_session(payload) as (graph, config):