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
+27 -8
View File
@@ -7,6 +7,7 @@ import time
import threading
from functools import lru_cache
from contextlib import ExitStack
from contextvars import ContextVar
import httpx
@@ -14,6 +15,10 @@ from app.core.config import get_settings
logger = logging.getLogger(__name__)
# Per-execution health evidence, distinct from business validation or cached
# progress. A staged review may yield before the whole report is complete.
model_successes = ContextVar('model_successes', default=0)
def routing_revision():
settings = get_settings()
@@ -86,7 +91,9 @@ class PlanningModel:
if remaining < 1:
raise ModelUnavailable('planning_deadline')
try:
return self.invoke(*args, timeout_seconds=min(timeout_seconds, remaining, 12), **kwargs)
# Do not discard a progressing request at 12 s and resend the
# same expensive prompt with only 8 s left to finish it.
return self.invoke(*args, timeout_seconds=min(timeout_seconds, remaining), **kwargs)
except ModelUnavailable as exc:
remaining = self.deadline - time.monotonic()
if not exc.retryable or self.retried or remaining < 2:
@@ -118,10 +125,12 @@ def _direct_generation_schema(schema):
# The deployed native decoder suppresses answer newlines when maxLength is
# present (reproduced with a three-line exact-copy request). Keep the original
# bound in the instruction and enforce it locally, outside guided decoding.
if not schema or 'answer' not in schema.get('properties', {}):
if not schema or not {'answer', 'reply'}.intersection(schema.get('properties', {})):
return schema
result = json.loads(json.dumps(schema))
result['properties']['answer'].pop('maxLength', None)
for key in ('answer', 'reply'):
if key in result.get('properties', {}):
result['properties'][key].pop('maxLength', None)
return result
@@ -204,14 +213,20 @@ def complete_json(instruction: str, content: dict, schema: dict | None = None, *
started = time.monotonic()
reservation = reserved_turn.get()
tokens = None
output_limit = None
if fit_context:
settings=get_settings()
if settings.direct_llm_api_key and not settings.work_assistant_model_control_url:
from app.modules.work_assistant.model_capacity import request_tokens, FULL_CONTEXT
from app.modules.work_assistant.model_capacity import request_tokens, FULL_CONTEXT, TokenCountUnavailable
messages=[{'role':'system','content':_contract_instruction(instruction,prompt_schema if prompt_schema is not None else schema)},
{'role':'user','content':json.dumps(content,ensure_ascii=False,separators=(',',':'))}]
available=FULL_CONTEXT-request_tokens(messages,0,_model_client())-128
try:
input_tokens=request_tokens(messages,0,_model_client(),require_exact=True)
except TokenCountUnavailable as exc:
raise ModelUnavailable('token_count_unavailable',retryable=True,retry_after=5) from exc
available=FULL_CONTEXT-input_tokens-128
if available<512:raise ModelUnavailable('model_context_full')
output_limit = available
max_tokens=min(max_tokens,available)
if reservation is None and dispatch.token_budget:
from app.modules.work_assistant.model_capacity import request_tokens, FULL_CONTEXT
@@ -233,9 +248,11 @@ def complete_json(instruction: str, content: dict, schema: dict | None = None, *
# Admission consumed the execution window. Continue the durable job
# later without opening an upstream request or reporting an outage.
raise ModelUnavailable('review_continuation', retry_after=2)
return _complete_json(instruction, content, schema,
result = _complete_json(instruction, content, schema,
timeout_seconds=max(0.1, timeout_seconds - (time.monotonic() - started)),
max_tokens=max_tokens, images=images, prose=prose, prompt_schema=prompt_schema, stop=stop, single_object=single_object)
max_tokens=max_tokens, images=images, prose=prose, prompt_schema=prompt_schema, stop=stop, single_object=single_object, output_limit=output_limit)
model_successes.set(model_successes.get() + 1)
return result
except ModelUnavailable as exc:
service_failure = exc.retryable or exc.reason in {
'model_account_unavailable', 'direct_http_401', 'direct_http_403',
@@ -262,7 +279,7 @@ def _complete_object(raw):
def _complete_json(instruction: str, content: dict, schema: dict | None = None, *, timeout_seconds: float = 40,
max_tokens: int = 1600, images: list[tuple[int, str]] | None = None,
prose: bool = False, prompt_schema: dict | None = None, stop: list[str] | None = None, single_object: bool = False) -> dict:
prose: bool = False, prompt_schema: dict | None = None, stop: list[str] | None = None, single_object: bool = False, output_limit: int | None = None) -> dict:
started = time.perf_counter()
settings = get_settings()
from app.modules.work_assistant.bid_progress import current_progress, stream_observer
@@ -272,6 +289,8 @@ def _complete_json(instruction: str, content: dict, schema: dict | None = None,
from .bid_timing import request_seconds
progress.check_active(True)
max_tokens = progress.tokens(base_tokens)
if output_limit is not None:
max_tokens = min(max_tokens, output_limit)
timeout_seconds = max(timeout_seconds, request_seconds(max_tokens))
if max_tokens > base_tokens:
instruction += '\n上一轮响应达到输出长度上限。本轮仅返回必要内容,不重复已正确的段落或表格;保持要求完整,不增加解释或重复字段。'