agents.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. """
  2. api.v1.agents — Agent CRUD + Execution endpoints.
  3. POST /api/v1/agents Create agent
  4. GET /api/v1/agents List agents
  5. GET /api/v1/agents/{agent_id} Get agent
  6. PUT /api/v1/agents/{agent_id} Update agent (auto version)
  7. DELETE /api/v1/agents/{agent_id} Soft delete
  8. POST /api/v1/agents/{agent_id}/run Synchronous execution
  9. POST /api/v1/agents/{agent_id}/rollback Rollback version
  10. """
  11. from __future__ import annotations
  12. import json
  13. import hashlib
  14. import time
  15. from typing import Any, Dict, Optional
  16. from fastapi import APIRouter, Depends, HTTPException
  17. from fastapi.responses import StreamingResponse
  18. from pydantic import BaseModel, Field
  19. from agentpaas.api.deps import get_tenant, get_database
  20. from agentpaas.api.middleware.auth import TenantContext
  21. from agentpaas.db.models import Database, gen_id, now_utc
  22. router = APIRouter(prefix="/agents", tags=["agents"])
  23. # ── Request/Response Models ──
  24. class CreateAgentRequest(BaseModel):
  25. name: str = Field(..., max_length=256)
  26. description: str = Field(default="", max_length=4096)
  27. config: Dict[str, Any]
  28. tags: list = Field(default_factory=list)
  29. environment: str = Field(default="production", max_length=64)
  30. class UpdateAgentRequest(BaseModel):
  31. config: Dict[str, Any]
  32. changelog: str = ""
  33. class RunRequest(BaseModel):
  34. input: str = Field(..., max_length=102400) # 100KB max
  35. parameters: Dict[str, Any] = Field(default_factory=dict)
  36. context: Dict[str, Any] = Field(default_factory=dict)
  37. class RollbackRequest(BaseModel):
  38. target_version: int
  39. # ── CRUD Endpoints ──
  40. @router.post("", status_code=201)
  41. async def create_agent(
  42. req: CreateAgentRequest,
  43. tenant: TenantContext = Depends(get_tenant),
  44. db: Database = Depends(get_database),
  45. ):
  46. """Create a new agent. Auto-compiles config via lambdagent."""
  47. agent_id = gen_id("ag_")
  48. config_json = json.dumps(req.config, ensure_ascii=False)
  49. config_hash = hashlib.sha256(config_json.encode()).hexdigest()
  50. # Validate config by compiling (fail fast)
  51. try:
  52. _compile_agent(req.config)
  53. except Exception as e:
  54. raise HTTPException(400, {"error": {"code": "INVALID_CONFIG", "message": str(e)}})
  55. now = now_utc()
  56. db.execute(
  57. "INSERT INTO agents (id, tenant_id, name, description, current_version, tags, environment, status, created_at, updated_at) "
  58. "VALUES (?, ?, ?, ?, 1, ?, ?, 'active', ?, ?)",
  59. (agent_id, tenant.tenant_id, req.name, req.description,
  60. json.dumps(req.tags), req.environment, now, now)
  61. )
  62. db.execute(
  63. "INSERT INTO agent_versions (agent_id, version, config, config_hash, changelog, created_by, created_at) "
  64. "VALUES (?, 1, ?, ?, 'Initial version', ?, ?)",
  65. (agent_id, config_json, config_hash, tenant.user_id, now)
  66. )
  67. db.commit()
  68. return {
  69. "agent_id": agent_id,
  70. "version": 1,
  71. "created_at": now,
  72. "endpoint": f"/api/v1/agents/{agent_id}",
  73. }
  74. @router.get("")
  75. async def list_agents(
  76. tag: Optional[str] = None,
  77. tenant: TenantContext = Depends(get_tenant),
  78. db: Database = Depends(get_database),
  79. ):
  80. """List all agents for this tenant."""
  81. sql = "SELECT * FROM agents WHERE tenant_id = ? AND status = 'active'"
  82. params = [tenant.tenant_id]
  83. if tag:
  84. # SEC-08/SEC-12: Escape SQL LIKE wildcards
  85. safe_tag = tag.replace("%", "\\%").replace("_", "\\_")
  86. sql += " AND tags LIKE ? ESCAPE '\\'"
  87. params.append(f'%"{safe_tag}"%')
  88. sql += " ORDER BY updated_at DESC"
  89. agents = db.fetchall(sql, tuple(params))
  90. for a in agents:
  91. a["tags"] = json.loads(a.get("tags", "[]"))
  92. return {"agents": agents, "count": len(agents)}
  93. @router.get("/{agent_id}")
  94. async def get_agent(
  95. agent_id: str,
  96. tenant: TenantContext = Depends(get_tenant),
  97. db: Database = Depends(get_database),
  98. ):
  99. """Get agent details including current version config."""
  100. agent = db.fetchone(
  101. "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
  102. (agent_id, tenant.tenant_id)
  103. )
  104. if not agent:
  105. raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND", "message": f"Agent {agent_id} not found"}})
  106. version = db.fetchone(
  107. "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
  108. (agent_id, agent["current_version"])
  109. )
  110. agent["tags"] = json.loads(agent.get("tags", "[]"))
  111. agent["config"] = json.loads(version["config"]) if version else {}
  112. return agent
  113. @router.put("/{agent_id}")
  114. async def update_agent(
  115. agent_id: str,
  116. req: UpdateAgentRequest,
  117. tenant: TenantContext = Depends(get_tenant),
  118. db: Database = Depends(get_database),
  119. ):
  120. """Update agent config. Auto-increments version."""
  121. agent = db.fetchone(
  122. "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
  123. (agent_id, tenant.tenant_id)
  124. )
  125. if not agent:
  126. raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
  127. config_json = json.dumps(req.config, ensure_ascii=False)
  128. config_hash = hashlib.sha256(config_json.encode()).hexdigest()
  129. # Check if config actually changed
  130. last_version = db.fetchone(
  131. "SELECT config_hash FROM agent_versions WHERE agent_id = ? ORDER BY version DESC LIMIT 1",
  132. (agent_id,)
  133. )
  134. if last_version and last_version["config_hash"] == config_hash:
  135. return {"message": "Config unchanged, no new version created", "version": agent["current_version"]}
  136. # Validate
  137. try:
  138. _compile_agent(req.config)
  139. except Exception as e:
  140. raise HTTPException(400, {"error": {"code": "INVALID_CONFIG", "message": str(e)}})
  141. new_version = agent["current_version"] + 1
  142. now = now_utc()
  143. db.execute(
  144. "INSERT INTO agent_versions (agent_id, version, config, config_hash, changelog, created_by, created_at) "
  145. "VALUES (?, ?, ?, ?, ?, ?, ?)",
  146. (agent_id, new_version, config_json, config_hash, req.changelog, tenant.user_id, now)
  147. )
  148. db.execute(
  149. "UPDATE agents SET current_version = ?, updated_at = ? WHERE id = ?",
  150. (new_version, now, agent_id)
  151. )
  152. db.commit()
  153. return {"agent_id": agent_id, "version": new_version, "updated_at": now}
  154. @router.delete("/{agent_id}")
  155. async def delete_agent(
  156. agent_id: str,
  157. tenant: TenantContext = Depends(get_tenant),
  158. db: Database = Depends(get_database),
  159. ):
  160. """Soft delete agent."""
  161. db.execute(
  162. "UPDATE agents SET status = 'deleted', updated_at = ? WHERE id = ? AND tenant_id = ?",
  163. (now_utc(), agent_id, tenant.tenant_id)
  164. )
  165. db.commit()
  166. return {"message": "Agent deleted", "agent_id": agent_id}
  167. @router.post("/{agent_id}/rollback")
  168. async def rollback_agent(
  169. agent_id: str,
  170. req: RollbackRequest,
  171. tenant: TenantContext = Depends(get_tenant),
  172. db: Database = Depends(get_database),
  173. ):
  174. """Rollback to a previous version."""
  175. version = db.fetchone(
  176. "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
  177. (agent_id, req.target_version)
  178. )
  179. if not version:
  180. raise HTTPException(404, {"error": {"code": "VERSION_NOT_FOUND"}})
  181. db.execute(
  182. "UPDATE agents SET current_version = ?, updated_at = ? WHERE id = ? AND tenant_id = ?",
  183. (req.target_version, now_utc(), agent_id, tenant.tenant_id)
  184. )
  185. db.commit()
  186. return {"agent_id": agent_id, "version": req.target_version, "message": "Rolled back"}
  187. # ── Execution Endpoint ──
  188. @router.post("/{agent_id}/run")
  189. async def run_agent(
  190. agent_id: str,
  191. req: RunRequest,
  192. tenant: TenantContext = Depends(get_tenant),
  193. db: Database = Depends(get_database),
  194. ):
  195. """
  196. Synchronous agent execution.
  197. AgentPaaS.serve(request) =
  198. let yaml = Registry.load(agent_id) in
  199. let term = lambdagent.from_config(yaml) in
  200. let result = Runtime.reduce(term, input) in
  201. (result, trace)
  202. """
  203. # Load agent
  204. agent = db.fetchone(
  205. "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
  206. (agent_id, tenant.tenant_id)
  207. )
  208. if not agent:
  209. raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
  210. version_rec = db.fetchone(
  211. "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
  212. (agent_id, agent["current_version"])
  213. )
  214. config = json.loads(version_rec["config"])
  215. # Apply runtime parameter overrides
  216. for key, val in req.parameters.items():
  217. parts = key.split(".")
  218. target = config
  219. for p in parts[:-1]:
  220. target = target.setdefault(p, {})
  221. target[parts[-1]] = val
  222. # Create run record
  223. run_id = gen_id("run_")
  224. now = now_utc()
  225. db.execute(
  226. "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, status, created_at) "
  227. "VALUES (?, ?, ?, ?, ?, 'running', ?)",
  228. (run_id, agent_id, agent["current_version"], tenant.tenant_id, req.input, now)
  229. )
  230. db.commit()
  231. # Execute via lambdagent
  232. t0 = time.time()
  233. try:
  234. result, trace_info = _execute_agent(config, req.input)
  235. duration_ms = int((time.time() - t0) * 1000)
  236. db.execute(
  237. "UPDATE runs SET status='completed', output=?, duration_ms=?, "
  238. "input_tokens=?, output_tokens=?, steps=?, completed_at=? WHERE id=?",
  239. (str(result), duration_ms,
  240. trace_info.get("input_tokens", 0), trace_info.get("output_tokens", 0),
  241. trace_info.get("steps", 0), now_utc(), run_id)
  242. )
  243. db.commit()
  244. return {
  245. "run_id": run_id,
  246. "status": "completed",
  247. "output": str(result),
  248. "usage": {
  249. "input_tokens": trace_info.get("input_tokens", 0),
  250. "output_tokens": trace_info.get("output_tokens", 0),
  251. "total_tokens": trace_info.get("total_tokens", 0),
  252. "steps": trace_info.get("steps", 0),
  253. "duration_ms": duration_ms,
  254. },
  255. }
  256. except Exception as e:
  257. duration_ms = int((time.time() - t0) * 1000)
  258. # SEC-04: Log full detail server-side, return sanitized error to client
  259. from agentpaas.observability.logging import logger
  260. logger.error("Agent execution failed: run=%s agent=%s error=%s", run_id, agent_id, str(e), exc_info=True)
  261. db.execute(
  262. "UPDATE runs SET status='failed', error=?, duration_ms=?, completed_at=? WHERE id=?",
  263. (json.dumps({"code": type(e).__name__}), duration_ms, now_utc(), run_id)
  264. )
  265. db.commit()
  266. raise HTTPException(500, {"error": {"code": "EXECUTION_ERROR", "message": "Agent execution failed", "run_id": run_id}})
  267. # ── Streaming Execution (SSE) ──
  268. @router.post("/{agent_id}/run/stream")
  269. async def run_agent_stream(
  270. agent_id: str,
  271. req: RunRequest,
  272. tenant: TenantContext = Depends(get_tenant),
  273. db: Database = Depends(get_database),
  274. ):
  275. """
  276. SSE stream agent execution — emits step events in real time.
  277. Events:
  278. event: think — agent's reasoning for this step
  279. event: tool_call — tool invocation (name + input)
  280. event: tool_result — tool output
  281. event: error — tool error
  282. event: answer — final answer
  283. event: done — execution complete with usage stats
  284. """
  285. agent = db.fetchone(
  286. "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
  287. (agent_id, tenant.tenant_id)
  288. )
  289. if not agent:
  290. raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
  291. version_rec = db.fetchone(
  292. "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
  293. (agent_id, agent["current_version"])
  294. )
  295. config = json.loads(version_rec["config"])
  296. for key, val in req.parameters.items():
  297. parts = key.split(".")
  298. target = config
  299. for p in parts[:-1]:
  300. target = target.setdefault(p, {})
  301. target[parts[-1]] = val
  302. import queue
  303. event_queue = queue.Queue()
  304. def generate():
  305. import threading
  306. def _run():
  307. try:
  308. result, trace_info = _execute_agent(config, req.input, on_step=event_queue.put)
  309. event_queue.put({"event": "done", "data": {
  310. "status": "completed", "output": str(result),
  311. "steps": trace_info.get("steps", 0),
  312. "total_tokens": trace_info.get("total_tokens", 0),
  313. }})
  314. except Exception as e:
  315. event_queue.put({"event": "error", "data": {"message": str(e)}})
  316. event_queue.put({"event": "done", "data": {"status": "failed"}})
  317. event_queue.put(None) # sentinel
  318. threading.Thread(target=_run, daemon=True).start()
  319. while True:
  320. item = event_queue.get()
  321. if item is None:
  322. break
  323. evt_type = item.get("event", "message")
  324. data = json.dumps(item.get("data", item), ensure_ascii=False)
  325. yield f"event: {evt_type}\ndata: {data}\n\n"
  326. return StreamingResponse(generate(), media_type="text/event-stream",
  327. headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
  328. # ── Agent Versions ──
  329. @router.get("/{agent_id}/versions")
  330. async def list_versions(
  331. agent_id: str,
  332. tenant: TenantContext = Depends(get_tenant),
  333. db: Database = Depends(get_database),
  334. ):
  335. """List all versions of an agent."""
  336. versions = db.fetchall(
  337. "SELECT v.*, a.current_version FROM agent_versions v "
  338. "JOIN agents a ON v.agent_id = a.id "
  339. "WHERE v.agent_id = ? AND a.tenant_id = ? ORDER BY v.version DESC",
  340. (agent_id, tenant.tenant_id)
  341. )
  342. for v in versions:
  343. v["is_current"] = v["version"] == v.pop("current_version", None)
  344. return {"versions": versions}
  345. # ── Record-Only Endpoint (for external execution backends like Claude Code CLI) ──
  346. class RecordRunRequest(BaseModel):
  347. """记录一次外部执行结果(不触发 lambdagent 执行)"""
  348. input: str
  349. output: str
  350. status: str = "completed"
  351. duration_ms: int = 0
  352. steps: int = 0
  353. source: str = "external"
  354. @router.post("/{agent_id}/runs/record", status_code=201)
  355. async def record_run(
  356. agent_id: str,
  357. req: RecordRunRequest,
  358. tenant: TenantContext = Depends(get_tenant),
  359. db: Database = Depends(get_database),
  360. ):
  361. """
  362. Record an externally-executed run (e.g., from Claude Code CLI).
  363. Does NOT trigger lambdagent execution — only writes to the runs table.
  364. """
  365. agent = db.fetchone(
  366. "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
  367. (agent_id, tenant.tenant_id)
  368. )
  369. if not agent:
  370. raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
  371. run_id = gen_id("run_")
  372. now = now_utc()
  373. db.execute(
  374. "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, output, "
  375. "status, duration_ms, steps, created_at, completed_at) "
  376. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
  377. (run_id, agent_id, agent["current_version"], tenant.tenant_id,
  378. req.input, req.output, req.status, req.duration_ms, req.steps, now, now)
  379. )
  380. db.commit()
  381. return {
  382. "run_id": run_id,
  383. "status": req.status,
  384. "source": req.source,
  385. "message": "Run recorded (external execution)",
  386. }
  387. # ── Runs History ──
  388. @router.get("/{agent_id}/runs")
  389. async def list_runs(
  390. agent_id: str,
  391. limit: int = 20,
  392. tenant: TenantContext = Depends(get_tenant),
  393. db: Database = Depends(get_database),
  394. ):
  395. """List recent runs for an agent."""
  396. runs = db.fetchall(
  397. "SELECT * FROM runs WHERE agent_id = ? AND tenant_id = ? ORDER BY created_at DESC LIMIT ?",
  398. (agent_id, tenant.tenant_id, limit)
  399. )
  400. return {"runs": runs}
  401. # ── Internal helpers ──
  402. def _compile_agent(config: dict):
  403. """Compile agent config via lambdagent. Raises on invalid config."""
  404. import tempfile, yaml, os
  405. with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
  406. yaml.dump(config, f, allow_unicode=True)
  407. tmp_path = f.name
  408. try:
  409. from lambdagent.fromconfig import from_config
  410. return from_config(tmp_path)
  411. finally:
  412. os.unlink(tmp_path)
  413. def _execute_agent(config: dict, input_text: str, on_step=None):
  414. """Execute agent via lambdagent. Returns (result, trace_info).
  415. Args:
  416. on_step: Optional callback for streaming. Receives StepEvent dicts
  417. from ReActEngine with keys: event, data.
  418. """
  419. import tempfile, yaml, os
  420. with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
  421. yaml.dump(config, f, allow_unicode=True)
  422. tmp_path = f.name
  423. try:
  424. from lambdagent.fromconfig import from_config
  425. from lambdagent.core import Context
  426. # Wire on_step callback into the compiled term's ReActEngine
  427. overrides = {}
  428. if on_step:
  429. def _step_adapter(step_event):
  430. """Convert StepEvent dataclass to SSE dict for the queue."""
  431. on_step({
  432. "event": step_event.type,
  433. "data": {
  434. "step": step_event.step,
  435. "content": step_event.content,
  436. "tool": step_event.tool,
  437. "duration_ms": step_event.duration_ms,
  438. },
  439. })
  440. overrides["on_step"] = _step_adapter
  441. # Bridge on_chunk for ClaudeLam streaming (provider: claude-code)
  442. def _chunk_adapter(text):
  443. """Push ClaudeLam streaming chunks as SSE think_chunk events."""
  444. on_step({
  445. "event": "think_chunk",
  446. "data": {"content": text},
  447. })
  448. overrides["on_chunk"] = _chunk_adapter
  449. term = from_config(tmp_path, **overrides)
  450. ctx = Context()
  451. result = term.apply(input_text, ctx)
  452. # Extract trace info
  453. trace_info = {
  454. "steps": len(ctx.trace),
  455. "input_tokens": sum(getattr(e, 'tokens_used', 0) for e in ctx.trace),
  456. "output_tokens": 0,
  457. "total_tokens": sum(getattr(e, 'tokens_used', 0) for e in ctx.trace),
  458. }
  459. return result, trace_info
  460. finally:
  461. os.unlink(tmp_path)