重构第1批:新增统一异常体系,扩展 schemas,添加 fastapi/uvicorn 依赖

- 新增 errors.py:EkbError 基类 + 6 个子类(NotLoggedIn/Authentication/
  NotFound/Conflict/Input/ApiResponse),供所有层统一使用
- schemas.py:追加 Server 请求/响应模型(ApiResult / Corp* / Agent*Request /
  Rule*Request),与快报 API 模型分区维护
- pyproject.toml:新增 fastapi>=0.115.0、uvicorn[standard]>=0.34.0
This commit is contained in:
gitea committed 2026-04-14 11:03:27 +08:00
1 parent 8ae14842cc
commit 4faba77234
4 files changed
+444 -7

No files matched your search

+94 -7
View File
@@ -1,17 +1,21 @@
"""Pydantic 响应模型:快报 API 结构校验"""
"""Pydantic 响应模型:快报 API 结构校验 + ekb-cli Server 请求/响应模型
分为两部分:
1. 快报 API 响应模型(EkbResponse / PageData / Rule / Agent 系列)
2. ekb-cli HTTP Server 的请求/响应模型(*Request / *Response / ApiResult)
"""
from typing import Any, Generic, List, Optional, TypeVar
from pydantic import BaseModel, ConfigDict
# 允许字段多于定义(快报可能新增字段),但已知字段必须类型正确
# 允许字段多于定义(快报可能新增字段),已知字段必须类型正确
_cfg = ConfigDict(extra="allow")
# ── 通用分页响应 ────────────────────────────────────────────────
T = TypeVar("T")
# ── 快报 API:通用分页响应 ─────────────────────────────────────
class PageData(BaseModel, Generic[T]):
model_config = _cfg
number: int
@@ -28,7 +32,7 @@ class EkbResponse(BaseModel, Generic[T]):
data: Optional[T] = None
# ── Rule(审核规则)────────────────────────────────────────────
# ── 快报 API:Rule(审核规则)────────────────────────────────
class RuleAgentRef(BaseModel):
"""规则列表中关联的 Agent 摘要(仅 id/name/icon)"""
@@ -60,7 +64,7 @@ class RuleWithAgents(Rule):
freeflows: List[Any] = []
# ── Agent(智能审核 Agent)─────────────────────────────────────
# ── 快报 API:Agent(智能审核 Agent)─────────────────────────
class AgentRuleRef(Rule):
"""Agent 详情中内嵌的规则(完整规则字段,无 agents 字段)"""
@@ -92,3 +96,86 @@ class AgentDetail(AgentSummary):
"""Agent 详情(含关联规则列表)"""
agentRule: List[AgentRuleRef] = []
enrichedContext: Optional[Any] = None
# ══════════════════════════════════════════════════════════════
# ekb-cli HTTP Server 请求/响应模型
# 这些模型用于 FastAPI 路由的请求体(*Request)和响应体(*Response)
# 与快报 API 的模型分开维护,避免耦合
# ══════════════════════════════════════════════════════════════
DEFAULT_AGENT_ICON = "https://statics.ekuaibao.com/eui/eui-static/male5.png"
class ApiResult(BaseModel, Generic[T]):
"""ekb-cli Server 统一响应包装
成功时:{"success": true, "data": {...}}
失败时:{"success": false, "error": "...", "code": 404}
"""
success: bool = True
data: Optional[T] = None
error: Optional[str] = None
code: int = 0
# ── Server:Auth 请求/响应 ──────────────────────────────────
class CorpAddRequest(BaseModel):
"""添加企业认证的请求体"""
corp_id: str
name: str
access_token: str
staff_id: str
class CorpInfoResponse(BaseModel):
"""企业信息响应(不含敏感 token)"""
corp_id: str
name: str
is_current: bool
# ── Server:Agent 请求 ──────────────────────────────────────
class AgentCreateRequest(BaseModel):
"""新建 Agent 的请求体"""
name: str
description: str = ""
mode: str = "assist" # auto / semi / assist
sampling_rate: int = 0
agree_terms: str = ""
reject_terms: str = ""
exempt_terms: str = ""
review_terms: str = ""
rule_ids: List[str] = []
icon: str = DEFAULT_AGENT_ICON
class AgentUpdateRequest(BaseModel):
"""更新 Agent 的请求体(所有字段可选,只传需要改的)"""
name: Optional[str] = None
description: Optional[str] = None
mode: Optional[str] = None # auto / semi / assist
sampling_rate: Optional[int] = None
state: Optional[int] = None
agree_terms: Optional[str] = None
reject_terms: Optional[str] = None
exempt_terms: Optional[str] = None
review_terms: Optional[str] = None
# ── Server:Rule 请求 ───────────────────────────────────────
class RuleCreateRequest(BaseModel):
"""新建规则的请求体"""
purpose: str
description: str
level: str = "严重"
class RuleUpdateRequest(BaseModel):
"""更新规则的请求体(所有字段可选)"""
purpose: Optional[str] = None
description: Optional[str] = None
level: Optional[str] = None
+59
View File
@@ -0,0 +1,59 @@
"""统一业务异常体系
所有层(api / service / server / commands)统一使用此模块的异常类。
- CLI 层:捕获 EkbError,用 rich 红字输出并 Exit(1)
- Server 层:捕获 EkbError,转换为对应 HTTP 状态码的 JSON 响应
- API 层:捕获 httpx 错误,转换为 AuthenticationError / ApiResponseError
"""
class EkbError(Exception):
"""所有业务异常的基类"""
def __init__(self, message: str, code: int = -1):
self.message = message
self.code = code
super().__init__(message)
class NotLoggedInError(EkbError):
"""未登录/未配置认证"""
def __init__(self) -> None:
super().__init__("未登录,请先执行 `ekb auth add` 添加企业认证", code=401)
class AuthenticationError(EkbError):
"""认证失败:token 过期或无效(HTTP 401)"""
def __init__(self, message: str = "认证已过期,请重新执行 `ekb auth add` 更新 token") -> None:
super().__init__(message, code=401)
class NotFoundError(EkbError):
"""目标资源不存在(HTTP 404)"""
def __init__(self, resource: str, ref: str) -> None:
super().__init__(f"{resource} 不存在:{ref}", code=404)
class ConflictError(EkbError):
"""资源冲突,例如名称重复(HTTP 409)"""
def __init__(self, message: str) -> None:
super().__init__(message, code=409)
class InputError(EkbError):
"""参数/输入校验失败(HTTP 422)"""
def __init__(self, message: str) -> None:
super().__init__(message, code=422)
class ApiResponseError(EkbError):
"""快报 API 返回非 0 业务码"""
def __init__(self, api_code: int, msg: str) -> None:
super().__init__(f"快报 API 错误 [{api_code}]: {msg}", code=api_code)