This commit is contained in:
zyp
2026-11-27 14:43:37 +08:00
parent 1ae94dfb1f
commit b18c6efe92
64 changed files with 5629 additions and 2414 deletions
+69 -7
View File
@@ -4,6 +4,9 @@ import math
from typing import Annotated
from fastapi import APIRouter, Depends, Header, HTTPException, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.routing import APIRoute
from pydantic import BaseModel, ConfigDict, Field
from uuid import UUID
@@ -26,7 +29,8 @@ from app.modules.work_assistant.project_risk_review import RULE_VERSION as PROJE
from app.modules.work_assistant.review_jobs import JobDeferred, review_jobs
from app.modules.work_assistant.model_dispatch import background_review, dispatch
from app.modules.work_assistant.performance_review import PerformanceRequest, review_performance, validation_reason as performance_validation_reason, RULE_VERSION as PERFORMANCE_RULE
from app.modules.work_assistant.personnel_profile import ProfileRequest, review_profile, verified_partial_profile, REVIEW_CACHE_RULE as PERSONNEL_RULE, REVIEW_POLICY as PERSONNEL_POLICY
from app.modules.work_assistant.personnel_profile import (ANNUAL_ASSESSMENT_VERSION, ProfileRequest, review_profile,
verified_partial_profile, REVIEW_CACHE_RULE as PERSONNEL_RULE, REVIEW_POLICY as PERSONNEL_POLICY)
from app.modules.work_assistant.sales_review import SalesRequest, review_sales, RULE_VERSION as SALES_RULE
from app.modules.work_assistant.bid_writing import BidStep, bid_step, RULE_VERSION as BID_RULE
from app.modules.work_assistant.bid_queue import bid_queue
@@ -42,7 +46,30 @@ def require_pms_bridge(x_work_assistant_key: Annotated[str | None, Header()] = N
raise HTTPException(401, "Invalid work assistant bridge credential")
router = APIRouter(dependencies=[Depends(require_pms_bridge)])
class BidValidationRoute(APIRoute):
def get_route_handler(self):
original = super().get_route_handler()
async def handler(request):
try:
return await original(request)
except RequestValidationError as exc:
if not request.url.path.endswith('/bid-writing-step'):
raise
# Never include input values, validator context or upstream bodies.
allowed = {'request_id', 'action', 'project', 'instructions', 'blocks', 'company', 'workbench',
'requirements', 'draft', 'extraction_context', 'body', 'text', 'location', 'id'}
diagnostics = []
for error in exc.errors()[:8]:
loc = [str(x) if isinstance(x, int) or x in allowed else 'field' for x in error['loc']]
diagnostics.append({'field': '.'.join(loc), 'type': error['type']})
logger.warning('bid_request_validation fields=%s', diagnostics)
first = diagnostics[0]['field'] if diagnostics else 'body'
return JSONResponse(status_code=422, content={'detail': diagnostics},
headers={'X-Bid-Validation-Field': first})
return handler
router = APIRouter(dependencies=[Depends(require_pms_bridge)], route_class=BidValidationRoute)
logger = logging.getLogger(__name__)
PERSONNEL_JOB_PROTOCOL = 1
@@ -103,6 +130,13 @@ def personnel_profile_review(payload: ProfileRequest, response: Response = None)
def persist(value):
latest.clear();latest.update(value);save(value)
try:
if payload.profile_kind in {'annual', 'history'}:
from app.modules.work_assistant.personnel_talent import review_annual_talent
from app.modules.work_assistant.personnel_history_cache import HistoryCache
from app.modules.work_assistant.model_gateway import complete_json
return review_annual_talent(payload,core_review=review_profile,invoke=complete_json,
checkpoint=checkpoint,save_checkpoint=persist,staged=True,
history_cache=HistoryCache(review_jobs.path.with_name('personnel-history.sqlite3'),routing_revision()) if payload.full_history else None)
return review_profile(payload,checkpoint=checkpoint,save_checkpoint=persist,staged=True)
except JobDeferred:
previous = checkpoint or {}
@@ -110,24 +144,40 @@ def personnel_profile_review(payload: ProfileRequest, response: Response = None)
if unchanged:
slices = previous.get('unchanged_slices', 0) + 1
if slices >= MAX_UNCHANGED_SLICES:
if payload.profile_kind == 'history':
raise ModelUnavailable('annual_panel_retry', retryable=True, retry_after=300)
result = verified_partial_profile(payload, latest)
logger.warning("personnel_profile_partial reason=unchanged_slices")
return result
persist({**latest, 'unchanged_slices': slices})
elif previous.get('unchanged_slices'):
persist({**latest, 'unchanged_slices': 0})
raise
except ValueError:
except ValueError as exc:
if payload.profile_kind in {'annual', 'history'} and latest.get('talent'):
raise ModelUnavailable('annual_panel_retry', retryable=True, retry_after=300) from exc
result = verified_partial_profile(payload, latest)
logger.warning("personnel_profile_partial reason=validation")
return result
except ModelUnavailable as exc:
if payload.profile_kind == 'history':
# Keep the resumable portrait checkpoint. A context/output
# failure must never become a cached legacy partial report.
raise
if exc.reason not in {'profile_context_limit', 'direct_output_truncated', 'gateway_output_truncated'} or exc.retryable:
raise
result = verified_partial_profile(payload, latest)
logger.warning("personnel_profile_partial reason=%s", exc.reason)
return result
try:
return review_jobs.run(payload.model_dump(), PERSONNEL_RULE + ':' + routing_revision(),
execute, lease_seconds=180, rapid_recovery=True, progress_recovery=True, resume_context_failures=True)
rule = PERSONNEL_RULE
if payload.profile_kind in {'annual', 'history'}:
from app.modules.work_assistant.personnel_talent import PANEL_REVISION
rule += f':annual-{ANNUAL_ASSESSMENT_VERSION}:talent-{PANEL_REVISION}'
from app.modules.work_assistant.personnel_talent import resume_cached_talent
return review_jobs.run(payload.review_input(), rule + ':' + routing_revision(),
execute, lease_seconds=180, rapid_recovery=True, progress_recovery=True, resume_context_failures=True,
resume_ready=lambda result:resume_cached_talent(payload,result))
except ModelUnavailable as exc:
# A saved time slice is waiting to continue, not a model outage. Keep
# Java on its waiting path without consuming its service-failure budget.
@@ -140,7 +190,8 @@ def personnel_profile_review(payload: ProfileRequest, response: Response = None)
if latest:
state=progress(latest)
headers.update({'X-Review-Progress':state['token'],'X-Review-Phase':state['phase'],
'X-Review-Verified':str(state['verified']),'X-Review-Total':str(state['total'])})
'X-Review-Verified':str(state['verified']),'X-Review-Total':str(state['total']),
'X-Review-Read':str(state['read_records']),'X-Review-Source-Total':str(state['source_total'])})
raise HTTPException(503, "人员画像等待继续分析", headers=headers) from exc
except (ValueError, TypeError, AttributeError) as exc:
logger.warning("personnel_profile_failed type=%s", type(exc).__name__)
@@ -255,8 +306,12 @@ def project_document_review(payload: ProjectDocument) -> dict:
@router.get("/review-capabilities")
def review_capabilities() -> dict:
from app.modules.work_assistant.personnel_talent import PANEL_REVISION, QUALITY_REVISION
return {"bid_writing_rule": BID_RULE, "project_risk_rule": PROJECT_RISK_RULE, "document_rule": DOCUMENT_RULE, "performance_rule": PERFORMANCE_RULE, "sales_rule": SALES_RULE, "dispatch_version": 1,
"personnel_rule": PERSONNEL_POLICY, "personnel_job_protocol": PERSONNEL_JOB_PROTOCOL,
"personnel_annual_assessment": ANNUAL_ASSESSMENT_VERSION,
"personnel_talent_revision": PANEL_REVISION, "personnel_history_protocol": 2,
"personnel_quality_revision": QUALITY_REVISION,
"goal_review_rule": GOAL_RULE, "decomposition_rule": DECOMPOSITION_RULE,
"task_review_schema": TASK_REVIEW_SCHEMA, "routing_revision": routing_revision(), "model_dispatch": dispatch.snapshot()}
@@ -310,7 +365,14 @@ def plan_review(payload: PlanReviewRequest) -> dict:
def goal_review(payload: GoalReviewRequest) -> dict:
token = background_review.set(True)
try:
return review_goal(payload)
if not payload.children:
return review_goal(payload)
return review_jobs.run(payload.model_dump(mode="json", exclude={"as_of"}), GOAL_RULE + ':stages-v1:' + routing_revision(),
lambda checkpoint, save: review_goal(payload, checkpoint=checkpoint, save_checkpoint=save),
resume_incomplete=lambda result: not result["model_completed"]
or any((result.get(key) or {}).get("status") == "incomplete" for key in ("requirements", "commentary")))
except ModelUnavailable:
raise HTTPException(503, "目标分析正在等待可用的服务资源,已完成的核对会保留。")
except ValueError:
raise HTTPException(422, "目标检查的输入依据不完整或关联不一致")
finally: