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
+5
View File
@@ -20,6 +20,11 @@ def continue_adaptive(payload):
precise=precise_answer(payload) precise=precise_answer(payload)
if precise is not None: if precise is not None:
return precise return precise
if payload.question_spec.get("catalog_read"):
return ContinueDecision()
if all(item.status == "ok" and item.total == 0 for item in payload.evidence):
# A completed empty read supports a scoped no-records answer, without guessing why.
return ContinueDecision()
records, allowed, partial = evidence_context(payload.evidence, resources=payload.resources, question=payload.message) records, allowed, partial = evidence_context(payload.evidence, resources=payload.resources, question=payload.message)
from app.modules.work_assistant.answer_audit import add_calendar_facts from app.modules.work_assistant.answer_audit import add_calendar_facts
add_calendar_facts(records, _today(payload).isoformat()) add_calendar_facts(records, _today(payload).isoformat())
+4 -3
View File
@@ -132,10 +132,11 @@ def compose_verified_answer(payload: AnswerRequest, *, invoke_model=None) -> dic
# Prefixing it again repeats a caveat already explained in context. # Prefixing it again repeats a caveat already explained in context.
rendered['verification'] = 'source_bound' rendered['verification'] = 'source_bound'
return rendered return rendered
incomplete = bool(payload.investigation_note) catalog_read = payload.question_spec.get("catalog_read", False)
incomplete = bool(payload.investigation_note) or any(item.status != "ok" for item in payload.evidence)
# A failed synthesis must not trigger another model call just to display # A failed synthesis must not trigger another model call just to display
# records. Keep a short, clearly labelled partial result under outages. # records. Keep a short, clearly labelled partial result under outages.
selected = {} if incomplete else select_evidence(payload, invoke_model=invoke_model) selected = {} if incomplete or catalog_read else select_evidence(payload, invoke_model=invoke_model)
definitions = {item["id"]: item for item in payload.available_resources if "id" in item} definitions = {item["id"]: item for item in payload.available_resources if "id" in item}
blocks, citations, facts = [], [], [] blocks, citations, facts = [], [], []
if incomplete: if incomplete:
@@ -151,7 +152,7 @@ def compose_verified_answer(payload: AnswerRequest, *, invoke_model=None) -> dic
indexed = list(enumerate(payload.evidence)) indexed = list(enumerate(payload.evidence))
indexed.sort(key=lambda pair: 0 if pair[1].purpose == "primary" else 1) indexed.sort(key=lambda pair: 0 if pair[1].purpose == "primary" else 1)
for index, item in indexed: for index, item in indexed:
if incomplete and len(item.rows) > 3: if incomplete and not catalog_read and len(item.rows) > 3:
item = item.model_copy(update={"rows": item.rows[:3]}) item = item.model_copy(update={"rows": item.rows[:3]})
if item.query == "current-user": if item.query == "current-user":
from app.modules.work_assistant.service import compose_answer from app.modules.work_assistant.service import compose_answer
+23
View File
@@ -5,6 +5,29 @@ import re
from calendar import monthrange from calendar import monthrange
_DAY = r"(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})日?"
_CLOSED_DATES = re.compile(rf"(?<!\d){_DAY}(?:\s*(?:至|到|[~~—–])\s*{_DAY})?(?!\d)")
def explicit_date_bounds(text: str) -> tuple[str, str] | None:
"""Parse a complete date or a closed range, including Chinese date notation."""
match = _CLOSED_DATES.fullmatch(text.strip())
if not match:
return None
digits = match.groups()
try:
first = date(*map(int, digits[:3]))
last = date(*map(int, digits[3:])) if digits[3] else first
except ValueError:
return None
return (first.isoformat(), last.isoformat()) if first <= last else None
def single_explicit_date_span(text: str) -> str:
spans = list(_CLOSED_DATES.finditer(text))
return spans[0].group() if len(spans) == 1 else ""
def explicit_relative_period(message: str): def explicit_relative_period(message: str):
"""Canonical whole periods only; mixed ranges and specific weekdays stay explicit. """Canonical whole periods only; mixed ranges and specific weekdays stay explicit.
+157
View File
@@ -0,0 +1,157 @@
"""Resolve explicit catalog reads without asking a model to invent a query."""
import re
from pydantic import ValidationError
from app.modules.work_assistant.calendar import calendar_context, explicit_date_bounds, explicit_relative_period, single_explicit_date_span
from app.modules.work_assistant.schemas import Plan, ResourceQuery
COUNT = r"(?:(?:一共|总共|总计)有?|共有|还有|有)?(?:多少|几)(?:条|项|个|件|份|场)?(?:记录)?"
LIST = r"(?:有哪些|有什么|列表|清单|有哪些记录)"
def catalog_read(payload, previous_spec):
"""Only take over when the whole question identifies a read and its scope."""
question = payload.message.strip().rstrip("??。!! ")
definitions = {item["id"]: item for item in payload.resources}
submission = _own_submission_count(question, definitions, payload.today)
if submission:
return Plan(resource_queries=[submission], reply_mode="count"), "new"
count_only = re.fullmatch(r"(?:那|所以)?(?:" + COUNT + r"|数量呢|总数呢)(?:呢|啊|呀)?", question)
period = explicit_relative_period(question)
period_only = period and re.fullmatch(r"(?:那|那么)?" + re.escape(period[1]) + r"(?:的)?(?:呢|啊|呀)?", question)
if count_only or period_only:
# A short follow-up needs a single successfully executed query to inherit.
if payload.dialogue_context.last_assistant_act not in {"answered", "empty"}:
return None
if previous_spec.get("question") != payload.dialogue_context.active_question:
return None
queries = previous_spec.get("primary_queries", [])
if (len(queries) != 1 or previous_spec.get("requested_assessments") or previous_spec.get("limitation")
or previous_spec.get("subject", {}).get("mode") == "record"):
return None
try:
query = ResourceQuery.model_validate(queries[0])
except ValidationError:
return None
definition = definitions.get(query.resource, {})
if (query.operation not in {"list", "count"} or query.record_id or query.analysis or query.include
or {"summary", "group_by", "sort_by", "sort_direction"} & query.filters.keys()):
return None
if count_only:
if "count" not in definition.get("operations", []):
return None
query.operation, query.fields, query.limit = "count", [], 1
else:
dates = {key for key in query.filters if definition.get("filters", {}).get(key, {}).get("type") == "date"}
pairs = {tuple(pair) for pair in definition.get("time_bindings", {}).values() if len(pair) == 2 and set(pair) == dates}
if len(pairs) != 1 or query.operation not in definition.get("operations", []):
return None
if query.resource in {"tasks", "task-assignees"} and query.filters.get("status") in {"today", "week", "overdue"}:
return None
first, last = pairs.pop()
bounds = calendar_context(payload.today)[period[0]]
query.filters[first] = bounds if isinstance(bounds, str) else bounds["date_from"]
query.filters[last] = bounds if isinstance(bounds, str) else bounds["date_to"]
query.offset = 0
return Plan(resource_queries=[query], reply_mode="count" if query.operation == "count" else "details"), "followup"
clauses = re.split(r"\s*[,,;;??。]+\s*", question)
if len(clauses) > 4:
return None
queries = [_catalog_query(clause, payload, definitions) for clause in clauses]
if any(query is None for query in queries):
return None
if len({(q.resource, q.operation, tuple(q.filters.items())) for q in queries}) != len(queries):
return None
return Plan(resource_queries=queries, reply_mode="summary" if len(queries) > 1 else
"count" if queries[0].operation == "count" else "details"), "new"
def _catalog_query(question, payload, definitions):
# Use reviewed names here. Short aliases can imply extra conditions, such as 周例会.
text = re.sub(r"^(?:(?:请|帮我|再)?(?:查看|查询|查一下|列出)\s*)", "", question)
period = explicit_relative_period(text)
bounds = None
if period and text.startswith(period[1]):
text = text[len(period[1]):].removeprefix("的").strip()
bounds = calendar_context(payload.today)[period[0]]
elif span := single_explicit_date_span(text):
if text.startswith(span) and (dates := explicit_date_bounds(span)):
text = text[len(span):].removeprefix("的").strip()
bounds = dates[0] if dates[0] == dates[1] else {"date_from": dates[0], "date_to": dates[1]}
meeting = _meeting_agenda(text, bounds, definitions.get("meetings", {}))
if meeting:
return meeting
matches = []
for definition in definitions.values():
name = definition.get("name", "")
if not definition.get("operations") or len(name) < 2 or definition.get("parent_filter"):
continue
match = re.fullmatch(re.escape(name) + r"(?:里|中|的)?\s*(" + COUNT + "|" + LIST + ")", text)
if match:
matches.append((definition, "count" if re.fullmatch(COUNT, match[1]) else "list"))
if len(matches) != 1:
return None
definition, operation = matches[0]
if operation not in definition["operations"]:
return None
if any(re.search(rule["pattern"], question) for rule in definition.get("selection_conflicts", [])):
return None
# Task and approval reads default to this account. Menu readers use existing data scope.
scope = "mine" if definition["id"] in {"tasks", "approvals", "work-logs", "log-checks"} or definition.get("scope") == "personal" else "accessible"
if definition["id"] == "task-assignees" and not payload.allow_organization:
return None
filters = {}
if bounds:
bindings = definition.get("time_bindings", {})
# An unqualified period can be read directly only with one date meaning.
# 日报的覆盖日期和提交日期 are distinct, for example.
if len(bindings) != 1:
return None
first, last = next(iter(bindings.values()))
if not all(definition.get("filters", {}).get(key, {}).get("type") == "date" for key in (first, last)):
return None
filters = {first: bounds if isinstance(bounds, str) else bounds["date_from"],
last: bounds if isinstance(bounds, str) else bounds["date_to"]}
return ResourceQuery(resource=definition["id"], operation=operation, scope=scope,
filters=filters, limit=1 if operation == "count" else 12)
def _own_submission_count(question, definitions, today):
definition = definitions.get("work-logs", {})
if ("count" not in definition.get("operations", []) or
definition.get("time_bindings", {}).get("submitted") != ["submitted_from", "submitted_to"]):
return None
span = single_explicit_date_span(question)
bounds = explicit_date_bounds(span)
if not bounds:
period = explicit_relative_period(question)
value = calendar_context(today)[period[0]] if period else None
if not isinstance(value, str):
return None
span, bounds = period[1], (value, value)
match = re.fullmatch(r"(?:我|本人)(?:在)?" + re.escape(span) +
r"(?:实际)?(?:提交|上交|交)(?:了)?(?:多少|几)(?:份|篇|条)?(日报|周报)(?:记录)?"
r"(?:[??,,]\s*只按(?:实际)?提交(?:时间|日期)查)?", question)
if not match:
return None
kind = {"日报": "daily", "周报": "weekly"}[match[1]]
if kind not in definition.get("filters", {}).get("type", {}).get("values", {}):
return None
return ResourceQuery(resource="work-logs", operation="count", limit=1,
filters={"type": kind, "submitted_from": bounds[0], "submitted_to": bounds[1]})
def _meeting_agenda(text, day, definition):
if (not isinstance(day, str) or "list" not in definition.get("operations", [])
or not definition.get("relations", {}).get("items") or "date" not in definition.get("filters", {})):
return None
match = re.fullmatch(r"(晨会|早会|晨夕会|周例会)(?:上)?(?:具体)?(?:安排了哪些(?:事|工作)|安排了什么(?:事|工作)?|有哪些(?:工作)?安排|讲了什么|讨论了什么)", text)
if not match:
return None
kind = "weekly" if match[1] == "周例会" else "daily"
if kind not in definition.get("filters", {}).get("type", {}).get("values", {}):
return None
return ResourceQuery(resource="meetings", scope="accessible", filters={"date": day, "type": kind}, include=["items"], limit=12)
@@ -334,6 +334,7 @@ def review_decomposition(payload: ReviewRequest, *, invoke=None) -> dict:
limitations = list(payload.limitations) limitations = list(payload.limitations)
if not model_ok: if not model_ok:
limitations.append(analysis_error['message']) limitations.append(analysis_error['message'])
analysis_error = analysis_error or (commentary or {}).get("analysis_error") or requirements.get("analysis_error")
return {"status": status, "summary": summary, "findings": findings, "limitations": limitations, return {"status": status, "summary": summary, "findings": findings, "limitations": limitations,
"alignment": alignment, "workflow": workflow, "schedule": schedule, "alignment": alignment, "workflow": workflow, "schedule": schedule,
"model_completed": model_ok, "analysis_error": analysis_error, "requirements": requirements, "model_completed": model_ok, "analysis_error": analysis_error, "requirements": requirements,
@@ -220,6 +220,7 @@ def review_goal(payload: GoalReviewRequest, *, invoke=None) -> dict:
limitations = list(payload.limitations) limitations = list(payload.limitations)
if not model_ok: if not model_ok:
limitations.append(analysis_error['message']) limitations.append(analysis_error['message'])
analysis_error = analysis_error or (commentary or {}).get("analysis_error") or requirements.get("analysis_error")
return dict(status=status,summary=commentary.get("assessment", "本次具体评价未完成。") if commentary else "本次分析未完成。",review_kind="goal",goal_name=goal.name, return dict(status=status,summary=commentary.get("assessment", "本次具体评价未完成。") if commentary else "本次分析未完成。",review_kind="goal",goal_name=goal.name,
goal_suggestions=suggestions,child_issues=issues,findings=findings,alignment=None,workflow=workflow, goal_suggestions=suggestions,child_issues=issues,findings=findings,alignment=None,workflow=workflow,
schedule=schedule,limitations=limitations,model_completed=model_ok,analysis_error=analysis_error, schedule=schedule,limitations=limitations,model_completed=model_ok,analysis_error=analysis_error,
+69 -10
View File
@@ -11,14 +11,14 @@ import logging
import re import re
import time import time
from dataclasses import dataclass 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.graph import END, START, StateGraph
from langgraph.runtime import Runtime from langgraph.runtime import Runtime
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
from app.core.config import get_settings 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.model_gateway import complete_json
from app.modules.work_assistant.schemas import Plan, PlanRequest from app.modules.work_assistant.schemas import Plan, PlanRequest
from app.modules.work_assistant.protocol import normalize_proposal from app.modules.work_assistant.protocol import normalize_proposal
@@ -111,6 +111,7 @@ class TurnRuntime:
decision_mode: str = "" decision_mode: str = ""
confirmed_spec: dict | None = None confirmed_spec: dict | None = None
reference_model: object = None reference_model: object = None
catalog_read: bool = False
class RecordReferenceVerdict(BaseModel): class RecordReferenceVerdict(BaseModel):
@@ -137,6 +138,40 @@ def check_record_reference(message, selected_name, invoke):
return verdict 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。 INSTRUCTION = """你是公司工作助手的主决策者。先理解用户真正目的和上下文,再决定直接回答、读取业务资料或澄清。只能返回符合schema的JSON。
一、决定行动 一、决定行动
@@ -192,6 +227,18 @@ focus与plan是同级成员,scope只放在每个resource_queries元素中。
def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict: def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
context = runtime.context context = runtime.context
payload = context.request 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} visible = {r["id"] for r in payload.resources}
objects = [o for o in payload.context_objects if o.get("resource") in visible] 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 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): if 0 <= index < len(candidate.plan.resource_queries):
definition = definitions.get(candidate.plan.resource_queries[index].resource, {}) definition = definitions.get(candidate.plan.resource_queries[index].resource, {})
known_periods.update(definition.get("time_periods", {})) 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): 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", errors.append({"location": ["focus", "period"], "type": "unknown_time_period",
"allowed": sorted(known_periods), "allowed": sorted(known_periods),
@@ -368,13 +417,18 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
if not set(values) <= set(allowed): if not set(values) <= set(allowed):
errors.append({"location": location+[field], "type": "undeclared_query_member", "allowed": list(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",{}): 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: try:
ids=json.loads(query.filters["record_ids"]) 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 ( 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) 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 except (ValueError,TypeError):valid=False
if not valid:errors.append({"location":location+["filters","record_ids"],"type":"unverified_record_reference","allowed_ids":sorted(trusted)}) 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 return candidate, errors
proposal, locations = parse(raw) proposal, locations = parse(raw)
if locations: if locations:
@@ -382,9 +436,13 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
logger.warning("Assistant proposal contract mismatch fields=%s", locations) logger.warning("Assistant proposal contract mismatch fields=%s", locations)
if remaining < 2: if remaining < 2:
raise ValueError("Query contract mismatch") 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: for error in locations:
relevant.update(error.get('alternatives', [])) relevant.update(error.get('alternatives', []))
if not relevant.intersection(visible):
relevant.update(resource["id"] for resource in selected_resources)
repaired = invoke( repaired = invoke(
INSTRUCTION + ANALYSIS_INSTRUCTIONS + "仅修复上一份规划的格式错误,保持用户原意和权限目录不变。按errors定位,不扩展查询范围。", INSTRUCTION + ANALYSIS_INSTRUCTIONS + "仅修复上一份规划的格式错误,保持用户原意和权限目录不变。按errors定位,不扩展查询范围。",
{"question": payload.message, "proposal": raw, "errors": locations, {"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) subject = _subject_from_object(patch.selected_source_id, payload)
elif patch.subject_action == "clear": elif patch.subject_action == "clear":
subject = {} 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 = 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 '') 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')), {}) 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 continue
if field not in query.filters and field in old[0].get("filters",{}): if field not in query.filters and field in old[0].get("filters",{}):
query.filters[field]=old[0]["filters"][field] 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): if index < 0 or index >= len(plan.resource_queries):
raise ValueError("查询对象尚未定位,请重试。") raise ValueError("查询对象尚未定位,请重试。")
query = plan.resource_queries[index] query = plan.resource_queries[index]
@@ -806,7 +865,7 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
restored.fields = [] restored.fields = []
plan.resource_queries[index] = restored plan.resource_queries[index] = restored
scope_notes.append('关联明细沿用刚才的上级记录范围;明细若分页,仅能就实际展示的记录列出符合条件的项,不能推断全部数量。') scope_notes.append('关联明细沿用刚才的上级记录范围;明细若分页,仅能就实际展示的记录列出符合条件的项,不能推断全部数量。')
if context.reference_model: if context.reference_model and not context.catalog_read:
for query in plan.resource_queries: for query in plan.resource_queries:
definition = definitions.get(query.resource, {}) definition = definitions.get(query.resource, {})
relations = definition.get('relations', {}) relations = definition.get('relations', {})
@@ -844,7 +903,7 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
pair = definition.get("time_bindings", {}).get(basis) pair = definition.get("time_bindings", {}).get(basis)
if pair and all(key in query.filters for key in pair): 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": ""} 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 = [] missing_rules = []
for reference in proposal.requested_assessments: for reference in proposal.requested_assessments:
definition = next((r for r in payload.resources if r["id"] == reference.resource), {}) 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], "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)}, "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 ""} "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: 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() plan.question_spec["direct_response"] = proposal.reply.strip()
if plan.response_kind=="clarification" or plan.clarification and not plan.resource_queries: 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.""" """Checkpointed joint planning, without allowing an old answer to become new evidence."""
from app.modules.work_assistant.state_store import planning_session 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 model = invoke_model or complete_json
try: try:
with planning_session(payload) as (graph, config): with planning_session(payload) as (graph, config):
@@ -17,6 +17,7 @@ from app.modules.work_assistant import personnel_context as context
RULE_VERSION = "personnel-profile-v6" RULE_VERSION = "personnel-profile-v6"
REVIEW_SECONDS = 150 REVIEW_SECONDS = 150
VERIFICATION_BATCH_SIZE = 8
MAX_CORRECTIONS = 5 MAX_CORRECTIONS = 5
MAX_PROFILE_REPAIRS = 18 MAX_PROFILE_REPAIRS = 18
FULL_RESULT_TOKENS = 9000 FULL_RESULT_TOKENS = 9000
@@ -1176,7 +1177,12 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
workflow_steps=int(resume.get('workflow_steps',0)) workflow_steps=int(resume.get('workflow_steps',0))
workflow_phase=resume.get('workflow_phase','generating') workflow_phase=resume.get('workflow_phase','generating')
calls_in_slice=0 calls_in_slice=0
verification_batch_size=max(1,min(8,int(resume.get('verification_batch_size',4 if staged else 8)))) # Old staged jobs started with four rows. Keep a known reduction, and let
# jobs still using the old default adopt the larger batch on their next slice.
previous_batch = int(resume.get('verification_batch_size', VERIFICATION_BATCH_SIZE))
if staged and 'verification_batch_ceiling' not in resume and previous_batch == 4:
previous_batch = VERIFICATION_BATCH_SIZE
verification_batch_size = max(1, min(VERIFICATION_BATCH_SIZE, previous_batch))
last_checkpoint={} last_checkpoint={}
def remember(candidate,attempt,feedback=None): def remember(candidate,attempt,feedback=None):
nonlocal last_checkpoint nonlocal last_checkpoint
@@ -1186,7 +1192,7 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
'split_generation':split_generation,'generation_parts':deepcopy(generation_parts), 'split_generation':split_generation,'generation_parts':deepcopy(generation_parts),
'grounding_cache':deepcopy(grounding_cache),'grounding_revision':GROUNDING_REVISION,'repair_revision':REPAIR_REVISION} 'grounding_cache':deepcopy(grounding_cache),'grounding_revision':GROUNDING_REVISION,'repair_revision':REPAIR_REVISION}
saved.update(workflow_steps=workflow_steps,workflow_phase=workflow_phase,operation_truncations=dict(operation_truncations)) saved.update(workflow_steps=workflow_steps,workflow_phase=workflow_phase,operation_truncations=dict(operation_truncations))
saved['verification_batch_size']=verification_batch_size saved.update(verification_batch_size=verification_batch_size, verification_batch_ceiling=VERIFICATION_BATCH_SIZE)
if staged: if staged:
saved.update(context_revision=context.CONTEXT_REVISION,context_scans=deepcopy(scans),context_limits=dict(context_limits)) saved.update(context_revision=context.CONTEXT_REVISION,context_scans=deepcopy(scans),context_limits=dict(context_limits))
saved['verified_current']=0 saved['verified_current']=0
@@ -1207,6 +1213,7 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
request_schema=future_role_contract(request_schema,data['duty_refs'],data['behavior_refs']+data['readable_refs']) request_schema=future_role_contract(request_schema,data['duty_refs'],data['behavior_refs']+data['readable_refs'])
stage=('scan' if 'evidence_batch' in payload else 'verify' if 'issues' in request_schema.get('properties',{}) stage=('scan' if 'evidence_batch' in payload else 'verify' if 'issues' in request_schema.get('properties',{})
else 'repair' if 'repair_keys' in payload or 'validation_feedback' in payload else 'generate') else 'repair' if 'repair_keys' in payload or 'validation_feedback' in payload else 'generate')
verification_rows=sum(map(len,payload['candidate'].values())) if stage=='verify' and not payload.get('adjudication') else 0
operation=('adjudicate' if payload.get('adjudication') else stage+':'+(payload.get('evidence_batch') or payload.get('generation_part') operation=('adjudicate' if payload.get('adjudication') else stage+':'+(payload.get('evidence_batch') or payload.get('generation_part')
or ','.join(payload.get('repair_keys',[])+payload.get('repair_sections',[])))) or ','.join(payload.get('repair_keys',[])+payload.get('repair_sections',[]))))
transform=kwargs.pop('transform',lambda value:value) transform=kwargs.pop('transform',lambda value:value)
@@ -1220,8 +1227,8 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
if count(payload)>limit: if count(payload)>limit:
# Verification is already local to cited rows. Split the pending # Verification is already local to cited rows. Split the pending
# assertions before narrowing a single row's reference context. # assertions before narrowing a single row's reference context.
if stage=='verify' and not payload.get('adjudication') and verification_batch_size>1: if verification_rows>1:
verification_batch_size=max(1,verification_batch_size//2) verification_batch_size=verification_rows//2
remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections)) remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections))
raise JobDeferred() raise JobDeferred()
nested='material' in payload and 'evidence_columns' in payload['material'] nested='material' in payload and 'evidence_columns' in payload['material']
@@ -1293,10 +1300,10 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
# These pages are already below the bounded input limit. A # These pages are already below the bounded input limit. A
# different upstream capacity must not reopen the same page forever. # different upstream capacity must not reopen the same page forever.
raise ModelUnavailable('profile_context_limit') from exc raise ModelUnavailable('profile_context_limit') from exc
if staged and stage=='verify' and not payload.get('adjudication') and verification_batch_size>1 and exc.reason in {'direct_output_truncated','gateway_output_truncated','direct_timeout','model_context_full','context_capacity'}: if staged and verification_rows>1 and exc.reason in {'direct_output_truncated','gateway_output_truncated','direct_timeout','model_context_full','context_capacity'}:
# A long verification response is a unit-size problem. Keep all # A long verification response is a unit-size problem. Keep all
# accepted rows and automatically retry a smaller pending batch. # accepted rows and automatically retry a smaller pending batch.
verification_batch_size=max(1,verification_batch_size//2) verification_batch_size=verification_rows//2
remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections),last_checkpoint.get('validation_feedback')) remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections),last_checkpoint.get('validation_feedback'))
raise JobDeferred() from exc raise JobDeferred() from exc
if staged and stage!='scan' and exc.reason in {'model_context_full','context_capacity'}: if staged and stage!='scan' and exc.reason in {'model_context_full','context_capacity'}:
+5 -1
View File
@@ -131,11 +131,15 @@ def normalize_proposal(raw: dict, resources: list[dict]) -> dict:
del query[alias] del query[alias]
if isinstance(query.get("filters"), dict): if isinstance(query.get("filters"), dict):
for name, value in list(query["filters"].items()): for name, value in list(query["filters"].items()):
codes = allowed_filters.get(name, {}).get("values", {})
if isinstance(value, bool): if isinstance(value, bool):
query["filters"][name] = "true" if value else "false" query["filters"][name] = "true" if value else "false"
elif isinstance(value, (str, int)) and str(value) not in codes:
matches = [key for key, label in codes.items() if label == str(value).strip()]
if len(matches) == 1:
query["filters"][name] = matches[0]
elif isinstance(value,list) and value and all(isinstance(v,(str,int)) and not isinstance(v,bool) for v in value): elif isinstance(value,list) and value and all(isinstance(v,(str,int)) and not isinstance(v,bool) for v in value):
values=[str(v) for v in value] values=[str(v) for v in value]
codes=allowed_filters.get(name,{}).get("values",{})
def code(v): def code(v):
candidates=[key for key,label in codes.items() if label==v] candidates=[key for key,label in codes.items() if label==v]
return candidates[0] if v not in codes and len(candidates)==1 else v return candidates[0] if v not in codes and len(candidates)==1 else v
@@ -3,6 +3,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from .confidential_delivery import CONFIDENTIAL_DELIVERY_POLICY from .confidential_delivery import CONFIDENTIAL_DELIVERY_POLICY
from .review_failure import review_failure
class TaskEvidence(BaseModel): class TaskEvidence(BaseModel):
@@ -109,9 +110,10 @@ def review_requirements(subject, tasks, sources, *, invoke, timeout_seconds):
for item in result["items"]: for item in result["items"]:
for proof in item["evidence"]: for proof in item["evidence"]:
proof["task_name"] = tasks_by_id[proof["task_id"]].name proof["task_name"] = tasks_by_id[proof["task_id"]].name
except Exception: except Exception as exc:
result["status"] = "incomplete" result["status"] = "incomplete"
result["message"] = "项目要求核对未完成,可重新分析。已核实的日期问题仍保留。" result["analysis_error"] = review_failure(exc)
result["message"] = "项目要求核对未完成。已核实的日期问题仍保留。"
for item in result["items"]: for item in result["items"]:
if item["status"] == "pending": if item["status"] == "pending":
item.update(status="unverified", reason="本次尚未完成核对。", suggestion="") item.update(status="unverified", reason="本次尚未完成核对。", suggestion="")
@@ -1,9 +1,11 @@
"""Task-specific explanations, grounded in the authorized review snapshot.""" """Task-specific explanations, grounded in the authorized review snapshot."""
import logging import logging
import time
from typing import Literal from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator from pydantic import BaseModel, ConfigDict, Field, model_validator
from .confidential_delivery import CONFIDENTIAL_DELIVERY_POLICY from .confidential_delivery import CONFIDENTIAL_DELIVERY_POLICY
from .review_failure import review_failure
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -145,6 +147,7 @@ def citation_schema(sources):
def review_commentary(*, subject, goal, tasks, sources, review_kind, workflow, def review_commentary(*, subject, goal, tasks, sources, review_kind, workflow,
alignment, findings, schedule, requirements, limitations, alignment, findings, schedule, requirements, limitations,
invoke, timeout_seconds, child_issues=None): invoke, timeout_seconds, child_issues=None):
deadline = time.monotonic() + timeout_seconds
try: try:
if timeout_seconds < 1: if timeout_seconds < 1:
raise TimeoutError() raise TimeoutError()
@@ -182,9 +185,34 @@ def review_commentary(*, subject, goal, tasks, sources, review_kind, workflow,
if alignment and alignment['status'] == 'unrelated': if alignment and alignment['status'] == 'unrelated':
schema['properties']['verdict']['enum'] = ['adjust'] schema['properties']['verdict']['enum'] = ['adjust']
instruction += '\n本次已根据原文核实:当前任务不属于所挂上级目标。即使任务自身描述清楚,也必须说明这项归属冲突并建议核对挂靠,不能给sound;不要把技术任务改写成另一种业务任务。' instruction += '\n本次已根据原文核实:当前任务不属于所挂上级目标。即使任务自身描述清楚,也必须说明这项归属冲突并建议核对挂靠,不能给sound;不要把技术任务改写成另一种业务任务。'
result = Commentary.model_validate(invoke(instruction, data, schema,
timeout_seconds=min(18, timeout_seconds), max_tokens=3000))
available = {s['id']: s['text'] for s in data['sources']} available = {s['id']: s['text'] for s in data['sources']}
def evaluate():
remaining = deadline - time.monotonic()
if remaining < 1:
raise TimeoutError()
raw = invoke(instruction, data, schema, timeout_seconds=min(30, remaining), max_tokens=3000)
return validate_commentary(raw, subject.id, available, review_kind, alignment)
try:
result = evaluate()
except ValueError:
if deadline - time.monotonic() < 8:
raise
instruction += (
'\n上一轮未通过核对。按结构完整重写,引用直接使用对应来源的候选原文,'
'至少一条引用来自当前任务,结论、描述充分性和整改意见必须一致。'
)
result = evaluate()
return dict(status="complete", **result.model_dump())
except Exception as exc:
failure = review_failure(exc)
logger.warning("review_commentary_incomplete reason=%s error_type=%s", failure["code"], type(exc).__name__)
return dict(status="incomplete", message=failure["message"], analysis_error=failure)
def validate_commentary(raw, subject_id, available, review_kind, alignment):
result = Commentary.model_validate(raw)
description = result.description_check description = result.description_check
description_details = [description.work_scope, description.expected_result, description.completion_condition] description_details = [description.work_scope, description.expected_result, description.completion_condition]
for citation in [*result.evidence, *(c for a in result.actions for c in a.evidence), for citation in [*result.evidence, *(c for a in result.actions for c in a.evidence),
@@ -192,7 +220,7 @@ def review_commentary(*, subject, goal, tasks, sources, review_kind, workflow,
source = available.get(citation.source_id) source = available.get(citation.source_id)
if source is None or not citation.quote.strip() or citation.quote not in source: if source is None or not citation.quote.strip() or citation.quote not in source:
raise ValueError("评价引用了未读取的依据") raise ValueError("评价引用了未读取的依据")
if not any(c.source_id == f"task:{subject.id}" for c in result.evidence): if not any(c.source_id == f"task:{subject_id}" for c in result.evidence):
raise ValueError("缺少当前工作原文依据") raise ValueError("缺少当前工作原文依据")
subject_actions = [a for a in result.actions if a.scope == "subject"] subject_actions = [a for a in result.actions if a.scope == "subject"]
if description.status == 'needs_detail' and (result.verdict == 'sound' or not subject_actions): if description.status == 'needs_detail' and (result.verdict == 'sound' or not subject_actions):
@@ -205,7 +233,4 @@ def review_commentary(*, subject, goal, tasks, sources, review_kind, workflow,
raise ValueError("当前工作判断与修改意见不一致") raise ValueError("当前工作判断与修改意见不一致")
if alignment and alignment["status"] == "unrelated" and result.verdict != "adjust": if alignment and alignment["status"] == "unrelated" and result.verdict != "adjust":
raise ValueError("评价与已核实的任务归属不一致") raise ValueError("评价与已核实的任务归属不一致")
return dict(status="complete", **result.model_dump()) return result
except Exception as exc:
logger.warning("review_commentary_incomplete error_type=%s", type(exc).__name__)
return dict(status="incomplete", message="本次具体评价未完成,请重新分析。已核实的依据仍可查看。")
+9 -4
View File
@@ -2,14 +2,19 @@
def review_failure(exc): def review_failure(exc):
if getattr(exc, 'reason', None) == 'model_account_unavailable': reason = getattr(exc, 'reason', None)
if reason == 'model_account_unavailable':
return { return {
'code': 'model_account_unavailable', 'code': 'model_account_unavailable',
'message': '模型服务账户暂不可用,请联系管理员检查账户余额及服务状态,恢复后重新分析。', 'message': '模型服务账户暂不可用,请联系管理员检查账户余额及服务状态。',
} }
if isinstance(exc, TimeoutError) or getattr(exc, 'reason', None) in ('gateway_timeout', 'direct_timeout'): if reason in ('queue_full', 'queue_timeout', 'circuit_open', 'review_continuation'):
return {'code': 'model_waiting', 'message': '模型服务暂忙,本轮未取得完整结果。'}
if isinstance(exc, TimeoutError) or reason in ('gateway_timeout', 'direct_timeout', 'direct_deadline'):
return {'code': 'model_timeout', 'message': '模型核对超时,未生成完整建议。'} return {'code': 'model_timeout', 'message': '模型核对超时,未生成完整建议。'}
if isinstance(exc, ValueError) or reason in ('direct_output_truncated', 'gateway_output_truncated'):
return {'code': 'model_output_invalid', 'message': '本轮分析未通过格式或原文核对。'}
return { return {
'code': 'analysis_incomplete', 'code': 'analysis_incomplete',
'message': '本次分析未完成,请稍后重新分析;无需因此修改目标或任务描述。', 'message': '本轮未取得完整的分析结果。',
} }
+6
View File
@@ -308,17 +308,23 @@ def plan_review(payload: PlanReviewRequest) -> dict:
@router.post("/goal-review") @router.post("/goal-review")
def goal_review(payload: GoalReviewRequest) -> dict: def goal_review(payload: GoalReviewRequest) -> dict:
token = background_review.set(True)
try: try:
return review_goal(payload) return review_goal(payload)
except ValueError: except ValueError:
raise HTTPException(422, "目标检查的输入依据不完整或关联不一致") raise HTTPException(422, "目标检查的输入依据不完整或关联不一致")
finally:
background_review.reset(token)
@router.post("/decomposition") @router.post("/decomposition")
def decomposition(payload: ReviewRequest) -> dict: def decomposition(payload: ReviewRequest) -> dict:
token = background_review.set(True)
try: try:
return review_decomposition(payload) return review_decomposition(payload)
except ValueError: except ValueError:
raise HTTPException(422, "分解检查的输入依据不完整或关联不一致") raise HTTPException(422, "分解检查的输入依据不完整或关联不一致")
finally:
background_review.reset(token)
@router.get("/skills") @router.get("/skills")
@@ -45,5 +45,6 @@ def review_standalone(payload, *, invoke):
return dict(status=status, summary=commentary.get('assessment',commentary.get('message','')), return dict(status=status, summary=commentary.get('assessment',commentary.get('message','')),
review_kind='task', standalone=True, subject_name=task.name, findings=findings, review_kind='task', standalone=True, subject_name=task.name, findings=findings,
alignment=None, workflow=[], schedule=schedule, commentary=commentary, requirements=requirements, alignment=None, workflow=[], schedule=schedule, commentary=commentary, requirements=requirements,
model_completed=complete, analysis_error=None, limitations=list(payload.limitations), model_completed=complete, analysis_error=commentary.get('analysis_error') or requirements.get('analysis_error'),
limitations=list(payload.limitations),
rule_version=GOAL_RULE, schema_version=SCHEMA_VERSION, sources=[s.model_dump(mode='json') for s in payload.sources]) rule_version=GOAL_RULE, schema_version=SCHEMA_VERSION, sources=[s.model_dump(mode='json') for s in payload.sources])
+4 -4
View File
@@ -26,9 +26,9 @@ def test_staged_report_makes_one_model_call_per_slice_and_resumes_every_group():
assert len(operations)-before==1;continue assert len(operations)-before==1;continue
break break
else:pytest.fail('workflow did not complete') else:pytest.fail('workflow did not complete')
assert operations==[name for name,_,_ in GROUPS]+['verify','verify'] assert operations==[name for name,_,_ in GROUPS]+['verify']
assert result['findings'][0]['finding']==raw['findings'][0]['finding'] assert result['findings'][0]['finding']==raw['findings'][0]['finding']
assert saved[-1]['workflow_steps']==6 assert saved[-1]['workflow_steps']==5
def test_incomplete_generation_cannot_be_saved_as_a_finished_unit(): def test_incomplete_generation_cannot_be_saved_as_a_finished_unit():
@@ -52,7 +52,7 @@ def test_broken_link_is_repaired_without_regenerating_completed_sections():
except JobDeferred:continue except JobDeferred:continue
break break
else:pytest.fail('link repair did not progress') else:pytest.fail('link repair did not progress')
assert calls==['repair','verify','verify'] assert calls==['repair','verify']
assert result['directions'][0]['activity_id']=='work' assert result['directions'][0]['activity_id']=='work'
@@ -86,7 +86,7 @@ def test_verification_automatically_shrinks_after_truncation_without_rechecking_
except JobDeferred:continue except JobDeferred:continue
break break
else:pytest.fail('adaptive verification did not complete') else:pytest.fail('adaptive verification did not complete')
assert list(map(len,batches))==[4,2,2,1] assert list(map(len,batches))==[5,2,2,1]
assert [key for batch in batches[1:] for key in batch]==list(profile.KEYS) assert [key for batch in batches[1:] for key in batch]==list(profile.KEYS)
assert saved[-1]['verification_batch_size']==2 assert saved[-1]['verification_batch_size']==2
+73
View File
@@ -0,0 +1,73 @@
from copy import deepcopy
from app.modules.work_assistant.decomposition import Source, Task
from app.modules.work_assistant.goal_review import GoalReviewRequest, review_goal
from app.modules.work_assistant.model_gateway import ModelUnavailable
def standalone_task():
task = Task(id=17, parent_id=0, name="提交财务核对清单",
content="把本周财务核对清单交给财务负责人确认", assignee="23")
source = Source(id="task:17", title=task.name, text=task.content)
return GoalReviewRequest(goal=task, children=[], sources=[source], subject_kind="task")
def valid_evaluation(payload):
evidence = {"source_id": "task:17", "quote": payload.goal.content}
detail = {"detail": "提交核对清单给财务负责人确认", "evidence": evidence}
return {
"description_check": {
"status": "sufficient", "work_scope": detail, "expected_result": detail,
"completion_condition": detail, "missing_details": [],
},
"understanding": "本项工作是提交本周的财务核对清单。",
"assessment": "提交对象和确认要求已经明确。",
"verdict": "sound",
"evidence": [evidence],
"actions": [],
}
def test_invalid_citation_is_corrected_before_finishing_the_review():
payload = standalone_task()
good = valid_evaluation(payload)
bad = deepcopy(good)
bad["evidence"][0]["quote"] = "不存在的原文"
calls = []
def invoke(instruction, data, schema, **kwargs):
assert data["phase"] == "review_commentary"
calls.append(instruction)
return bad if len(calls) == 1 else good
result = review_goal(payload, invoke=invoke)
assert len(calls) == 2 and "上一轮未通过核对" in calls[1]
assert result["model_completed"] is True
assert result["commentary"]["evidence"] == good["evidence"]
assert result["analysis_error"] is None
def test_repeated_invalid_evidence_keeps_review_incomplete():
payload = standalone_task()
bad = valid_evaluation(payload)
bad["evidence"][0]["quote"] = "不存在的原文"
result = review_goal(payload, invoke=lambda *_args, **_kwargs: bad)
assert result["model_completed"] is False
assert result["commentary"]["status"] == "incomplete"
assert result["analysis_error"]["code"] == "model_output_invalid"
def test_busy_model_is_reported_to_the_background_scheduler_without_inline_retry():
calls = []
def invoke(*_args, **_kwargs):
calls.append(True)
raise ModelUnavailable("queue_timeout")
result = review_goal(standalone_task(), invoke=invoke)
assert len(calls) == 1
assert result["model_completed"] is False
assert result["analysis_error"]["code"] == "model_waiting"
+208
View File
@@ -0,0 +1,208 @@
from types import SimpleNamespace
import pytest
from app.modules.work_assistant import orchestration
from app.modules.work_assistant.adaptive import continue_adaptive
from app.modules.work_assistant.answers import compose_verified_answer
from app.modules.work_assistant.protocol import normalize_proposal
from app.modules.work_assistant.schemas import AnswerRequest, ContinueRequest, PlanRequest
RESOURCES = [
{"id": "meetings", "name": "会议记录", "scope": "module", "operations": ["list", "count"],
"aliases": ["晨会", "周例会"], "fields": {"name": "会议名称"}, "relations": {},
"time_bindings": {"recorded": ["date_from", "date_to"]},
"filters": {"type": {"values": {"daily": "晨夕会", "weekly": "周例会"}},
"date_from": {"type": "date"}, "date_to": {"type": "date"}}},
{"id": "tasks", "name": "新任务", "scope": "assistant", "operations": ["list", "count"],
"fields": {"name": "任务名称"}, "relations": {},
"filters": {"status": {"values": {"today": "今日到期及计划", "overdue": "逾期未完成"}}}},
{"id": "menu-expense", "name": "报销请款", "scope": "module", "operations": ["list", "count"],
"fields": {"name": "报销事项"}, "relations": {},
"filters": {"status": {"values": {"done": "已通过", "open": "待审核"}}}},
]
@pytest.fixture(autouse=True)
def planner_settings(monkeypatch):
settings = SimpleNamespace(work_assistant_model_enabled=True, work_assistant_planner_timeout_seconds=20)
monkeypatch.setattr(orchestration, "get_settings", lambda: settings)
return settings
def request(question, **kwargs):
return PlanRequest(message=question, allowed_skills=[], protocol_version=2,
today="2026-11-25", resources=kwargs.pop("resources", RESOURCES), **kwargs)
def no_model(*args, **kwargs):
pytest.fail("A verified catalog read called the model")
@pytest.mark.parametrize(("question", "resource", "operation", "scope"), [
("会议记录有哪些?", "meetings", "list", "accessible"),
("报销请款里一共有多少条记录?", "menu-expense", "count", "accessible"),
("帮我列出新任务清单。", "tasks", "list", "mine"),
])
def test_reviewed_catalog_reads_work_without_model(question, resource, operation, scope, planner_settings):
planner_settings.work_assistant_model_enabled = False
plan = orchestration.plan_turn(request(question), invoke_model=no_model)
assert plan.routing == "rules" and plan.question_spec["catalog_read"] and not plan.clarification
assert [(q.resource, q.operation, q.scope) for q in plan.resource_queries] == [(resource, operation, scope)]
def test_followup_count_rereads_exact_latest_query():
active = "我今天有哪些任务要处理?"
spec = {"question": active, "primary_queries": [{"resource": "tasks", "scope": "mine",
"operation": "list", "filters": {"status": "today"}, "fields": ["name"], "offset": 8}]}
context = {"active_question": active, "last_assistant_act": "answered", "question_spec": spec}
plan = orchestration.plan_turn(request("那一共多少项?", dialogue_context=context), invoke_model=no_model)
query, = plan.resource_queries
assert plan.dialogue_mode == "followup"
assert (query.operation, query.offset, query.scope, query.filters) == ("count", 0, "mine", {"status": "today"})
def test_period_only_followup_keeps_original_conditions_and_date_basis():
active = "本月晨会一共有多少场?"
spec = {"question": active, "primary_queries": [{"resource": "meetings", "scope": "accessible",
"operation": "count", "filters": {"type": "daily", "date_from": "2026-11-01", "date_to": "2026-11-30"}}]}
context = {"active_question": active, "last_assistant_act": "answered", "question_spec": spec}
result = orchestration.plan_turn(request("那去年的呢?", dialogue_context=context), invoke_model=no_model)
query, = result.resource_queries
assert result.dialogue_mode == "followup" and result.resolved_question == "那去年的呢?"
assert (query.operation, query.scope, query.filters) == (
"count", "accessible", {"type": "daily", "date_from": "2025-01-01", "date_to": "2025-12-31"})
def test_catalog_uses_declared_date_basis():
plan = orchestration.plan_turn(request("上周的会议记录有多少场?"), invoke_model=no_model)
query, = plan.resource_queries
assert query.operation == "count" and query.filters == {"date_from": "2026-11-16", "date_to": "2026-11-22"}
def test_read_meeting_agenda_uses_typed_items_on_exact_day():
meeting = {**RESOURCES[0], "filters": {**RESOURCES[0]["filters"], "date": {"type": "date"}},
"relations": {"items": {"target": "meeting-items"}}}
result = orchestration.plan_turn(request("2026年11月25日晨会具体安排了哪些工作?", resources=[meeting]), invoke_model=no_model)
query, = result.resource_queries
assert (query.resource, query.include, query.filters) == ("meetings", ["items"], {"date": "2026-11-25", "type": "daily"})
def test_submission_count_uses_authenticated_actor_and_actual_submission_date():
log = {"id": "work-logs", "name": "日志提交记录", "operations": ["count"],
"filters": {"type": {"values": {"daily": "日报", "weekly": "周报"}},
"submitted_from": {"type": "date"}, "submitted_to": {"type": "date"}},
"time_bindings": {"submitted": ["submitted_from", "submitted_to"]}}
result = orchestration.plan_turn(request("我在2026年11月25日实际提交了几份日报?只按提交时间查。", resources=[log]), invoke_model=no_model)
query, = result.resource_queries
assert (query.operation, query.scope, query.filters) == (
"count", "mine", {"type": "daily", "submitted_from": "2026-11-25", "submitted_to": "2026-11-25"})
def test_catalog_keeps_dates_separate_for_two_explicit_reads():
plan = orchestration.plan_turn(request("上周的会议记录有多少场?再查一下报销请款列表。"), invoke_model=no_model)
assert [(q.resource, q.operation, q.filters) for q in plan.resource_queries] == [
("meetings", "count", {"date_from": "2026-11-16", "date_to": "2026-11-22"}),
("menu-expense", "list", {}),
]
@pytest.mark.parametrize("question", ["周例会有哪些?", "我们部门的报销请款有哪些?",
"今天报销请款有多少条?", "会议记录有哪些,顺便查一下报销?"])
def test_catalog_does_not_drop_qualifiers(question, planner_settings):
planner_settings.work_assistant_model_enabled = False
assert not orchestration.plan_turn(request(question), invoke_model=no_model).resource_queries
def test_absent_or_ambiguous_resources_do_not_become_direct_queries(planner_settings):
planner_settings.work_assistant_model_enabled = False
same_name = [{**RESOURCES[0], "id": "menu-meetings"}, RESOURCES[0]]
for visible in (same_name, RESOURCES[1:]):
plan = orchestration.plan_turn(request("会议记录有哪些?", resources=visible), invoke_model=no_model)
assert not plan.resource_queries
def test_unknown_condition_is_repaired_without_dropping_other_queries():
attempts = []
def model(instruction, content, schema, **kwargs):
attempts.append(content)
if len(attempts) == 2:
assert content["errors"][0]["type"] == "unknown_filter_value"
return {"intent": "business", "plan": {"resource_queries": [
{"resource": "tasks", "operation": "count", "filters": {"status": "逾期未完成"}},
{"resource": "menu-expense", "operation": "count", "filters": {"status": "待审核" if len(attempts) == 2 else "pending"}},
]}}
plan = orchestration.plan_turn(request("我的逾期任务和待审核报销各有多少?"), invoke_model=model)
assert len(attempts) == 2 and not plan.clarification
assert [(q.resource, q.filters) for q in plan.resource_queries] == [
("tasks", {"status": "overdue"}), ("menu-expense", {"status": "open"})]
def test_ambiguous_enum_labels_and_business_names_are_preserved():
resource = {"id": "records", "filters": {"name": {}, "status": {"values": {"A": "处理", "B": "处理"}}}}
query = {"resource": "records", "filters": {"name": "处理", "status": "处理"}}
assert normalize_proposal({"plan": {"resource_queries": [query]}}, [resource])["plan"]["resource_queries"] == [query]
@pytest.mark.parametrize(("date_value", "evidence"), [
("2026年11月25日", "2026年11月25日"), ("2026-11-25", "2026-11-25"), ("2026/11/25", "2026/11/25"),
("2026年11月25日", "2026-11-25"), ("2026年11月25日", "2026年11月25日我实际交了"), ("2026年11月25日", ""),
])
def test_existing_read_conditions_supply_missing_explicit_focus_dates(date_value, evidence):
log = {"id": "work-logs", "name": "日志提交记录", "scope": "assistant", "operations": ["count"],
"fields": {}, "filters": {key: {"type": "date"} for key in ("date_from", "date_to", "submitted_from", "submitted_to")},
"time_bindings": {"reported": ["date_from", "date_to"], "submitted": ["submitted_from", "submitted_to"]}}
calls = []
def provider(*args, **kwargs):
calls.append(1)
return {"intent": "business", "focus": {"subject_action": "self", "time_action": "set", "time_evidence": evidence},
"plan": {"resource_queries": [{"resource": "work-logs", "operation": "count",
"filters": {"submitted_from": "2026-11-25", "submitted_to": "2026-11-25"}}]}}
planned = orchestration.plan_turn(request(f"{date_value}我实际交了几份?", resources=[log]), invoke_model=provider)
query, = planned.resource_queries
assert len(calls) == 1 and query.filters == {"submitted_from": "2026-11-25", "submitted_to": "2026-11-25"}
assert planned.question_spec["period"]["basis"] == "submitted"
def test_explicit_time_recovery_requires_matching_dates_and_literal_scope():
from app.modules.work_assistant.schemas import ResourceQuery
literal = "2026年11月25日"
patch = orchestration.FocusPatch(time_action="set", time_evidence=literal)
query = ResourceQuery(resource="meetings", filters={"date_from": "2026-11-24", "date_to": "2026-11-24"})
orchestration._restore_explicit_period(patch, [query], {"meetings": RESOURCES[0]}, literal)
assert not patch.date_from
query.filters = {"date_from": "2026-11-25", "date_to": "2026-11-25"}
orchestration._restore_explicit_period(patch, [query], {"meetings": RESOURCES[0]}, literal + "以前的会议")
assert not patch.date_from
def test_known_list_and_partial_multiquery_show_records_without_model(monkeypatch):
monkeypatch.setattr("app.modules.work_assistant.investigation.complete_json", no_model)
good = {"query": "resource:meetings", "title": "会议记录", "resource": "meetings", "status": "ok",
"total": 1, "fields": {"name": "会议名称"}, "rows": [{"id": "22", "name": "测试会议"}]}
decision = continue_adaptive(ContinueRequest(**request("会议记录有哪些?").model_dump(),
evidence=[good], question_spec={"catalog_read": True}))
assert not decision.answer and not decision.resource_queries and not decision.note
common = dict(message="会议记录有哪些?", skill_ids=[], scope_label="账号可见范围", data_time="2026-11-25",
available_resources=RESOURCES, protocol_version=2)
reply = compose_verified_answer(AnswerRequest(**common, question_spec={"catalog_read": True}, evidence=[good]),
invoke_model=no_model)
assert reply["answer_status"] == "complete" and reply["source_ids"] == ["meetings:22"]
failed = {"query": "resource:menu-expense", "title": "报销请款", "resource": "menu-expense", "status": "error",
"note": "请确认涉及哪位申请人。"}
partial = compose_verified_answer(AnswerRequest(**common, evidence=[good, failed]), invoke_model=no_model)
assert partial["answer_status"] == "partial" and partial["source_ids"] == ["meetings:22"]
assert "测试会议" in partial["answer"] and "哪位申请人" in partial["answer"] and "共 0 项" not in partial["answer"]
def test_empty_success_does_not_invoke_synthesis(monkeypatch):
monkeypatch.setattr("app.modules.work_assistant.investigation.complete_json", no_model)
evidence = {"query": "resource:meetings", "resource": "meetings", "title": "会议记录", "status": "ok", "total": 0, "rows": []}
decision = continue_adaptive(ContinueRequest(**request("星河楼会谈有什么安排?").model_dump(), evidence=[evidence]))
assert not decision.answer and not decision.resource_queries and not decision.note