197 lines
9.8 KiB
Python
197 lines
9.8 KiB
Python
"""Stateless language generation using the assistant's already configured model gateway."""
|
|
import json
|
|
import re
|
|
import logging
|
|
import time
|
|
from functools import lru_cache
|
|
|
|
import httpx
|
|
|
|
from app.core.config import get_settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
def _model_client() -> httpx.Client:
|
|
return httpx.Client(trust_env=False, limits=httpx.Limits(max_connections=20, max_keepalive_connections=10))
|
|
|
|
|
|
def close_model_client() -> None:
|
|
if _model_client.cache_info().currsize:
|
|
_model_client().close()
|
|
_model_client.cache_clear()
|
|
|
|
|
|
class ModelUnavailable(RuntimeError):
|
|
def __init__(self, reason, *, retryable=False):
|
|
super().__init__(reason)
|
|
self.reason = reason
|
|
self.retryable = retryable
|
|
|
|
|
|
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 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:
|
|
started = time.perf_counter()
|
|
settings = get_settings()
|
|
instruction = _contract_instruction(instruction, 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"},
|
|
}
|
|
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)
|
|
raw = data["choices"][0]["message"]["content"]
|
|
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"},
|
|
}
|
|
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']
|
|
logger.info('assistant_direct_model model=%s elapsed_ms=%d',
|
|
settings.direct_llm_model, (time.perf_counter()-started)*1000)
|
|
except ModelUnavailable:
|
|
raise
|
|
except httpx.TimeoutException as exc:
|
|
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")
|
|
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
|