-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathconfig_api.py
More file actions
306 lines (256 loc) · 9.09 KB
/
config_api.py
File metadata and controls
306 lines (256 loc) · 9.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""配置管理 API"""
from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Dict, Any, Optional, List
import json
from pathlib import Path
router = APIRouter(prefix="/config", tags=["Config"])
# 配置模型
class ConfigUpdateRequest(BaseModel):
updates: Dict[str, Any]
class AgentConfigRequest(BaseModel):
name: str
description: Optional[str] = None
max_steps: Optional[int] = 200
permission: Optional[Dict[str, Any]] = None
class SandboxConfigRequest(BaseModel):
enabled: Optional[bool] = None
image: Optional[str] = None
memory_limit: Optional[str] = None
timeout: Optional[int] = None
# 全局配置管理器
_config_manager = None
def get_config_manager():
global _config_manager
if _config_manager is None:
from derisk_core.config import ConfigManager
_config_manager = ConfigManager
return _config_manager
@router.get("/current")
async def get_current_config():
"""获取当前完整配置"""
try:
manager = get_config_manager()
config = manager.get()
return JSONResponse(content={
"success": True,
"data": config.model_dump(mode="json")
})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/schema")
async def get_config_schema():
"""获取配置 Schema(用于前端表单生成)"""
from derisk_core.config import AppConfig, AgentConfig, ModelConfig, SandboxConfig
schema = {
"app": AppConfig.model_json_schema(),
"agent": AgentConfig.model_json_schema(),
"model": ModelConfig.model_json_schema(),
"sandbox": SandboxConfig.model_json_schema()
}
return JSONResponse(content={
"success": True,
"data": schema
})
@router.get("/model")
async def get_model_config():
"""获取模型配置"""
manager = get_config_manager()
config = manager.get()
return JSONResponse(content={
"success": True,
"data": config.default_model.model_dump()
})
@router.post("/model")
async def update_model_config(request: Dict[str, Any]):
"""更新模型配置"""
try:
manager = get_config_manager()
config = manager.get()
# 更新模型配置
for key, value in request.items():
if hasattr(config.default_model, key):
setattr(config.default_model, key, value)
return JSONResponse(content={
"success": True,
"message": "模型配置已更新",
"data": config.default_model.model_dump()
})
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@router.get("/agents")
async def list_agents():
"""列出所有 Agent 配置"""
manager = get_config_manager()
config = manager.get()
agents = []
for name, agent in config.agents.items():
agents.append({
"name": agent.name,
"description": agent.description,
"max_steps": agent.max_steps,
"color": agent.color,
"permission": agent.permission.model_dump() if agent.permission else None
})
return JSONResponse(content={
"success": True,
"data": agents
})
@router.get("/agents/{agent_name}")
async def get_agent_config(agent_name: str):
"""获取指定 Agent 配置"""
manager = get_config_manager()
config = manager.get()
if agent_name not in config.agents:
raise HTTPException(status_code=404, detail=f"Agent '{agent_name}' not found")
agent = config.agents[agent_name]
return JSONResponse(content={
"success": True,
"data": agent.model_dump()
})
@router.post("/agents")
async def create_agent(request: AgentConfigRequest):
"""创建新 Agent"""
try:
manager = get_config_manager()
config = manager.get()
from derisk_core.config import AgentConfig, PermissionConfig
agent = AgentConfig(
name=request.name,
description=request.description or "",
max_steps=request.max_steps or 200,
permission=PermissionConfig(**request.permission) if request.permission else PermissionConfig()
)
config.agents[request.name] = agent
return JSONResponse(content={
"success": True,
"message": f"Agent '{request.name}' created",
"data": agent.model_dump()
})
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@router.put("/agents/{agent_name}")
async def update_agent(agent_name: str, request: Dict[str, Any]):
"""更新 Agent 配置"""
try:
manager = get_config_manager()
config = manager.get()
if agent_name not in config.agents:
raise HTTPException(status_code=404, detail=f"Agent '{agent_name}' not found")
agent = config.agents[agent_name]
for key, value in request.items():
if hasattr(agent, key):
setattr(agent, key, value)
return JSONResponse(content={
"success": True,
"message": f"Agent '{agent_name}' updated",
"data": agent.model_dump()
})
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@router.delete("/agents/{agent_name}")
async def delete_agent(agent_name: str):
"""删除 Agent"""
try:
manager = get_config_manager()
config = manager.get()
if agent_name not in config.agents:
raise HTTPException(status_code=404, detail=f"Agent '{agent_name}' not found")
if agent_name == "primary":
raise HTTPException(status_code=400, detail="Cannot delete primary agent")
del config.agents[agent_name]
return JSONResponse(content={
"success": True,
"message": f"Agent '{agent_name}' deleted"
})
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@router.get("/sandbox")
async def get_sandbox_config():
"""获取沙箱配置"""
manager = get_config_manager()
config = manager.get()
return JSONResponse(content={
"success": True,
"data": config.sandbox.model_dump()
})
@router.post("/sandbox")
async def update_sandbox_config(request: SandboxConfigRequest):
"""更新沙箱配置"""
try:
manager = get_config_manager()
config = manager.get()
if request.enabled is not None:
config.sandbox.enabled = request.enabled
if request.image:
config.sandbox.image = request.image
if request.memory_limit:
config.sandbox.memory_limit = request.memory_limit
if request.timeout:
config.sandbox.timeout = request.timeout
return JSONResponse(content={
"success": True,
"message": "沙箱配置已更新",
"data": config.sandbox.model_dump()
})
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@router.post("/validate")
async def validate_config():
"""验证当前配置"""
try:
manager = get_config_manager()
config = manager.get()
from derisk_core.config import ConfigValidator
warnings = ConfigValidator.validate(config)
return JSONResponse(content={
"success": True,
"data": {
"valid": len([w for w in warnings if w[0] == "error"]) == 0,
"warnings": [{"level": w[0], "message": w[1]} for w in warnings]
}
})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.post("/reload")
async def reload_config():
"""重新加载配置"""
try:
manager = get_config_manager()
config = manager.reload()
return JSONResponse(content={
"success": True,
"message": "配置已重新加载",
"data": config.model_dump(mode="json")
})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/export")
async def export_config():
"""导出配置为 JSON"""
manager = get_config_manager()
config = manager.get()
return JSONResponse(
content={
"success": True,
"data": config.model_dump(mode="json", exclude_none=True)
}
)
@router.post("/import")
async def import_config(config_data: Dict[str, Any]):
"""导入配置"""
try:
from derisk_core.config import AppConfig
config = AppConfig(**config_data)
manager = get_config_manager()
manager._config = config
return JSONResponse(content={
"success": True,
"message": "配置已导入",
"data": config.model_dump(mode="json")
})
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))