Coverage for app / routers / agent.py: 81%
295 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1import asyncio
2import json
3import time
4from typing import Any, AsyncIterator, Literal, NoReturn
6from fastapi import APIRouter, Depends, HTTPException
7from fastapi.responses import StreamingResponse
8from pydantic import BaseModel, Field
9from sqlalchemy.orm import Session
11from app.db.postgres.enums import InvocationEnum
12from app.dependency.base import get_db
13from app.inference import InferenceContext, InferenceEngineFactory, output_shape
14from app.inference.engines.graph_based import (
15 _checkpointer,
16 _store,
17 _stream_graph,
18 build_graph_plan,
19)
20from app.inference.rules import (
21 RuleBlock,
22 RulesEnforcer,
23 audit_done_frame,
24 block_payload,
25 stream_guard,
26)
27from app.models.spec import (
28 AgentGraphConfig,
29 ExecuteRequest,
30 ExecuteResponse,
31 KnowledgeBaseSpec,
32 RuleSpec,
33 SkillSpec,
34)
35from app.agents.factory import AgentFactory
36from app.services import executor, metering, model_errors
37from app.services.conversation import (
38 persist_execution,
39 persist_execution_error,
40 persist_llm_invocation,
41)
42from app.services.model_errors import ModelUnavailableError
43from app.util import safe_json
44from app.util.logger import get_logger
46logger = get_logger(__name__)
48router = APIRouter(prefix="/agents", tags=["agents"])
51# ---------------------------------------------------------------------------
52# SSE helper
53# ---------------------------------------------------------------------------
56def _sse(data: dict) -> str:
57 return f"data: {safe_json.dumps(data)}\n\n"
60# Seconds of stream silence before an SSE comment is emitted. System nodes
61# (planning / synthesis / evaluator) run non-streaming structured-output LLM
62# calls that produce no frames for minutes; without a keepalive, upstream
63# read timeouts (svc-core httpx, proxies) abort the stream mid-execution.
64_KEEPALIVE_INTERVAL_S = 10.0
67async def _with_keepalive(
68 inner: AsyncIterator[str],
69 interval: float = _KEEPALIVE_INTERVAL_S,
70) -> AsyncIterator[str]:
71 """Yield frames from ``inner``, emitting an SSE comment during silence.
73 SSE comment lines (leading ``:``) are ignored by every consumer — they
74 exist purely to keep bytes flowing so intermediaries never see a silent
75 connection while a long non-streaming LLM call is in flight.
76 """
77 iterator = inner.__aiter__()
78 next_frame: asyncio.Task | None = None
79 try:
80 while True:
81 if next_frame is None:
82 next_frame = asyncio.ensure_future(iterator.__anext__())
83 try:
84 frame = await asyncio.wait_for(
85 asyncio.shield(next_frame), timeout=interval
86 )
87 except asyncio.TimeoutError:
88 yield ": keepalive\n\n"
89 continue
90 except StopAsyncIteration:
91 break
92 next_frame = None
93 yield frame
94 finally:
95 if next_frame is not None and not next_frame.done():
96 next_frame.cancel()
97 try:
98 await next_frame
99 except asyncio.CancelledError:
100 pass
101 except Exception:
102 pass
105# ---------------------------------------------------------------------------
106# Persistence wrapper for streaming executions
107# ---------------------------------------------------------------------------
110class _StreamOutcome:
111 """How a stream ended, read from the frames it sent."""
113 def __init__(self) -> None:
114 self.error: str | None = None
115 self.output: str | None = None
117 def observe(self, chunk: str) -> None:
118 if not chunk.startswith("data: "):
119 return
120 try:
121 data = json.loads(chunk[6:].rstrip("\n"))
122 except ValueError:
123 return
124 if not isinstance(data, dict):
125 return
126 if data.get("type") == "error":
127 self.error = str(data.get("message") or "Stream error")
128 elif data.get("type") == "done":
129 self.output = data.get("output") or None
132async def _with_persistence(
133 inner: AsyncIterator[str],
134 db: Session,
135 request: Any,
136 started_at: float,
137) -> AsyncIterator[str]:
138 """Wrap a streaming engine generator to persist an LLMInvocation record
139 once the stream completes.
141 The row takes its calls — and so its tokens and cost — from the usage
142 meter, which also covers a run that paused for a person and so never
143 sent a ``done`` frame. The ``done`` frame's counts are the fallback for
144 a stream the meter did not see. Error frames set invocation status to
145 ``error`` without suppressing the frame.
147 Persistence is called synchronously at end-of-stream. Sharing a
148 SQLAlchemy session across threads would race with FastAPI's own
149 contextmanager_in_threadpool cleanup and cause IllegalStateChangeError;
150 the sync call is safe here because FastAPI only closes the session after
151 this generator is fully exhausted.
152 """
153 prompt_tokens = 0
154 completion_tokens = 0
155 estimated_cost_usd: float | None = None
156 had_error = False
157 error_detail = ""
159 try:
160 async for chunk in inner:
161 # The done frame's usage becomes the meter's: every call the
162 # stream made, priced per model — see services/metering.py.
163 chunk = metering.meter_frame(chunk)
164 yield chunk
165 if chunk.startswith("data: "):
166 try:
167 data = json.loads(chunk[6:].rstrip("\n"))
168 event_type = data.get("type")
169 if event_type == "done":
170 usage = data.get("usage", {})
171 prompt_tokens = usage.get("prompt_tokens", 0)
172 completion_tokens = usage.get("completion_tokens", 0)
173 estimated_cost_usd = usage.get("estimated_cost_usd")
174 elif event_type == "error":
175 had_error = True
176 error_detail = data.get("message", "Stream error")
177 except Exception:
178 pass
179 except Exception as exc:
180 had_error = True
181 error_detail = str(exc)
182 raise
183 finally:
184 try:
185 if had_error:
186 persist_execution_error(db, request, started_at, error_detail)
187 else:
188 _persist_usage: dict = {
189 "prompt_tokens": prompt_tokens,
190 "completion_tokens": completion_tokens,
191 "total_tokens": prompt_tokens + completion_tokens,
192 }
193 if estimated_cost_usd is not None:
194 _persist_usage["estimated_cost_usd"] = estimated_cost_usd
195 persist_execution(
196 db,
197 request,
198 ExecuteResponse(output="", usage=_persist_usage),
199 started_at,
200 )
201 except Exception:
202 logger.exception("[stream] Failed to persist LLMInvocation after stream")
205# ---------------------------------------------------------------------------
206# Response models
207# ---------------------------------------------------------------------------
210class GraphInfo(BaseModel):
211 name: str
212 description: str
215class GraphListResponse(BaseModel):
216 patterns: list[GraphInfo]
219class AgentInfo(BaseModel):
220 role: str
221 description: str
224class AgentListResponse(BaseModel):
225 agents: list[AgentInfo]
228# ---------------------------------------------------------------------------
229# Information endpoints
230# ---------------------------------------------------------------------------
233@router.get("/graphs", response_model=GraphListResponse)
234async def list_graphs() -> GraphListResponse:
235 """Return the built-in graph patterns available for execution."""
236 return GraphListResponse(
237 patterns=[
238 GraphInfo(name=name, description=desc)
239 for name, desc in AgentFactory.BUILTIN_GRAPHS.items()
240 ]
241 )
244@router.get("/agents", response_model=AgentListResponse)
245async def list_agents() -> AgentListResponse:
246 """Return all agent roles available in the system."""
247 return AgentListResponse(
248 agents=[
249 AgentInfo(role=role.value, description=role.description)
250 for role in AgentFactory.ROLE_CLASS_MAP
251 ]
252 )
255# ---------------------------------------------------------------------------
256# Helper request models
257# ---------------------------------------------------------------------------
260class GraphExecutionRequest(BaseModel):
261 config: AgentGraphConfig
262 input: str
263 user_id: str
264 session_id: str | None = None
265 conversation_id: str | None = None
266 external_agent_id: str | None = None
267 rules: list[RuleSpec] = Field(default_factory=list)
270# ---------------------------------------------------------------------------
271# Streaming execution
272# ---------------------------------------------------------------------------
275@router.post("/execute/stream")
276async def execute_stream(
277 request: ExecuteRequest,
278 db: Session = Depends(get_db),
279) -> StreamingResponse:
280 """
281 Stream an execution result token-by-token via Server-Sent Events.
283 All execution types (model, agent, skill, graph, pipeline) are handled by
284 the inference engine for the requested type. The SSE event
285 format is uniform across all types:
287 data: {"type": "graph_plan", "stages": [...]}
288 data: {"type": "status", "message": "..."}
289 data: {"type": "token", "token": "..."}
290 data: {"type": "token_reset", "worker_agent_slug": "..."}
291 data: {"type": "tool_call", ...}
292 data: {"type": "node_start", ...}
293 data: {"type": "node_end", ...}
294 data: {"type": "citations", "citations": [...]}
295 data: {"type": "done", "output": "...", "usage": {...}}
296 data: {"type": "error", "message": "..."}
297 """
298 engine = InferenceEngineFactory.create(
299 request.type,
300 db=db,
301 rules_list=request.rules,
302 )
303 ctx = InferenceContext(request=request, db=db)
304 started = time.time()
306 return StreamingResponse(
307 _with_keepalive(
308 _with_persistence(
309 engine.infer_stream(ctx),
310 db=db,
311 request=request,
312 started_at=started,
313 )
314 ),
315 media_type="text/event-stream",
316 )
319# ---------------------------------------------------------------------------
320# HITL resume
321# ---------------------------------------------------------------------------
324class HitlResumeRequest(BaseModel):
325 """Resume a HITL-interrupted streaming graph execution.
327 ``thread_id`` identifies the saved checkpoint in the module-level
328 MemorySaver so LangGraph resumes from the exact interrupt point.
329 """
331 thread_id: str
332 # "agent" is a plain agent's chat turn — the type svc-core resumes with
333 # whenever the agent has no skill graph.
334 type: Literal["agent", "skill", "graph"]
335 spec: dict[str, Any]
336 user_id: str
337 session_id: str | None = None
338 approved: bool = True
339 feedback: str = ""
340 answers: dict[str, Any] | None = Field(
341 default=None,
342 description=(
343 "Answers to a clarification_request interrupt, keyed by question id. "
344 "Each value is a list, so single- and multi-select share one shape."
345 ),
346 )
347 rules: list[RuleSpec] = Field(default_factory=list)
348 # The conversation the resumed segment's trace row belongs to, as the
349 # first leg's execute request carried it.
350 conversation_id: str | None = None
353def _resumed_model(request: HitlResumeRequest) -> tuple[str | None, str | None]:
354 """The model a resumed run's spec names: an agent's; a skill names none."""
355 if request.type != "agent":
356 return None, None
357 model = request.spec.get("model") or {}
358 return model.get("provider") or None, model.get("model") or None
361def _persist_resume(
362 db: Session,
363 request: HitlResumeRequest,
364 started_at: float,
365 error: str | None,
366 output: str | None,
367) -> None:
368 """Trace a resumed segment like any other invocation.
370 Each resume is its own call to svc-ai, with its own model calls; without
371 a row of its own, everything a run did after a person answered was
372 missing from the traces.
373 """
374 provider, model = _resumed_model(request)
375 persist_llm_invocation(
376 db,
377 purpose=request.type,
378 provider=provider,
379 model=model,
380 user_id=request.user_id,
381 conversation_id=request.conversation_id,
382 latency_ms=int((time.time() - started_at) * 1000),
383 status=InvocationEnum.Status.error if error else InvocationEnum.Status.success,
384 error_detail=error,
385 request_config={"resumed_thread_id": request.thread_id},
386 output_preview=output,
387 )
390def _rebuild_paused_graph(request: HitlResumeRequest, db: Session) -> tuple[Any, str]:
391 """The graph a paused agent or skill run was built as, built again.
393 Through the same engine that built the paused run, from the same spec, so
394 the resumed graph has the same nodes — the ``__clarify__`` node when the
395 spec checks scope, the same tools, the same model override. Rebuilding by
396 hand here is how the two drifted: a plain agent could not be resumed at
397 all, and a skill resumed without the settings its spec carried.
398 """
399 from app.inference.context import InferenceContext
400 from app.inference.engines._factory import InferenceEngineFactory
401 from app.models.spec import AgentConfig, ExecuteRequest
403 spec: AgentConfig | SkillSpec = (
404 AgentConfig.model_validate(request.spec)
405 if request.type == "agent"
406 else SkillSpec.model_validate(request.spec)
407 )
408 engine = InferenceEngineFactory.create(request.type, db=db)
409 ctx = InferenceContext(
410 request=ExecuteRequest(
411 type=request.type,
412 spec=spec,
413 input="",
414 user_id=request.user_id,
415 session_id=request.thread_id,
416 ),
417 db=db,
418 )
419 builder, _, _ = engine._build_builder(ctx) # type: ignore[attr-defined]
420 end_node = next(iter(builder.end_nodes), getattr(engine, "_default_end_node", ""))
421 return builder, end_node
424@router.post("/execute/stream/resume")
425async def execute_stream_resume(
426 request: HitlResumeRequest,
427 db: Session = Depends(get_db),
428) -> StreamingResponse:
429 """
430 Resume a HITL-interrupted graph execution and stream the remainder.
432 The client sends this after receiving a ``hitl_interrupt`` SSE frame.
433 The graph is rebuilt from the same spec, then resumed via
434 ``Command(resume={approved, feedback})`` against the saved checkpoint.
435 SSE frames are identical to the initial stream, ending with a ``done`` frame.
436 """
437 from langgraph.types import Command
439 # One resume payload serves both interrupt kinds: the approval node reads
440 # approved/feedback, ask_user reads answers. Sending all three keeps the
441 # resume endpoint agnostic about which kind of interrupt it is resuming.
442 resume_command = Command(
443 resume={
444 "approved": request.approved,
445 "feedback": request.feedback,
446 "answers": request.answers or {},
447 }
448 )
449 thread_id = request.thread_id
451 async def _generate() -> AsyncIterator[str]:
452 try:
453 if request.type in ("agent", "skill"):
454 builder, end_node = _rebuild_paused_graph(request, db)
455 builder.store = _store
456 builder.memory_redaction = _resume_memory_redaction()
457 builder.withholding = enforcer.may_withhold
458 compiled = builder.build(checkpointer=_checkpointer)
459 async for chunk in _stream_graph(
460 compiled,
461 resume_command,
462 set(builder.nodes.keys()),
463 end_node,
464 thread_id=thread_id,
465 config=builder.run_config(thread_id),
466 skill_interface=getattr(builder, "skill_interface", None),
467 graph_plan=build_graph_plan(builder),
468 answer_shape=output_shape.of_builder(builder),
469 ):
470 yield chunk
472 elif request.type == "graph":
473 spec_g = AgentGraphConfig.model_validate(request.spec)
474 if spec_g.name == "analysis":
475 builder_g = AgentFactory.create_analysis_graph()
476 elif spec_g.name == "rag":
477 builder_g = AgentFactory.create_retrieval_augmented_graph()
478 else:
479 agents_g = AgentFactory.agents_from_spec(spec_g)
480 builder_g = AgentFactory.create_custom_graph(
481 agents=agents_g,
482 edges=spec_g.edges,
483 start_node=spec_g.start_agent,
484 end_nodes=spec_g.end_agents,
485 )
486 builder_g.store = _store
487 builder_g.memory_redaction = _resume_memory_redaction()
488 builder_g.withholding = enforcer.may_withhold
489 compiled_g = builder_g.build(checkpointer=_checkpointer)
490 node_ids_g = set(builder_g.nodes.keys())
491 end_node_g = (
492 spec_g.end_agents[0]
493 if spec_g.end_agents
494 else (
495 next(iter(builder_g.end_nodes)) if builder_g.end_nodes else ""
496 )
497 )
498 async for chunk in _stream_graph(
499 compiled_g,
500 resume_command,
501 node_ids_g,
502 end_node_g,
503 thread_id=thread_id,
504 config=builder_g.run_config(thread_id),
505 graph_plan=build_graph_plan(builder_g),
506 ):
507 yield chunk
509 else:
510 yield _sse(
511 {
512 "type": "error",
513 "message": f"Unsupported type for HITL resume: {request.type!r}",
514 }
515 )
517 except ModelUnavailableError as exc:
518 yield _sse({"type": "error", **exc.payload()})
519 except Exception:
520 logger.exception("Error in HITL resume stream")
521 yield _sse({"type": "error", "message": "An internal error has occurred."})
523 # The resume path bypasses the inference engines (it replays a saved
524 # LangGraph checkpoint), so audit rules are applied to the terminal
525 # ``done`` frame here. Policy (input) rules already ran when the
526 # original execution started.
527 enforcer = RulesEnforcer(request.rules)
528 rule_ctx = {
529 "user_id": str(request.user_id or ""),
530 "execution_type": request.type,
531 }
532 # The resumed run streams like the first leg did, so a redact_pii rule
533 # redacts it the same way — tokens, trace and the pause it may reach.
534 guard = stream_guard(enforcer, rule_ctx)
536 def _resume_memory_redaction() -> Any:
537 """What memory redacts on the resumed leg, as the first leg did
538 (``graph_based._memory_redaction``)."""
539 from app.memory.service import Redaction
541 return Redaction(
542 stored=enforcer.output_redactor(rule_ctx),
543 recalled=enforcer.input_redactor(rule_ctx),
544 )
546 started = time.monotonic()
547 trace_started = time.time()
549 async def _audited() -> AsyncIterator[str]:
550 fired: list[dict] = []
551 outcome = _StreamOutcome()
552 try:
553 async for raw in _generate():
554 for frame in guard.process(raw) if guard else (raw,):
555 frame, events = audit_done_frame(
556 enforcer, frame, rule_ctx, prior_events=fired, started=started
557 )
558 fired.extend(events)
559 outcome.observe(frame)
560 yield metering.meter_frame(frame)
561 if guard:
562 for frame in guard.flush():
563 outcome.observe(frame)
564 yield metering.meter_frame(frame)
565 finally:
566 _persist_resume(
567 db,
568 request,
569 trace_started,
570 outcome.error,
571 # A run a withhold rule governs keeps no preview of its answer.
572 None if enforcer.may_withhold else outcome.output,
573 )
575 return StreamingResponse(
576 _with_keepalive(_audited()), media_type="text/event-stream"
577 )
580@router.delete("/execute/threads/{thread_id}", status_code=204)
581async def discard_paused_thread(thread_id: str) -> None:
582 """Drop a paused run's checkpoint without resuming it.
584 Checkpoints are kept in-process so a paused run can resume; one whose
585 caller cancelled it, or gave up waiting, would otherwise stay for good.
586 """
587 from app.inference.engines.graph_based import _evict_checkpoint_thread
589 await _evict_checkpoint_thread(thread_id)
592# ---------------------------------------------------------------------------
593# Batch execution endpoints
594# ---------------------------------------------------------------------------
597#: What a run stopped at its caller's time limit is recorded as.
598TIME_LIMIT_ERROR = "Stopped at the caller's time limit"
601def _failed(
602 db: Session, exec_req: ExecuteRequest, started: float, error: Exception
603) -> NoReturn:
604 """A run that failed for no reason the caller can act on: logged here —
605 svc-core reads only that it failed — recorded, and answered 500."""
606 logger.exception("[execute] %s run failed: %s", exec_req.type, type(error).__name__)
607 persist_execution_error(db, exec_req, started, str(error))
608 raise HTTPException(status_code=500, detail=str(error))
611async def execute_and_persist(exec_req: ExecuteRequest, db: Session) -> ExecuteResponse:
612 """Run ``exec_req`` through the executor and persist the outcome either way.
614 Every batch execution endpoint below (and ``routers/execute.py``) differs
615 only in how it builds the ``ExecuteRequest`` — running it, persisting the
616 LLMInvocation, and mapping exceptions to HTTP status codes is identical,
617 so it lives here once: ``RuleBlock`` → 403, ``ValueError`` → 400 (bad
618 spec), a fatal model error → 502 with what to fix (``main.py``'s handler:
619 no route on this backend, credentials, model access, quota, the spending
620 ceiling), past the caller's ``time_limit_s`` → 504, anything else → 500.
622 A run past its time limit is cancelled, not left running: the caller has
623 stopped waiting, and the 504 carries what the run spent (``X-LLM-Usage``)
624 so the caller's ledger has it.
625 """
626 started = time.time()
627 limit = asyncio.timeout(exec_req.time_limit_s)
628 try:
629 async with limit:
630 response = await executor.execute(exec_req, db)
631 except TimeoutError as e:
632 if not limit.expired():
633 # A socket's own timeout inside the run, not the caller's limit.
634 _failed(db, exec_req, started, e)
635 logger.warning(
636 "[execute] %s run stopped at its time limit of %.0fs",
637 exec_req.type,
638 exec_req.time_limit_s or 0,
639 )
640 persist_execution_error(db, exec_req, started, TIME_LIMIT_ERROR)
641 raise HTTPException(status_code=504, detail=TIME_LIMIT_ERROR)
642 except ModelUnavailableError as e:
643 # Re-raised for main.py's handler, which answers with the actionable
644 # message and code. Caught by the catch-all below, it became a 500
645 # carrying the exception's own text.
646 persist_execution_error(db, exec_req, started, model_errors.describe(e))
647 raise
648 except RuleBlock as e:
649 persist_execution_error(db, exec_req, started, str(e))
650 raise HTTPException(
651 status_code=403,
652 detail=block_payload(e),
653 )
654 except ValueError as e:
655 persist_execution_error(db, exec_req, started, str(e))
656 raise HTTPException(status_code=400, detail=str(e))
657 except Exception as e: # pragma: no cover
658 _failed(db, exec_req, started, e)
659 # Every call the execution made, priced per model — including a run that
660 # paused, whose engine response carries no usage of its own.
661 response = response.model_copy(
662 update={"usage": metering.merge_into_usage(response.usage)}
663 )
664 conversation_id = persist_execution(db, exec_req, response, started)
665 if conversation_id:
666 response.conversation_id = str(conversation_id)
667 return response
670@router.post("/execute", response_model=ExecuteResponse)
671async def execute_agent(
672 request: ExecuteRequest,
673 db: Session = Depends(get_db),
674) -> ExecuteResponse:
675 """Generic entrypoint used by other components (models, agents, graphs, pipelines)."""
676 return await execute_and_persist(request, db)
679@router.post("/graph", response_model=ExecuteResponse)
680async def execute_graph(
681 request: GraphExecutionRequest,
682 db: Session = Depends(get_db),
683) -> ExecuteResponse:
684 """Run a graph configuration and initial input."""
685 exec_req = ExecuteRequest(
686 type="graph",
687 spec=request.config,
688 input=request.input,
689 user_id=request.user_id,
690 session_id=request.session_id,
691 conversation_id=request.conversation_id,
692 external_agent_id=request.external_agent_id,
693 rules=request.rules,
694 )
695 return await execute_and_persist(exec_req, db)
698# ---------------------------------------------------------------------------
699# Shortcut endpoints for common built-in graph patterns
700# ---------------------------------------------------------------------------
703class SimpleExecutionRequest(BaseModel):
704 input: str
705 user_id: str
706 session_id: str | None = None
707 conversation_id: str | None = None
708 external_agent_id: str | None = None
709 rules: list[RuleSpec] = Field(default_factory=list)
712@router.post("/analysis", response_model=ExecuteResponse)
713async def run_analysis(
714 request: SimpleExecutionRequest,
715 db: Session = Depends(get_db),
716) -> ExecuteResponse:
717 """Execute the standard 'analysis' graph (planner → analyzer → validator)."""
718 exec_req = ExecuteRequest(
719 type="graph",
720 spec=AgentGraphConfig(name="analysis", start_agent="planner"),
721 input=request.input,
722 user_id=request.user_id,
723 session_id=request.session_id,
724 conversation_id=request.conversation_id,
725 external_agent_id=request.external_agent_id,
726 rules=request.rules,
727 )
728 return await execute_and_persist(exec_req, db)
731@router.post("/rag", response_model=ExecuteResponse)
732async def run_rag(
733 request: SimpleExecutionRequest,
734 db: Session = Depends(get_db),
735) -> ExecuteResponse:
736 """Execute the built-in RAG pipeline graph."""
737 exec_req = ExecuteRequest(
738 type="graph",
739 spec=AgentGraphConfig(name="rag", start_agent="planner"),
740 input=request.input,
741 user_id=request.user_id,
742 session_id=request.session_id,
743 conversation_id=request.conversation_id,
744 external_agent_id=request.external_agent_id,
745 rules=request.rules,
746 )
747 return await execute_and_persist(exec_req, db)
750# ---------------------------------------------------------------------------
751# Skill execution
752# ---------------------------------------------------------------------------
755class SkillExecutionRequest(BaseModel):
756 skill_id: str
757 name: str = ""
758 graph_definition: dict[str, Any]
759 knowledge_bases: list[KnowledgeBaseSpec] = Field(default_factory=list)
760 input: str
761 user_id: str
762 session_id: str | None = None
763 conversation_id: str | None = None
764 external_agent_id: str | None = None
765 rules: list[RuleSpec] = Field(default_factory=list)
768@router.post("/skill", response_model=ExecuteResponse)
769async def execute_skill(
770 request: SkillExecutionRequest,
771 db: Session = Depends(get_db),
772) -> ExecuteResponse:
773 """Execute a stored Skill as a dynamic multi-agent LangGraph."""
774 exec_req = ExecuteRequest(
775 type="skill",
776 spec=SkillSpec(
777 skill_id=request.skill_id,
778 name=request.name,
779 graph_definition=request.graph_definition,
780 knowledge_bases=request.knowledge_bases,
781 ),
782 input=request.input,
783 user_id=request.user_id,
784 session_id=request.session_id,
785 conversation_id=request.conversation_id,
786 external_agent_id=request.external_agent_id,
787 rules=request.rules,
788 )
789 return await execute_and_persist(exec_req, db)