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)
if precise is not None:
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)
from app.modules.work_assistant.answer_audit import add_calendar_facts
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.
rendered['verification'] = 'source_bound'
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
# 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}
blocks, citations, facts = [], [], []
if incomplete:
@@ -151,7 +152,7 @@ def compose_verified_answer(payload: AnswerRequest, *, invoke_model=None) -> dic
indexed = list(enumerate(payload.evidence))
indexed.sort(key=lambda pair: 0 if pair[1].purpose == "primary" else 1)
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]})
if item.query == "current-user":
from app.modules.work_assistant.service import compose_answer
+23
View File
@@ -5,6 +5,29 @@ import re
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):
"""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)
if not model_ok:
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,
"alignment": alignment, "workflow": workflow, "schedule": schedule,
"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)
if not model_ok:
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,
goal_suggestions=suggestions,child_issues=issues,findings=findings,alignment=None,workflow=workflow,
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 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):
@@ -17,6 +17,7 @@ from app.modules.work_assistant import personnel_context as context
RULE_VERSION = "personnel-profile-v6"
REVIEW_SECONDS = 150
VERIFICATION_BATCH_SIZE = 8
MAX_CORRECTIONS = 5
MAX_PROFILE_REPAIRS = 18
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_phase=resume.get('workflow_phase','generating')
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={}
def remember(candidate,attempt,feedback=None):
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),
'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['verification_batch_size']=verification_batch_size
saved.update(verification_batch_size=verification_batch_size, verification_batch_ceiling=VERIFICATION_BATCH_SIZE)
if staged:
saved.update(context_revision=context.CONTEXT_REVISION,context_scans=deepcopy(scans),context_limits=dict(context_limits))
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'])
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')
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')
or ','.join(payload.get('repair_keys',[])+payload.get('repair_sections',[]))))
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:
# Verification is already local to cited rows. Split the pending
# assertions before narrowing a single row's reference context.
if stage=='verify' and not payload.get('adjudication') and verification_batch_size>1:
verification_batch_size=max(1,verification_batch_size//2)
if verification_rows>1:
verification_batch_size=verification_rows//2
remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections))
raise JobDeferred()
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
# different upstream capacity must not reopen the same page forever.
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
# 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'))
raise JobDeferred() from exc
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]
if isinstance(query.get("filters"), dict):
for name, value in list(query["filters"].items()):
codes = allowed_filters.get(name, {}).get("values", {})
if isinstance(value, bool):
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):
values=[str(v) for v in value]
codes=allowed_filters.get(name,{}).get("values",{})
def code(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
@@ -3,6 +3,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .confidential_delivery import CONFIDENTIAL_DELIVERY_POLICY
from .review_failure import review_failure
class TaskEvidence(BaseModel):
@@ -109,9 +110,10 @@ def review_requirements(subject, tasks, sources, *, invoke, timeout_seconds):
for item in result["items"]:
for proof in item["evidence"]:
proof["task_name"] = tasks_by_id[proof["task_id"]].name
except Exception:
except Exception as exc:
result["status"] = "incomplete"
result["message"] = "项目要求核对未完成,可重新分析。已核实的日期问题仍保留。"
result["analysis_error"] = review_failure(exc)
result["message"] = "项目要求核对未完成。已核实的日期问题仍保留。"
for item in result["items"]:
if item["status"] == "pending":
item.update(status="unverified", reason="本次尚未完成核对。", suggestion="")
+49 -24
View File
@@ -1,9 +1,11 @@
"""Task-specific explanations, grounded in the authorized review snapshot."""
import logging
import time
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from .confidential_delivery import CONFIDENTIAL_DELIVERY_POLICY
from .review_failure import review_failure
logger = logging.getLogger(__name__)
@@ -145,6 +147,7 @@ def citation_schema(sources):
def review_commentary(*, subject, goal, tasks, sources, review_kind, workflow,
alignment, findings, schedule, requirements, limitations,
invoke, timeout_seconds, child_issues=None):
deadline = time.monotonic() + timeout_seconds
try:
if timeout_seconds < 1:
raise TimeoutError()
@@ -182,30 +185,52 @@ def review_commentary(*, subject, goal, tasks, sources, review_kind, workflow,
if alignment and alignment['status'] == 'unrelated':
schema['properties']['verdict']['enum'] = ['adjust']
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']}
description = result.description_check
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),
*(d.evidence for d in description_details if d)]:
source = available.get(citation.source_id)
if source is None or not citation.quote.strip() or citation.quote not in source:
raise ValueError("评价引用了未读取的依据")
if not any(c.source_id == f"task:{subject.id}" for c in result.evidence):
raise ValueError("缺少当前工作原文依据")
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):
raise ValueError('任务要求不充分不能显示暂无调整建议')
if review_kind == 'task' and any(a.scope != 'subject' for a in result.actions):
raise ValueError("当前任务评价不得混入整体分工建议")
if result.verdict != "sound" and not (subject_actions if review_kind == 'task' else result.actions):
raise ValueError("当前工作评价不能由其他任务的缺口替代")
if result.verdict == "sound" and subject_actions:
raise ValueError("当前工作判断与修改意见不一致")
if alignment and alignment["status"] == "unrelated" and result.verdict != "adjust":
raise ValueError("评价与已核实的任务归属不一致")
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:
logger.warning("review_commentary_incomplete error_type=%s", type(exc).__name__)
return dict(status="incomplete", message="本次具体评价未完成,请重新分析。已核实的依据仍可查看。")
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_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),
*(d.evidence for d in description_details if d)]:
source = available.get(citation.source_id)
if source is None or not citation.quote.strip() or citation.quote not in source:
raise ValueError("评价引用了未读取的依据")
if not any(c.source_id == f"task:{subject_id}" for c in result.evidence):
raise ValueError("缺少当前工作原文依据")
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):
raise ValueError('任务要求不充分不能显示暂无调整建议')
if review_kind == 'task' and any(a.scope != 'subject' for a in result.actions):
raise ValueError("当前任务评价不得混入整体分工建议")
if result.verdict != "sound" and not (subject_actions if review_kind == 'task' else result.actions):
raise ValueError("当前工作评价不能由其他任务的缺口替代")
if result.verdict == "sound" and subject_actions:
raise ValueError("当前工作判断与修改意见不一致")
if alignment and alignment["status"] == "unrelated" and result.verdict != "adjust":
raise ValueError("评价与已核实的任务归属不一致")
return result
+9 -4
View File
@@ -2,14 +2,19 @@
def review_failure(exc):
if getattr(exc, 'reason', None) == 'model_account_unavailable':
reason = getattr(exc, 'reason', None)
if reason == 'model_account_unavailable':
return {
'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': '模型核对超时,未生成完整建议。'}
if isinstance(exc, ValueError) or reason in ('direct_output_truncated', 'gateway_output_truncated'):
return {'code': 'model_output_invalid', 'message': '本轮分析未通过格式或原文核对。'}
return {
'code': 'analysis_incomplete',
'message': '本次分析未完成,请稍后重新分析;无需因此修改目标或任务描述。',
'message': '本轮未取得完整的分析结果。',
}
+6
View File
@@ -308,17 +308,23 @@ def plan_review(payload: PlanReviewRequest) -> dict:
@router.post("/goal-review")
def goal_review(payload: GoalReviewRequest) -> dict:
token = background_review.set(True)
try:
return review_goal(payload)
except ValueError:
raise HTTPException(422, "目标检查的输入依据不完整或关联不一致")
finally:
background_review.reset(token)
@router.post("/decomposition")
def decomposition(payload: ReviewRequest) -> dict:
token = background_review.set(True)
try:
return review_decomposition(payload)
except ValueError:
raise HTTPException(422, "分解检查的输入依据不完整或关联不一致")
finally:
background_review.reset(token)
@router.get("/skills")
@@ -45,5 +45,6 @@ def review_standalone(payload, *, invoke):
return dict(status=status, summary=commentary.get('assessment',commentary.get('message','')),
review_kind='task', standalone=True, subject_name=task.name, findings=findings,
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])