标书生成与审查

This commit is contained in:
zyp
2026-11-14 22:48:33 +08:00
parent fc3420ef31
commit 0dc48ad092
57 changed files with 5067 additions and 13011 deletions
+198 -20
View File
@@ -1,9 +1,12 @@
"""Stateless language generation using the assistant's already configured model gateway."""
import json
import hashlib
import re
import logging
import time
import threading
from functools import lru_cache
from contextlib import ExitStack
import httpx
@@ -12,22 +15,55 @@ from app.core.config import get_settings
logger = logging.getLogger(__name__)
def routing_revision():
settings = get_settings()
values = [settings.work_assistant_model_enabled, settings.work_assistant_model_control_url,
settings.work_assistant_model_control_api_key, settings.direct_llm_base_url,
settings.direct_llm_api_key, settings.direct_llm_model]
return hashlib.sha256(json.dumps(values).encode()).hexdigest()
_client_lock = threading.Lock()
@lru_cache(maxsize=1)
def _cached_model_client() -> httpx.Client:
return httpx.Client(trust_env=False, limits=httpx.Limits(max_connections=40, max_keepalive_connections=36))
def _model_client() -> httpx.Client:
return httpx.Client(trust_env=False, limits=httpx.Limits(max_connections=20, max_keepalive_connections=10))
with _client_lock:
return _cached_model_client()
def close_model_client() -> None:
if _model_client.cache_info().currsize:
_model_client().close()
_model_client.cache_clear()
with _client_lock:
if _cached_model_client.cache_info().currsize:
_cached_model_client().close()
_cached_model_client.cache_clear()
def _post_json(client, url, payload, headers, timeout_seconds):
"""Retry only a TCP connection that never opened, within the original budget."""
started = time.monotonic()
for attempt in range(2):
remaining = timeout_seconds - (time.monotonic() - started)
if remaining <= 0:
raise httpx.ConnectTimeout('Connection budget expired')
try:
return client.post(url, json=payload, headers=headers,
timeout=httpx.Timeout(remaining, connect=min(5, remaining)))
except (httpx.ConnectTimeout, httpx.ConnectError):
if attempt:
raise
class ModelUnavailable(RuntimeError):
def __init__(self, reason, *, retryable=False):
def __init__(self, reason, *, retryable=False, retry_after=None):
super().__init__(reason)
self.reason = reason
self.retryable = retryable
self.retry_after = retry_after
def _gateway_failure(reason, started, *, retryable=False):
@@ -89,10 +125,136 @@ def _direct_generation_schema(schema):
return result
def _stream_json_response(client, url, request, headers, timeout_seconds, observer, started):
"""Read actual SSE content under a wall-clock budget; no simulated typing."""
from .bid_progress import current_progress
progress = current_progress.get()
request = dict(request, stream=True)
chunks, size, finish, observed_at = [], 0, None, 0.0
with ExitStack() as stack:
for connection_attempt in range(2):
remaining = timeout_seconds - (time.perf_counter() - started)
if remaining <= 0:
raise _gateway_failure('direct_deadline' if progress is not None else 'direct_timeout',
started, retryable=progress is None)
try:
response = stack.enter_context(client.stream('POST', url, json=request, headers=headers,
timeout=httpx.Timeout(remaining, read=min(60 if progress is not None else 30, remaining), connect=min(5, remaining))))
break
except (httpx.ConnectTimeout, httpx.ConnectError) as exc:
# Only a connection that never opened is safe to retry here.
# Never duplicate a request after sending or receiving any data.
if progress is None or connection_attempt:
raise
progress.check_active(True)
logger.warning('bid_model_connect_retry phase=%s elapsed_ms=%d',
type(exc).__name__, (time.perf_counter() - started) * 1000)
if response.is_error:
raise _gateway_failure(f'direct_http_{response.status_code}', started,
retryable=response.status_code in {408,429,500,502,503,504})
for line in response.iter_lines():
if progress is not None:
progress.check_active()
if time.perf_counter()-started > timeout_seconds:
raise _gateway_failure('direct_deadline' if progress is not None else 'direct_timeout',
started, retryable=progress is None)
if not line.startswith('data:'):
continue
data = line[5:].strip()
if data == '[DONE]':
break
if len(data) > 1_000_000:
raise _gateway_failure('direct_response_too_large', started)
event = json.loads(data)
if event.get('error'):
raise _gateway_failure('direct_stream_error', started, retryable=True)
choices = event.get('choices') or []
if not choices:
continue
choice = choices[0]
delta = choice.get('delta', {}).get('content')
if isinstance(delta, str):
size += len(delta)
if size > 1_000_000:
raise _gateway_failure('direct_response_too_large', started)
chunks.append(delta)
if progress is not None:
progress.received(size)
if time.monotonic()-observed_at >= .4:
observer(''.join(chunks))
if progress is not None:
progress.persist()
observed_at = time.monotonic()
if choice.get('finish_reason'):
finish = choice['finish_reason']
observer(''.join(chunks))
if finish == 'length':
raise _gateway_failure('direct_output_truncated', started)
if finish not in {'stop', 'tool_calls'}:
raise _gateway_failure('direct_stream_incomplete', started, retryable=True)
return ''.join(chunks)
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) -> dict:
max_tokens: int = 1600, images: list[tuple[int, str]] | None = None,
prose: bool = False) -> dict:
from app.modules.work_assistant.model_dispatch import dispatch, DispatchUnavailable, reserved_turn, parallel_bid, background_review
started = time.monotonic()
reservation = reserved_turn.get()
tokens = None
if reservation is None and dispatch.token_budget:
from app.modules.work_assistant.model_capacity import request_tokens, FULL_CONTEXT
from app.modules.work_assistant.bid_progress import current_progress
progress = current_progress.get()
budget = progress.tokens(max_tokens) if progress is not None else max_tokens
messages = [{'role': 'system', 'content': _contract_instruction(instruction, schema)},
{'role': 'user', 'content': json.dumps(content, ensure_ascii=False, separators=(',', ':'))}]
tokens = FULL_CONTEXT if images else request_tokens(messages, budget, _model_client())
try:
wait_limit = 30 if background_review.get() or parallel_bid.get() else 5
ticket = dispatch.acquire(min(wait_limit, max(0, timeout_seconds - (time.monotonic() - started) - 1)), tokens=tokens) if reservation is None else None
except DispatchUnavailable as exc:
# Do not immediately retry admission failures inside a business pipeline.
raise ModelUnavailable(str(exc)) from exc
service_failure = False
try:
return _complete_json(instruction, content, schema,
timeout_seconds=max(0.1, timeout_seconds - (time.monotonic() - started)),
max_tokens=max_tokens, images=images, prose=prose)
except ModelUnavailable as exc:
service_failure = exc.retryable or exc.reason in {
'model_account_unavailable', 'direct_http_401', 'direct_http_403',
'gateway_http_401', 'gateway_http_403'}
raise
finally:
if reservation is None:
dispatch.release(ticket, service_failure)
else:
reservation['failed'] = service_failure
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) -> dict:
started = time.perf_counter()
settings = get_settings()
from app.modules.work_assistant.bid_progress import current_progress, stream_observer
progress, observer = current_progress.get(), stream_observer.get()
base_tokens = max_tokens
if progress is not None:
from .bid_timing import request_seconds
progress.check_active(True)
max_tokens = progress.tokens(base_tokens)
timeout_seconds = max(timeout_seconds, request_seconds(max_tokens))
if max_tokens > base_tokens:
instruction += '\n上一轮响应达到输出长度上限。本轮仅返回必要内容,不重复已正确的段落或表格;保持要求完整,不增加解释或重复字段。'
if progress.deadline is not None:
timeout_seconds = min(timeout_seconds, max(.1, progress.deadline-time.monotonic()))
progress.begin_request()
# Extraction/reconciliation also stream. Their partial JSON is kept
# private; only a complete, validated result advances business progress.
if observer is None:
observer = lambda raw: None
instruction = _contract_instruction(instruction, schema)
if not settings.work_assistant_model_enabled:
raise ModelUnavailable("Model routing is disabled")
@@ -117,6 +279,8 @@ def complete_json(instruction: str, content: dict, schema: dict | None = None, *
"name": "work_assistant", "schema": schema,
}} if schema else {"type": "json_object"},
}
if prose:
request.update(temperature=0.7, top_p=0.8, presence_penalty=1.5)
try:
response = _model_client().post(gateway + "/v1/chat/completions/json", json=request,
headers={"X-API-Key": key} if key else {}, timeout=httpx.Timeout(timeout_seconds, connect=min(5, timeout_seconds)))
@@ -134,7 +298,11 @@ def complete_json(instruction: str, content: dict, schema: dict | None = None, *
code = envelope.get('code')
raise _gateway_failure('gateway_rejected', started, retryable=code in (408,429,500,502,503,504))
data = envelope.get("data", envelope)
if data['choices'][0].get('finish_reason') == 'length':
if progress is not None: progress.truncated(base_tokens)
raise _gateway_failure('gateway_output_truncated', started)
raw = data["choices"][0]["message"]["content"]
if observer is not None: observer(raw)
usage = data.get("usage") or {}
logger.info("assistant_model model=%s elapsed_ms=%d prompt_tokens=%s completion_tokens=%s",
str(data.get("model", ""))[:100], (time.perf_counter()-started)*1000,
@@ -160,25 +328,33 @@ def complete_json(instruction: str, content: dict, schema: dict | None = None, *
"name": "work_assistant", "schema": _direct_generation_schema(schema),
}} if schema else {"type": "json_object"},
}
if prose:
request.update(temperature=0.7, top_p=0.8, presence_penalty=1.5)
try:
response = _model_client().post(settings.direct_llm_base_url.rstrip('/') + '/chat/completions',
json=request, headers={"Authorization": "Bearer " + settings.direct_llm_api_key},
timeout=httpx.Timeout(timeout_seconds, connect=min(5, timeout_seconds)))
if response.is_error:
raise _gateway_failure(f'direct_http_{response.status_code}', started,
retryable=response.status_code in {408,429,500,502,503,504})
if len(response.content) > 1_000_000:
raise _gateway_failure('direct_response_too_large', started)
data = response.json()
choice = data['choices'][0]
if choice.get('finish_reason') == 'length':
raise _gateway_failure('direct_output_truncated', started)
raw = choice['message']['content']
url = settings.direct_llm_base_url.rstrip('/') + '/chat/completions'
headers = {"Authorization": "Bearer " + settings.direct_llm_api_key}
if observer is not None:
raw = _stream_json_response(_model_client(), url, request, headers, timeout_seconds, observer, started)
else:
response = _post_json(_model_client(), url, request, headers, timeout_seconds)
if response.is_error:
raise _gateway_failure(f'direct_http_{response.status_code}', started,
retryable=response.status_code in {408,429,500,502,503,504})
if len(response.content) > 1_000_000:
raise _gateway_failure('direct_response_too_large', started)
data = response.json()
choice = data['choices'][0]
if choice.get('finish_reason') == 'length':
raise _gateway_failure('direct_output_truncated', started)
raw = choice['message']['content']
logger.info('assistant_direct_model model=%s elapsed_ms=%d',
settings.direct_llm_model, (time.perf_counter()-started)*1000)
except ModelUnavailable:
except ModelUnavailable as exc:
if exc.reason == 'direct_output_truncated' and progress is not None:
progress.truncated(base_tokens)
raise
except httpx.TimeoutException as exc:
logger.warning('assistant_direct_timeout phase=%s', type(exc).__name__)
raise _gateway_failure('direct_timeout', started, retryable=True) from exc
except httpx.TransportError as exc:
raise _gateway_failure('direct_connection', started, retryable=True) from exc
@@ -186,6 +362,8 @@ def complete_json(instruction: str, content: dict, schema: dict | None = None, *
raise _gateway_failure('direct_invalid_response', started) from exc
else:
raise ModelUnavailable("No configured assistant model")
if progress is not None:
progress.check_active(True)
raw = re.sub(r"^```(?:json)?\s*|\s*```$", "", str(raw).strip())
result = json.loads(raw)
if not isinstance(result, dict):