Files
company-ai-platform/app/modules/work_assistant/model_gateway.py
T
2026-11-18 16:01:50 +08:00

382 lines
20 KiB
Python

"""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
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:
with _client_lock:
return _cached_model_client()
def close_model_client() -> None:
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, retry_after=None):
super().__init__(reason)
self.reason = reason
self.retryable = retryable
self.retry_after = retry_after
def _gateway_failure(reason, started, *, retryable=False):
from app.core.http.request_context import get_request_id
logger.warning('assistant_gateway_failure reason=%s elapsed_ms=%d request_id=%r',
reason, (time.perf_counter() - started) * 1000, get_request_id())
return ModelUnavailable(reason, retryable=retryable)
class PlanningModel:
"""One transient recovery across all planning stages, within a shared deadline."""
def __init__(self, invoke, budget_seconds):
self.invoke = invoke
self.deadline = time.monotonic() + budget_seconds
self.retried = False
def __call__(self, *args, timeout_seconds, **kwargs):
while True:
remaining = self.deadline - time.monotonic()
if remaining < 1:
raise ModelUnavailable('planning_deadline')
try:
return self.invoke(*args, timeout_seconds=min(timeout_seconds, remaining, 12), **kwargs)
except ModelUnavailable as exc:
remaining = self.deadline - time.monotonic()
if not exc.retryable or self.retried or remaining < 2:
raise
self.retried = True
logger.warning('assistant_planning_retry reason=%s remaining_seconds=%.1f', exc.reason, remaining)
def _contract_instruction(instruction: str, schema: dict | None) -> str:
if not schema:
return instruction
def compact(value, property_map=False):
if isinstance(value, dict):
# Annotation names may also be actual business field names. Preserve
# them inside properties/$defs instead of silently deleting fields.
return {key: compact(item, key in {'properties', '$defs', 'definitions'})
for key, item in value.items()
if property_map or key not in {'title','default','description'}}
if isinstance(value, list):
return [compact(item) for item in value]
return value
# Some compatible gateways accept response_format yet do not enforce its schema
# upstream. Make the exact contract visible to the model as well; local typed
# validation is still mandatory and no gateway behavior is assumed.
return instruction+'\n输出须符合以下JSON Schema;只填写本轮必要字段,不复述schema,不添加解释字段:\n'+json.dumps(compact(schema),ensure_ascii=False,separators=(',',':'))
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', {}):
return schema
result = json.loads(json.dumps(schema))
result['properties']['answer'].pop('maxLength', None)
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,
prose: bool = False, prompt_schema: dict | None = None,
minimum_execution_seconds: float = 0) -> 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, prompt_schema if prompt_schema is not None else 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:
if minimum_execution_seconds and timeout_seconds-(time.monotonic()-started)<minimum_execution_seconds:
# 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,
timeout_seconds=max(0.1, timeout_seconds - (time.monotonic() - started)),
max_tokens=max_tokens, images=images, prose=prose, prompt_schema=prompt_schema)
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, prompt_schema: dict | None = None) -> 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
# The decoder still receives the full schema below. A caller can describe
# its shape concisely in the prompt instead of duplicating long ID branches.
instruction = _contract_instruction(instruction, prompt_schema if prompt_schema is not None else schema)
if not settings.work_assistant_model_enabled:
raise ModelUnavailable("Model routing is disabled")
gateway = (settings.work_assistant_model_control_url or "").strip().rstrip("/")
user_content = json.dumps(content, ensure_ascii=False, separators=(",", ":"))
if images:
if len(images) > 2:
raise ValueError("最多传入两张原图")
parts = [{"type": "text", "text": user_content}]
for file_id, data_url in images:
parts.extend([{"type": "text", "text": f"附件 {file_id} 的画面"},
{"type": "image_url", "image_url": {"url": data_url}}])
user_content = parts
if gateway:
key = settings.work_assistant_model_control_api_key
request = {
"messages": [{"role": "system", "content": instruction},
{"role": "user", "content": user_content}],
"temperature": 0.1,
"max_tokens": max_tokens,
"response_format": {"type": "json_schema", "json_schema": {
"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)))
if response.is_error:
if '"Arrearage"' in response.text[:16384].replace('\\"', '"'):
raise _gateway_failure('model_account_unavailable', started)
raise _gateway_failure(f'gateway_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('gateway_response_too_large', started)
envelope = response.json()
if envelope.get("code", 200) not in (0, 200):
if '"Arrearage"' in str(envelope.get('message', '')).replace('\\"', '"'):
raise _gateway_failure('model_account_unavailable', started)
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,
usage.get("prompt_tokens"), usage.get("completion_tokens"))
except ModelUnavailable:
raise
except httpx.TimeoutException as exc:
raise _gateway_failure('gateway_timeout', started, retryable=True) from exc
except httpx.TransportError as exc:
raise _gateway_failure('gateway_connection', started, retryable=True) from exc
except Exception as exc:
# No credentials, upstream bodies or user material in exception messages.
raise _gateway_failure('gateway_invalid_response', started) from exc
elif settings.direct_llm_api_key:
# Use the native compatible endpoint with the same structured contract and
# output budget as the gateway; ordinary chat adapters omit those controls.
request = {
"model": settings.direct_llm_model,
"messages": [{"role": "system", "content": instruction},
{"role": "user", "content": user_content}],
"temperature": 0.1, "max_tokens": max_tokens,
"response_format": {"type": "json_schema", "json_schema": {
"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:
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 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
except Exception as exc:
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):
raise ValueError("Model response must be one JSON object")
answer_limit = (schema or {}).get('properties', {}).get('answer', {}).get('maxLength')
if isinstance(answer_limit, int) and isinstance(result.get('answer'), str) and len(result['answer']) > answer_limit:
raise ValueError("Model answer exceeds the original length limit")
return result