feat:简化部分代码
This commit is contained in:
+16
-54
@@ -1,8 +1,6 @@
|
||||
"""可复用的 Jev 决策客户端;重试和 HTTP 连接管理交给官方 SDK"""
|
||||
|
||||
from functools import cache
|
||||
from math import isclose
|
||||
from typing import Self
|
||||
|
||||
from pydantic import ValidationError
|
||||
from typesafe_sdk import (
|
||||
@@ -29,24 +27,11 @@ from app.schemas.decision import (
|
||||
|
||||
|
||||
class DecisionEngine:
|
||||
def __init__(
|
||||
self,
|
||||
config: Settings | None = None,
|
||||
*,
|
||||
client: AsyncTypeSafeClient | None = None,
|
||||
):
|
||||
def __init__(self, config: Settings | None = None):
|
||||
self._config = config if config is not None else settings
|
||||
self._client = client
|
||||
self._owns_client = client is None
|
||||
self._closed = False
|
||||
|
||||
@property
|
||||
def closed(self) -> bool:
|
||||
return self._closed
|
||||
self._client: AsyncTypeSafeClient | None = None
|
||||
|
||||
def _get_client(self) -> AsyncTypeSafeClient:
|
||||
if self._closed:
|
||||
raise DecisionError("决策客户端已关闭", kind="closed")
|
||||
if self._client is None:
|
||||
config = self._config
|
||||
if not config.typesafe_api_key.strip():
|
||||
@@ -69,8 +54,6 @@ class DecisionEngine:
|
||||
return self._client
|
||||
|
||||
async def run(self, request: DecisionRequest) -> DecisionResponse:
|
||||
# 即便模型实例在创建后被修改,也必须重新经过请求校验
|
||||
request = DecisionRequest.model_validate(request.model_dump(mode="json"))
|
||||
client = self._get_client()
|
||||
questions = {
|
||||
name: question.model_dump(mode="json", exclude_unset=True)
|
||||
@@ -136,27 +119,18 @@ class DecisionEngine:
|
||||
answer = result.results[name]
|
||||
if answer.type != question.type:
|
||||
raise ValueError("返回的决策类型与请求不一致")
|
||||
if isinstance(question, ChoiceDecision) and isinstance(
|
||||
answer, ChoiceResult
|
||||
if (
|
||||
isinstance(question, ChoiceDecision)
|
||||
and isinstance(answer, ChoiceResult)
|
||||
and answer.choice not in question.criteria
|
||||
):
|
||||
if answer.choice not in question.criteria:
|
||||
raise ValueError("返回了候选集合之外的选项")
|
||||
if answer.probabilities.keys() != question.criteria.keys():
|
||||
raise ValueError("选项概率不完整")
|
||||
if isinstance(question, ScoreDecision) and isinstance(
|
||||
answer, ScoreResult
|
||||
raise ValueError("返回了候选集合之外的选项")
|
||||
if (
|
||||
isinstance(question, ScoreDecision)
|
||||
and isinstance(answer, ScoreResult)
|
||||
and not 0 <= answer.score <= len(question.criteria) - 1
|
||||
):
|
||||
levels = {str(index) for index in range(len(question.criteria))}
|
||||
if (
|
||||
answer.probabilities.keys() != levels
|
||||
or answer.legend.keys() != levels
|
||||
):
|
||||
raise ValueError("评分等级不完整")
|
||||
if not 0 <= answer.score <= len(question.criteria) - 1:
|
||||
raise ValueError("评分超出等级范围")
|
||||
if isinstance(answer, (ChoiceResult, ScoreResult)):
|
||||
if not isclose(sum(answer.probabilities.values()), 1, abs_tol=1e-4):
|
||||
raise ValueError("概率之和不为 1")
|
||||
raise ValueError("评分超出等级范围")
|
||||
return result
|
||||
except (ValidationError, ValueError) as error:
|
||||
raise DecisionError(
|
||||
@@ -166,17 +140,9 @@ class DecisionEngine:
|
||||
) from error
|
||||
|
||||
async def aclose(self) -> None:
|
||||
if not self._closed:
|
||||
if self._owns_client and self._client is not None:
|
||||
await self._client.aclose()
|
||||
self._closed = True
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
self._get_client()
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
|
||||
await self.aclose()
|
||||
if self._client is not None:
|
||||
await self._client.aclose()
|
||||
self._client = None
|
||||
|
||||
|
||||
@cache
|
||||
@@ -186,11 +152,7 @@ def _cached_engine() -> DecisionEngine:
|
||||
|
||||
def get_decision_engine() -> DecisionEngine:
|
||||
"""与 get_llm 类似的共享入口;适用于单个服务事件循环"""
|
||||
engine = _cached_engine()
|
||||
if engine.closed:
|
||||
_cached_engine.cache_clear()
|
||||
engine = _cached_engine()
|
||||
return engine
|
||||
return _cached_engine()
|
||||
|
||||
|
||||
async def close_decision_engine() -> None:
|
||||
|
||||
Reference in New Issue
Block a user