Coverage for app / agents / factory.py: 92%
255 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
1"""
2AgentFactory — creates agent instances and pre-built graph patterns.
3"""
5from __future__ import annotations
7from collections.abc import Callable
8from typing import TYPE_CHECKING, Any, Optional
10from langchain_core.language_models import BaseLanguageModel
12from app.agents.base import WorkerAgent, reply_text
14from app.agents.enums import AgentRole
15from app.agents.planner import PlannerAgent
16from app.agents.analyzer import AnalyzerAgent
17from app.agents.validator import ValidatorAgent
18from app.agents.researcher import ResearchAgent
19from app.agents.router import RouterAgent
20from app.agents.reviewer import ReviewerAgent
21from app.agents.loop import LoopAgent
22from app.agents.graph import AgentGraphBuilder, GraphState
23from app.util.logger import get_logger
25if TYPE_CHECKING:
26 # Not at runtime: app.models.spec imports app.agents.enums, which loads
27 # this package, so a module-level import here is a cycle whenever
28 # app.models.spec is imported first (as main.py does) and svc-ai fails
29 # to start.
30 from app.models.spec import ModelConfig
33def _names_model(model_cfg: dict[str, Any]) -> bool:
34 """Whether a node's merged config chooses its own model: a pin, or a
35 custom definition that names one. Both halves, because a model name
36 means nothing without the provider that serves it."""
37 return bool(model_cfg.get("provider")) and bool(model_cfg.get("model"))
40logger = get_logger(__name__)
42# ---------------------------------------------------------------------------
43# Simple generic worker (for one-off / unnamed tasks)
44# ---------------------------------------------------------------------------
47class SimpleWorkerAgent(WorkerAgent):
48 """Basic worker agent for straightforward, generic task execution."""
50 async def execute(self, input_data: Any) -> Any:
51 # Sizes, never the words (``app/util/logger.py``).
52 logger.info("Executing SimpleWorkerAgent input_chars=%d", len(str(input_data)))
53 messages = self.build_messages(str(input_data))
54 logger.info(
55 "Invoking LLM for SimpleWorkerAgent: model=%s, tools=%s",
56 self.llm.name if self.llm else "none",
57 [t.name for t in self.tools] if self.tools else "none",
58 )
59 if self.tools:
60 # run_with_tools returns (content, new_messages); callers of execute
61 # only need the content string.
62 output, _ = await self.run_with_tools(messages)
63 return output
64 llm = self.resolve_llm()
65 response = await llm.ainvoke(messages)
67 content = reply_text(llm, response, self.name)
68 logger.info("SimpleWorkerAgent answered chars=%d", len(content or ""))
69 return content
72# ---------------------------------------------------------------------------
73# Factory
74# ---------------------------------------------------------------------------
77class AgentFactory:
78 """
79 Factory for creating individual agents and common graph patterns.
81 Graph patterns
82 --------------
83 ``create_analysis_graph`` Planner → Analyzer → Validator
84 ``create_retrieval_augmented_graph`` Same but Analyzer has a search tool
85 ``create_custom_graph`` Arbitrary agents/edges provided by caller
87 Dynamic construction from API spec
88 -----------------------------------
89 ``agents_from_spec(AgentGraphConfig)`` Instantiates all agents declared
90 in the spec, dispatching on AgentConfig.role.
91 """
93 # Registry of named built-in graph patterns. The executor's _run_graph
94 # matches on these names; keeping the list here ensures the router and
95 # executor stay in sync automatically.
96 BUILTIN_GRAPHS: dict[str, str] = {
97 "analysis": "Planner → Analyzer (calculate) → Validator pipeline",
98 "rag": "Retrieval-augmented workflow (Planner → Analyzer with web search + calculate → Validator)",
99 "custom": "Fully user-specified graph (agents + edges provided in spec)",
100 }
102 # Role → concrete class map used by from_config() and exposed to the router.
103 ROLE_CLASS_MAP: dict[AgentRole, type[WorkerAgent]] = {} # populated below
105 # ------------------------------------------------------------------
106 # Individual agent constructors
107 # ------------------------------------------------------------------
109 @staticmethod
110 def create_simple_agent(
111 name: str,
112 role: AgentRole = AgentRole.WORKER,
113 llm: Optional[BaseLanguageModel] = None,
114 system_prompt: str = "",
115 ) -> SimpleWorkerAgent:
116 from app.tools.registry import general_tools
118 return SimpleWorkerAgent(
119 name=name,
120 role=role,
121 llm=llm,
122 system_prompt=system_prompt,
123 tools=general_tools(),
124 )
126 @staticmethod
127 def create_planner(llm: Optional[BaseLanguageModel] = None) -> PlannerAgent:
128 from app.tools.registry import general_tools
130 return PlannerAgent(llm=llm, tools=general_tools())
132 @staticmethod
133 def create_analyzer(llm: Optional[BaseLanguageModel] = None) -> AnalyzerAgent:
134 from app.tools.registry import general_tools
136 return AnalyzerAgent(llm=llm, tools=general_tools())
138 @staticmethod
139 def create_validator(llm: Optional[BaseLanguageModel] = None) -> ValidatorAgent:
140 from app.tools.registry import general_tools
142 return ValidatorAgent(llm=llm, tools=general_tools())
144 @staticmethod
145 def create_researcher(llm: Optional[BaseLanguageModel] = None) -> ResearchAgent:
146 from app.tools.registry import general_tools
148 return ResearchAgent(llm=llm, tools=general_tools())
150 @staticmethod
151 def create_router(
152 candidates: list[str],
153 llm: Optional[BaseLanguageModel] = None,
154 ) -> RouterAgent:
155 return RouterAgent(candidates=candidates, llm=llm)
157 # ------------------------------------------------------------------
158 # Graph patterns
159 # ------------------------------------------------------------------
161 @staticmethod
162 def create_analysis_graph(
163 state_schema: type[GraphState] = GraphState,
164 ) -> AgentGraphBuilder:
165 """Standard Planner → Analyzer → Validator pipeline."""
166 builder = AgentGraphBuilder(state_schema=state_schema)
167 builder.add_agent("planner", AgentFactory.create_planner(), start=True)
168 builder.add_agent("analyzer", AgentFactory.create_analyzer())
169 builder.add_agent("validator", AgentFactory.create_validator(), end=True)
170 builder.add_edge("planner", "analyzer")
171 builder.add_edge("analyzer", "validator")
172 return builder
174 @staticmethod
175 def create_retrieval_augmented_graph(
176 state_schema: type[GraphState] = GraphState,
177 ) -> AgentGraphBuilder:
178 """RAG pipeline: Planner → Analyzer → Validator (all agents have general tools)."""
179 builder = AgentGraphBuilder(state_schema=state_schema)
180 builder.add_agent("planner", AgentFactory.create_planner(), start=True)
181 builder.add_agent("analyzer", AgentFactory.create_analyzer())
182 builder.add_agent("validator", AgentFactory.create_validator(), end=True)
183 builder.add_edge("planner", "analyzer")
184 builder.add_edge("analyzer", "validator")
185 return builder
187 @staticmethod
188 def create_custom_graph(
189 agents: dict[str, WorkerAgent],
190 edges: list[tuple[str, str]],
191 start_node: str,
192 end_nodes: list[str],
193 state_schema: type[GraphState] = GraphState,
194 ) -> AgentGraphBuilder:
195 """Build a graph from an arbitrary agent/edge configuration."""
196 builder = AgentGraphBuilder(state_schema=state_schema)
197 for node_id, agent in agents.items():
198 builder.add_agent(
199 node_id,
200 agent,
201 start=(node_id == start_node),
202 end=(node_id in end_nodes),
203 )
204 for from_node, to_node in edges:
205 builder.add_edge(from_node, to_node)
206 return builder
208 # ------------------------------------------------------------------
209 # Dynamic construction from API spec
210 # ------------------------------------------------------------------
212 @staticmethod
213 def agents_from_spec(spec: Any) -> dict[str, WorkerAgent]:
214 """
215 Instantiate agents declared in an AgentGraphConfig.
217 Dispatches on AgentConfig.role so the correct specialised class is
218 created. Falls back to SimpleWorkerAgent for unknown roles.
219 """
220 agents: dict[str, WorkerAgent] = {}
222 for node_id, agent_config in spec.agents.items():
223 agents[node_id] = AgentFactory.from_config(node_id, agent_config)
225 # Always ensure the start agent exists (default to PlannerAgent)
226 if spec.start_agent not in agents:
227 agents[spec.start_agent] = AgentFactory.create_planner()
229 return agents
231 @staticmethod
232 def from_config(node_id: str, config: Any) -> WorkerAgent:
233 """
234 Create the appropriate WorkerAgent subclass for a given AgentConfig.
236 Dispatches on config.role; falls back to SimpleWorkerAgent.
237 """
238 role: AgentRole = getattr(config, "role", AgentRole.WORKER)
239 cls = AgentFactory.ROLE_CLASS_MAP.get(role, SimpleWorkerAgent)
240 return cls.from_config(config, name=node_id)
242 @staticmethod
243 def from_definition(
244 node_id: str,
245 definition: Any,
246 config_overrides: dict[str, Any] | None = None,
247 extra_kwargs: dict[str, Any] | None = None,
248 *,
249 default_model: Callable[[], ModelConfig] | None = None,
250 llm: Any = None,
251 ) -> WorkerAgent:
252 """
253 Build a WorkerAgent from a WorkerAgentDefinition DB row (or dict).
255 Which model answers, first match wins:
257 1. ``llm`` — a model the caller already built (a chat's explicit model
258 override), used as given; nothing else is built.
259 2. The node's pin (``config_overrides`` provider + model), or a model
260 the definition itself names (a custom definition may; no built-in
261 does).
262 3. ``default_model()`` — the agent's model, or the deployment's
263 default for work with no agent. Called only when needed.
265 ``definition`` may be an ORM model instance or a plain dict with
266 the same keys. ``config_overrides`` are merged on top of the
267 definition's defaults; recognised non-model keys:
269 system_prompt — replaces the definition's prompt
270 tools_enabled — toggles the full general toolset on/off
271 mcp_servers — replaces the definition's MCP server list
272 input_schema — replaces the worker's typed input interface
273 output_schema — replaces the worker's typed output interface
274 (non-empty → the node returns a schema dict)
276 Every other key is merged into the model config (provider, model,
277 temperature, max_tokens, …).
279 This is the preferred construction path for skill graph execution —
280 it keeps graph_definitions lightweight (agent names only) while
281 still respecting per-node config overrides.
282 """
283 from app.services.llm import build_langchain_llm, deployment_default_model
284 from app.tools.registry import resolve_tool
285 from app.models.spec import ModelConfig, ToolConfig
287 # Support both ORM model and plain dict
288 if isinstance(definition, dict):
289 role = (
290 AgentRole(definition["role"])
291 if isinstance(definition["role"], str)
292 else definition["role"]
293 )
294 system_prompt = definition["system_prompt"]
295 model_cfg_dict = dict(definition.get("default_model_config", {}))
296 tools_cfg = definition.get("default_tools", [])
297 tools_enabled = bool(definition.get("tools_enabled", True))
298 mcp_servers = list(definition.get("mcp_servers") or [])
299 input_schema = list(definition.get("input_schema") or [])
300 output_schema = list(definition.get("output_schema") or [])
301 else:
302 role = definition.role
303 system_prompt = definition.system_prompt
304 model_cfg_dict = dict(definition.default_model_config or {})
305 tools_cfg = list(definition.default_tools or [])
306 tools_enabled = bool(getattr(definition, "tools_enabled", True))
307 mcp_servers = list(getattr(definition, "mcp_servers", None) or [])
308 input_schema = list(getattr(definition, "input_schema", None) or [])
309 output_schema = list(getattr(definition, "output_schema", None) or [])
311 # Apply per-node config overrides.
312 # Non-model keys are extracted first so they don't pollute model_cfg_dict.
313 if config_overrides:
314 overrides = dict(config_overrides)
315 prompt_override = overrides.pop("system_prompt", None)
316 if prompt_override:
317 system_prompt = prompt_override
318 if "tools_enabled" in overrides:
319 tools_enabled = bool(overrides.pop("tools_enabled"))
320 if "mcp_servers" in overrides:
321 mcp_servers = list(overrides.pop("mcp_servers") or [])
322 if "input_schema" in overrides:
323 input_schema = list(overrides.pop("input_schema") or [])
324 if "output_schema" in overrides:
325 output_schema = list(overrides.pop("output_schema") or [])
326 if overrides:
327 model_cfg_dict.update(overrides)
329 if llm is None:
330 if not _names_model(model_cfg_dict):
331 if default_model is None:
332 default_model = deployment_default_model
333 fallback = default_model()
334 model_cfg_dict = {
335 **model_cfg_dict,
336 "provider": fallback.provider,
337 "model": fallback.model,
338 }
339 model_config = ModelConfig(**model_cfg_dict)
340 llm = build_langchain_llm(model_config)
341 model_label = f"{model_config.provider}/{model_config.model}"
342 else:
343 model_label = "the caller's model"
345 # tools_enabled=True binds the full general toolset; False produces a
346 # pure reasoning unit. Specialist extras from default_tools (webhooks,
347 # KB tools) are merged either way — they were explicitly configured.
348 from app.tools.registry import general_tools, make_webhook_tool
350 tool_map: dict[str, Any] = (
351 {t.name: t for t in general_tools()} if tools_enabled else {}
352 )
353 for tc_dict in tools_cfg:
354 try:
355 tc = ToolConfig(**tc_dict)
356 if tc.type == "builtin":
357 tool_map[tc.name] = resolve_tool(tc.name, tc.config)
358 elif tc.type == "webhook" and tc.config.get("url"):
359 tool_map[tc.name] = make_webhook_tool(
360 tc.name,
361 tc.config["url"],
362 tc.description or tc.config.get("description", ""),
363 )
364 except Exception:
365 pass
366 tools = list(tool_map.values())
368 cls = AgentFactory.ROLE_CLASS_MAP.get(role, SimpleWorkerAgent)
369 tool_names = [t.name for t in tools] if tools else []
370 logger.info(
371 "[factory] from_definition: node=%r cls=%s role=%s model=%s "
372 "tools_enabled=%s tools=%s mcp_servers=%d",
373 node_id,
374 cls.__name__,
375 role,
376 model_label,
377 tools_enabled,
378 tool_names or "none",
379 len(mcp_servers),
380 )
381 agent = cls(
382 name=node_id,
383 role=role,
384 llm=llm,
385 system_prompt=system_prompt,
386 tools=tools or None,
387 **(extra_kwargs or {}),
388 )
389 # Attribute assignment (not a constructor kwarg) so role subclasses
390 # with custom __init__ signatures (RouterAgent, LoopAgent) work too.
391 agent.mcp_servers = mcp_servers
392 agent.set_interface(input_schema=input_schema, output_schema=output_schema)
393 return agent
395 @staticmethod
396 def from_graph_definition(
397 graph_definition: dict[str, Any],
398 db: Any,
399 llm_override: Any = None,
400 default_model: ModelConfig | None = None,
401 ) -> AgentGraphBuilder:
402 """
403 Build an AgentGraphBuilder from a stored skill graph_definition dict.
405 ``llm_override`` (a chat's explicit model choice) answers every node.
406 Otherwise a node runs on its own pin, else on ``default_model`` — the
407 model of the agent the skill runs for, which the system nodes (triage,
408 evaluator) then use too — else on the deployment's default.
410 The graph_definition format (schema v2 — every field beyond the v1
411 core is optional, so stored v1 definitions load unchanged)::
413 {
414 "state": { # optional user state declaration
415 "<key>": {"description": str, "default": any}
416 },
417 "nodes": {
418 "<node_id>": {
419 "type": "agent" | "tool" | "transform", # default "agent"
421 # type == "agent" (full LLM invocation):
422 "agent_name": str,
423 "config_overrides": dict,
424 "prompt_template": str, # optional; {key} renders from state
425 "input_keys": [str], # optional; state surfaced as context
427 # type == "tool" (deterministic builtin tool call, no LLM):
428 "tool": {"name": str, "args": dict, "config": dict},
430 # type == "transform" (pure state operation, no LLM):
431 "operation": {"op": "template" | "merge" | "select", ...},
433 # any type:
434 "output_key": str, # write result to state_vars[key]
435 "description": str,
436 # schema v3 — typed interface bindings:
437 "inputs": {"<field>": "{state_or_node.path}" | literal},
438 "input_schema": [FieldSpec], # per-node interface override
439 "output_schema": [FieldSpec] # non-empty → structured dict result
440 }
441 },
442 "edges": [[from, to], ...], # fan-out/fan-in: list multiple
443 # edges from/to the same node —
444 # parallel branches merge via
445 # state reducers
446 "start_node": str,
447 "end_nodes": [str, ...],
448 "conditional_edges": { # optional — three forms
449 # (a) schema v3: deterministic branches over graph variables
450 "<source_node_id>": {
451 "branches": [
452 {"key": "high", "target": "escalate",
453 "when": {"var": "assess.risk", "op": "eq", "value": "high"}},
454 {"key": "review", "target": "review",
455 "when": {"all": [{"var": "assess.score", "op": "lt", "value": 0.7}]}}
456 ],
457 "default": "finalise" # or "end"
458 },
459 # (b) route on a field of the source's structured output
460 "<source_node_id>": {
461 "route_field": "category",
462 "route_keys": ["billing", "technical"],
463 "edge_map": {"billing": "node_x", "technical": "node_y"},
464 "default": "node_z" # optional
465 },
466 # (c) legacy: LLM RouterAgent picks one of route_keys
467 "<source_node_id>": {
468 "route_keys": ["key_a", "key_b"],
469 "edge_map": {"key_a": "node_x", "key_b": "node_y"}
470 }
471 },
472 "interface": { # optional skill-level contract
473 "inputs": [FieldSpec], # seed state_vars from the caller
474 "outputs": [{"name": str, "from": "state_key_or_node.path"}]
475 }
476 }
478 Each agent node's ``agent_name`` is resolved to a WorkerAgentDefinition
479 in the DB. Falls back to a SimpleWorkerAgent if the definition
480 is not found. Tool and transform nodes build OperationAgents that run
481 deterministically at zero LLM cost.
483 Conditional edges are evaluated in the order above: ``branches``
484 (deterministic predicates, no LLM), then ``route_field`` (read a field
485 of the source's structured output), then the legacy LLM router — for
486 which the source must resolve to a RouterAgent whose ``candidates``
487 are populated from ``route_keys``. Regular edges from a
488 conditional-source node are skipped (LangGraph cannot have both a
489 plain edge and a conditional edge from the same node).
490 """
491 from app.db.postgres.models import WorkerAgentDefinition
492 from app.agents.conditions import (
493 DEFAULT_BRANCH_KEY,
494 build_branch_router,
495 build_field_router,
496 )
497 from app.agents.operations import ToolOperationAgent, TransformOperationAgent
499 nodes_cfg: dict[str, dict] = graph_definition.get("nodes", {})
500 edges: list[tuple[str, str]] = [
501 tuple(e) for e in graph_definition.get("edges", [])
502 ] # type: ignore[misc]
503 start_node: str = graph_definition.get("start_node", "")
504 end_nodes: list[str] = graph_definition.get("end_nodes", [])
505 # conditional_edges: source_node_id -> {route_keys, edge_map}
506 conditional_edges_cfg: dict[str, dict] = graph_definition.get(
507 "conditional_edges", {}
508 )
510 # Resolve all agent definitions in one query (agent-type nodes only)
511 agent_names = [
512 v.get("agent_name", "")
513 for v in nodes_cfg.values()
514 if v.get("type", "agent") == "agent" and v.get("agent_name")
515 ]
516 definitions: dict[str, WorkerAgentDefinition] = {}
517 if agent_names:
518 rows = (
519 db.query(WorkerAgentDefinition)
520 .filter(WorkerAgentDefinition.name.in_(agent_names))
521 .all()
522 )
523 definitions = {row.name: row for row in rows}
525 logger.info(
526 "[factory] from_graph_definition: nodes=%s start=%r end=%s conditional_sources=%s",
527 list(nodes_cfg.keys()),
528 start_node,
529 end_nodes,
530 list(conditional_edges_cfg.keys()),
531 )
533 # The model for nodes that name none, resolved at most once: the
534 # agent's, or the deployment's default for work with no agent.
535 resolved: list[ModelConfig] = []
537 def fallback_model() -> ModelConfig:
538 if not resolved:
539 from app.services.llm import deployment_default_model
541 resolved.append(default_model or deployment_default_model(db))
542 return resolved[0]
544 system_llm = llm_override
545 if system_llm is None and default_model is not None:
546 # The agent answers through its skill, so the system nodes run on
547 # its model, as they do for a plain agent.
548 from app.services.llm import build_langchain_llm
550 system_llm = build_langchain_llm(default_model)
551 builder = AgentGraphBuilder(db=db, llm=system_llm)
552 # Skill-level typed contract (schema v3) — read by SkillEngine to seed
553 # inputs and by GraphBasedEngine to project outputs.
554 builder.skill_interface = dict(graph_definition.get("interface") or {})
556 # A document the workflow makes in a step of its own is its only
557 # document: its other steps are not offered the tool. Research brief
558 # rendered four times in one run — its research and writing steps,
559 # then its own ``publish`` step.
560 from app.tools.registry import DOCUMENT_TOOL
562 step_owned = frozenset(
563 name
564 for name in (
565 (cfg.get("tool") or {}).get("name")
566 for cfg in nodes_cfg.values()
567 if cfg.get("type") == "tool"
568 )
569 if name == DOCUMENT_TOOL
570 )
572 for node_id, node_cfg in nodes_cfg.items():
573 node_type = node_cfg.get("type", "agent")
574 description = node_cfg.get("description", "")
576 if node_type == "tool":
577 tool_cfg = node_cfg.get("tool") or {}
578 agent: WorkerAgent = ToolOperationAgent(
579 name=node_id,
580 tool_name=tool_cfg.get("name", ""),
581 args=tool_cfg.get("args") or {},
582 config=tool_cfg.get("config") or {},
583 description=description,
584 )
585 elif node_type == "transform":
586 agent = TransformOperationAgent(
587 name=node_id,
588 operation=node_cfg.get("operation") or {},
589 description=description,
590 )
591 else:
592 agent_name = node_cfg.get("agent_name", "")
593 overrides = node_cfg.get("config_overrides") or {}
594 defn = definitions.get(agent_name)
596 # For RouterAgent nodes with conditional edges, pass route_keys as candidates
597 extra_kwargs: dict[str, Any] = {}
598 if node_id in conditional_edges_cfg and defn is not None:
599 defn_role = (
600 defn.role
601 if not isinstance(defn, dict)
602 else AgentRole(defn.get("role", "worker"))
603 )
604 if defn_role == AgentRole.ROUTER:
605 extra_kwargs["candidates"] = conditional_edges_cfg[node_id].get(
606 "route_keys", []
607 )
609 if defn is not None:
610 agent = AgentFactory.from_definition(
611 node_id,
612 defn,
613 overrides,
614 extra_kwargs,
615 default_model=fallback_model,
616 llm=llm_override,
617 )
618 else:
619 logger.warning(
620 "[factory] no WorkerAgentDefinition found for %r (node=%r) — using SimpleWorkerAgent",
621 agent_name,
622 node_id,
623 )
624 agent = SimpleWorkerAgent(name=node_id)
625 if llm_override is not None:
626 agent.llm = llm_override
627 elif default_model is not None:
628 from app.services.llm import build_langchain_llm
630 agent.llm = build_langchain_llm(default_model)
631 # Otherwise resolve_llm builds the deployment's default
632 # when the node first runs.
634 if step_owned and node_type not in ("tool", "transform"):
635 agent.withheld_tools = step_owned
636 agent.tools = [t for t in agent.tools if t.name not in step_owned]
638 # Per-node interface overrides (schema v3) apply to every node
639 # type — a generic worker can be given a structured contract at
640 # the node, and a tool/transform node can declare what it emits.
641 if (
642 node_cfg.get("input_schema") is not None
643 or node_cfg.get("output_schema") is not None
644 ):
645 agent.set_interface(
646 input_schema=node_cfg.get("input_schema"),
647 output_schema=node_cfg.get("output_schema"),
648 )
650 builder.add_agent(
651 node_id,
652 agent,
653 start=(node_id == start_node),
654 end=(node_id in end_nodes),
655 output_key=node_cfg.get("output_key", ""),
656 prompt_template=node_cfg.get("prompt_template", ""),
657 input_keys=node_cfg.get("input_keys") or [],
658 inputs=node_cfg.get("inputs") or {},
659 approval=node_cfg.get("approval") or None,
660 ask_user=bool(node_cfg.get("ask_user")),
661 )
663 # Add regular edges, skipping sources that use conditional routing
664 conditional_sources = set(conditional_edges_cfg.keys())
665 for from_node, to_node in edges:
666 if from_node not in conditional_sources:
667 builder.add_edge(from_node, to_node)
669 # Wire conditional edges. Deterministic forms first (no LLM cost);
670 # the legacy RouterAgent form uses route_from_state so the routing
671 # decision made when the node ran is reused rather than re-asked.
672 for source_id, ce_cfg in conditional_edges_cfg.items():
673 node = builder.nodes.get(source_id)
674 if node is None:
675 logger.warning(
676 "[factory] conditional edge source %r not in graph — skipping",
677 source_id,
678 )
679 continue
680 default_target = ce_cfg.get("default") or None
682 if ce_cfg.get("branches"):
683 route_fn, edge_map = build_branch_router(
684 source_id, ce_cfg["branches"], default_target
685 )
686 builder.add_conditional_edge(source_id, route_fn, edge_map)
687 logger.info(
688 "[factory] conditional edge (branches): %r → %s",
689 source_id,
690 edge_map,
691 )
692 continue
694 route_keys: list[str] = list(ce_cfg.get("route_keys") or [])
695 edge_map = dict(ce_cfg.get("edge_map") or {})
696 if ce_cfg.get("route_field"):
697 route_fn, extra = build_field_router(
698 source_id, ce_cfg["route_field"], route_keys, default_target
699 )
700 edge_map.update(extra)
701 builder.add_conditional_edge(source_id, route_fn, edge_map)
702 logger.info(
703 "[factory] conditional edge (field %r): %r → %s",
704 ce_cfg["route_field"],
705 source_id,
706 edge_map,
707 )
708 continue
710 if not isinstance(node.agent, RouterAgent):
711 logger.warning(
712 "[factory] conditional edge source %r resolved to %s, not "
713 "RouterAgent, and declares neither branches nor route_field — skipping",
714 source_id,
715 type(node.agent).__name__,
716 )
717 continue
718 if default_target:
719 edge_map[DEFAULT_BRANCH_KEY] = default_target
720 builder.add_conditional_edge(
721 source_id, node.agent.route_from_state, edge_map
722 )
723 logger.info(
724 "[factory] conditional edge (router): %r → %s", source_id, edge_map
725 )
727 return builder
730# Populate after class body so forward references are resolved.
731AgentFactory.ROLE_CLASS_MAP = {
732 AgentRole.PLANNER: PlannerAgent,
733 AgentRole.ANALYZER: AnalyzerAgent,
734 AgentRole.VALIDATOR: ValidatorAgent,
735 AgentRole.RESEARCHER: ResearchAgent,
736 AgentRole.ROUTER: RouterAgent,
737 AgentRole.EXECUTOR: SimpleWorkerAgent,
738 AgentRole.WORKER: SimpleWorkerAgent,
739 AgentRole.REVIEWER: ReviewerAgent,
740 AgentRole.LOOP: LoopAgent,
741}