重构:api层拆分 agent/rule,引入 Pydantic 校验,统一 re-export,补充 README.api.md
This commit is contained in:
1 parent
c3c389146f
commit
4466af7726
16 files changed
+487
-216
No files matched your search
@@ -0,0 +1,84 @@
|
||||
# API 层说明(`ekb_cli/api/`)
|
||||
|
||||
## 三层架构
|
||||
|
||||
```
|
||||
api/
|
||||
├── __init__.py # 第1层:HTTP 客户端(EkbClient)+ 统一 re-export
|
||||
├── schemas.py # 第2层辅助:Pydantic 响应模型,所有接口响应在此校验
|
||||
├── agent.py # 第2层:Agent 相关接口封装
|
||||
└── rule.py # 第2层:Rule(审核规则)相关接口封装
|
||||
```
|
||||
|
||||
**commands 只从 `ekb_cli.api` 导入**,内部文件如何拆分对上层透明:
|
||||
|
||||
```python
|
||||
from ekb_cli.api import get_client, list_agents, get_agent, list_rules, ...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## `__init__.py` — HTTP 客户端
|
||||
|
||||
`EkbClient` 负责:带认证头(`accesstoken` / `corpid` / `staffid`)发 HTTP 请求,返回原始 JSON。它不理解业务。
|
||||
|
||||
| 方法 | 说明 |
|
||||
|------|------|
|
||||
| `get(path, **params)` | GET 请求,自动附加 `corpId` |
|
||||
| `post(path, body, **params)` | POST 请求,body 为 JSON |
|
||||
|
||||
`get_client()` 从 `~/.config/ekb-cli/config.json` 读取当前企业认证信息,构建 `EkbClient`。
|
||||
|
||||
---
|
||||
|
||||
## `schemas.py` — Pydantic 响应模型
|
||||
|
||||
所有模型使用 `extra="allow"`(允许快报新增字段,但已知字段强制类型校验)。API 格式变更时,Pydantic 会抛出 `ValidationError`,精确定位到字段名。
|
||||
|
||||
| 模型 | 用途 |
|
||||
|------|------|
|
||||
| `EkbResponse[T]` | 通用响应包装(`code` / `msg` / `data`) |
|
||||
| `PageData[T]` | 通用分页(`totalItems` / `items`) |
|
||||
| `AgentSummary` | Agent 列表中的摘要条目(无 `agentRule`) |
|
||||
| `AgentDetail` | Agent 详情(含 `agentRule` 列表) |
|
||||
| `AgentRuleRef` | `AgentDetail` 中内嵌的规则完整字段 |
|
||||
| `Rule` | 规则新建/更新的响应体 |
|
||||
| `RuleWithAgents` | 规则列表中的条目(含 `agents` 关联摘要) |
|
||||
| `RuleAgentRef` | `RuleWithAgents` 中关联 Agent 摘要(`id/name/icon`) |
|
||||
|
||||
---
|
||||
|
||||
## `agent.py` — Agent 接口
|
||||
|
||||
| 函数 | 方法 | 路径 | 返回 |
|
||||
|------|------|------|------|
|
||||
| `check_agent_name(client, name)` | GET | `/engine/hab/agent/checkName` | `bool`(`True`=可用) |
|
||||
| `list_agents(client, page, size)` | GET | `/engine/hab/agent/list` | `PageData[AgentSummary]` |
|
||||
| `get_agent(client, agent_id)` | GET | `/engine/hab/agent/detail` | `AgentDetail` |
|
||||
| `save_agent(client, payload)` | POST | `/engine/hab/agent/save` | `AgentDetail` |
|
||||
|
||||
> `save_agent` 同时承担新建(无 `id`)和更新(有 `id`)。
|
||||
|
||||
---
|
||||
|
||||
## `rule.py` — Rule 接口
|
||||
|
||||
| 函数 | 方法 | 路径 | 返回 |
|
||||
|------|------|------|------|
|
||||
| `list_rules(client, page, size)` | GET | `/engine/hab/agent/rule/list` | `PageData[RuleWithAgents]` |
|
||||
| `save_rule(client, payload)` | POST | `/engine/hab/agent/rule/save` | `Rule` |
|
||||
| `update_rule(client, payload)` | POST | `/engine/hab/agent/rule/update` | `Rule` |
|
||||
|
||||
---
|
||||
|
||||
## 接口格式变更应对
|
||||
|
||||
快报前端更新后若接口格式改变,Pydantic 会在第一次调用时抛出 `ValidationError`,输出类似:
|
||||
|
||||
```
|
||||
pydantic_core._pydantic_core.ValidationError: 1 validation error for AgentDetail
|
||||
agentRule
|
||||
Field required [type=missing, ...]
|
||||
```
|
||||
|
||||
定位方式:字段名 → `schemas.py` 对应模型 → 对照实际响应 JSON 更新字段定义。
|
||||
@@ -54,3 +54,17 @@ def get_client() -> EkbClient:
|
||||
access_token=corp["access_token"],
|
||||
staff_id=corp["staff_id"],
|
||||
)
|
||||
|
||||
|
||||
# ── 统一 re-export:commands 只从这里导入,内部拆分对外透明 ──────────
|
||||
from ekb_cli.api.agent import ( # noqa: E402
|
||||
check_agent_name,
|
||||
list_agents,
|
||||
get_agent,
|
||||
save_agent,
|
||||
)
|
||||
from ekb_cli.api.rule import ( # noqa: E402
|
||||
list_rules,
|
||||
save_rule,
|
||||
update_rule,
|
||||
)
|
||||
+18
-22
@@ -1,35 +1,31 @@
|
||||
"""Agent 相关 API 调用封装"""
|
||||
|
||||
from ekb_cli.api import EkbClient
|
||||
from ekb_cli.api.schemas import (
|
||||
AgentDetail, AgentSummary, EkbResponse, PageData
|
||||
)
|
||||
|
||||
|
||||
def check_agent_name(client: EkbClient, name: str) -> bool:
|
||||
"""检查名称是否可用:True=可用,False=已存在(接口 data=false 表示可用)"""
|
||||
resp = client.get("/engine/hab/agent/checkName", name=name)
|
||||
return not resp.get("data", False)
|
||||
raw = client.get("/engine/hab/agent/checkName", name=name)
|
||||
EkbResponse[bool].model_validate(raw)
|
||||
return not raw.get("data", False)
|
||||
|
||||
|
||||
def list_agents(client: EkbClient, page: int = 1, size: int = 1000) -> dict:
|
||||
return client.get("/engine/hab/agent/list", page=page, size=size)
|
||||
def list_agents(client: EkbClient, page: int = 1, size: int = 1000) -> PageData[AgentSummary]:
|
||||
raw = client.get("/engine/hab/agent/list", page=page, size=size)
|
||||
resp = EkbResponse[PageData[AgentSummary]].model_validate(raw)
|
||||
return resp.data
|
||||
|
||||
|
||||
def get_agent(client: EkbClient, agent_id: str) -> dict:
|
||||
return client.get("/engine/hab/agent/detail", id=agent_id)
|
||||
def get_agent(client: EkbClient, agent_id: str) -> AgentDetail:
|
||||
raw = client.get("/engine/hab/agent/detail", id=agent_id)
|
||||
resp = EkbResponse[AgentDetail].model_validate(raw)
|
||||
return resp.data
|
||||
|
||||
|
||||
def save_agent(client: EkbClient, payload: dict) -> dict:
|
||||
return client.post("/engine/hab/agent/save", payload)
|
||||
|
||||
|
||||
def list_rules(client: EkbClient, page: int = 1, size: int = 1000) -> dict:
|
||||
return client.get("/engine/hab/agent/rule/list", page=page, size=size)
|
||||
|
||||
|
||||
def save_rule(client: EkbClient, payload: dict) -> dict:
|
||||
"""新建规则:payload 包含 purpose / description / level"""
|
||||
return client.post("/engine/hab/agent/rule/save", payload)
|
||||
|
||||
|
||||
def update_rule(client: EkbClient, payload: dict) -> dict:
|
||||
"""更新规则:payload 包含 id / code / purpose / description / level"""
|
||||
return client.post("/engine/hab/agent/rule/update", payload)
|
||||
def save_agent(client: EkbClient, payload: dict) -> AgentDetail:
|
||||
raw = client.post("/engine/hab/agent/save", payload)
|
||||
resp = EkbResponse[AgentDetail].model_validate(raw)
|
||||
return resp.data
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Rule(审核规则)相关 API 调用封装"""
|
||||
|
||||
from ekb_cli.api import EkbClient
|
||||
from ekb_cli.api.schemas import (
|
||||
EkbResponse, PageData, Rule, RuleWithAgents
|
||||
)
|
||||
|
||||
|
||||
def list_rules(client: EkbClient, page: int = 1, size: int = 1000) -> PageData[RuleWithAgents]:
|
||||
raw = client.get("/engine/hab/agent/rule/list", page=page, size=size)
|
||||
resp = EkbResponse[PageData[RuleWithAgents]].model_validate(raw)
|
||||
return resp.data
|
||||
|
||||
|
||||
def save_rule(client: EkbClient, payload: dict) -> Rule:
|
||||
"""新建规则:payload 包含 purpose / description / level"""
|
||||
raw = client.post("/engine/hab/agent/rule/save", payload)
|
||||
resp = EkbResponse[Rule].model_validate(raw)
|
||||
return resp.data
|
||||
|
||||
|
||||
def update_rule(client: EkbClient, payload: dict) -> Rule:
|
||||
"""更新规则:payload 包含 id / code / purpose / description / level"""
|
||||
raw = client.post("/engine/hab/agent/rule/update", payload)
|
||||
resp = EkbResponse[Rule].model_validate(raw)
|
||||
return resp.data
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Pydantic 响应模型:快报 API 结构校验"""
|
||||
|
||||
from typing import Any, Generic, List, Optional, TypeVar
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
# 允许字段多于定义(快报可能新增字段),但已知字段必须类型正确
|
||||
_cfg = ConfigDict(extra="allow")
|
||||
|
||||
|
||||
# ── 通用分页响应 ────────────────────────────────────────────────
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class PageData(BaseModel, Generic[T]):
|
||||
model_config = _cfg
|
||||
number: int
|
||||
size: int
|
||||
totalPages: int
|
||||
totalItems: int
|
||||
items: List[T]
|
||||
|
||||
|
||||
class EkbResponse(BaseModel, Generic[T]):
|
||||
model_config = _cfg
|
||||
code: int
|
||||
msg: str = ""
|
||||
data: Optional[T] = None
|
||||
|
||||
|
||||
# ── Rule(审核规则)────────────────────────────────────────────
|
||||
|
||||
class RuleAgentRef(BaseModel):
|
||||
"""规则列表中关联的 Agent 摘要(仅 id/name/icon)"""
|
||||
model_config = _cfg
|
||||
id: str
|
||||
name: str
|
||||
icon: str = ""
|
||||
|
||||
|
||||
class Rule(BaseModel):
|
||||
model_config = _cfg
|
||||
id: str
|
||||
corporationId: str
|
||||
code: str
|
||||
version: int
|
||||
purpose: str
|
||||
description: str
|
||||
level: str
|
||||
createTime: str
|
||||
updateTime: str
|
||||
active: bool
|
||||
staffId: str = ""
|
||||
staffName: str = ""
|
||||
|
||||
|
||||
class RuleWithAgents(Rule):
|
||||
"""规则列表响应中的规则(含关联 Agent 列表)"""
|
||||
agents: List[RuleAgentRef] = []
|
||||
freeflows: List[Any] = []
|
||||
|
||||
|
||||
# ── Agent(智能审核 Agent)─────────────────────────────────────
|
||||
|
||||
class AgentRuleRef(Rule):
|
||||
"""Agent 详情中内嵌的规则(完整规则字段,无 agents 字段)"""
|
||||
pass
|
||||
|
||||
|
||||
class AgentSummary(BaseModel):
|
||||
"""Agent 列表中的摘要(无 agentRule 字段)"""
|
||||
model_config = _cfg
|
||||
id: str
|
||||
corporationId: str
|
||||
version: int
|
||||
name: str
|
||||
description: str = ""
|
||||
icon: str = ""
|
||||
mode: int
|
||||
samplingRate: int = 0
|
||||
agreeTerms: str = ""
|
||||
rejectTerms: str = ""
|
||||
exemptTerms: str = ""
|
||||
reviewTerms: str = ""
|
||||
createTime: str
|
||||
updateTime: str
|
||||
state: int
|
||||
agentFlowRelations: List[Any] = []
|
||||
|
||||
|
||||
class AgentDetail(AgentSummary):
|
||||
"""Agent 详情(含关联规则列表)"""
|
||||
agentRule: List[AgentRuleRef] = []
|
||||
enrichedContext: Optional[Any] = None
|
||||
Reference in new issue
Block a user