Coverage for app / inference / engines / graph.py: 60%

30 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2GraphEngine — named or dynamically configured multi-agent graph. 

3 

4Handles ExecuteRequest(type="graph"). 

5""" 

6 

7from __future__ import annotations 

8 

9from typing import Any 

10 

11from app.agents.graph import GraphState 

12from app.inference.context import InferenceContext 

13from app.inference.engines.graph_based import GraphBasedEngine 

14from app.models.spec import AgentGraphConfig 

15 

16 

17class GraphEngine(GraphBasedEngine): 

18 """ 

19 Executes a named or dynamically specified agent graph. 

20 

21 Built-in graph patterns (``"analysis"``, ``"rag"``) are dispatched to 

22 AgentFactory's preset builders. All other specs are assembled from the 

23 ``agents`` + ``edges`` + ``conditional_routes`` fields. 

24 """ 

25 

26 def _build_builder( 

27 self, ctx: InferenceContext 

28 ) -> tuple[Any, list[dict], dict[str, Any]]: 

29 from app.agents.factory import AgentFactory 

30 

31 spec: AgentGraphConfig = ctx.request.spec # type: ignore[assignment] 

32 

33 if spec.name == "analysis": 

34 builder = AgentFactory.create_analysis_graph() 

35 elif spec.name == "rag": 

36 builder = AgentFactory.create_retrieval_augmented_graph() 

37 else: 

38 agents = AgentFactory.agents_from_spec(spec) 

39 builder = AgentFactory.create_custom_graph( 

40 agents=agents, 

41 edges=spec.edges, 

42 start_node=spec.start_agent, 

43 end_nodes=spec.end_agents, 

44 ) 

45 for from_node, route_cfg in spec.conditional_routes.items(): 

46 if from_node in builder.nodes: 

47 edge_map: dict[str, str] = route_cfg.get("edge_map", {}) 

48 field = route_cfg.get("field", "complexity") 

49 threshold = route_cfg.get("threshold", 3) 

50 

51 def _make_condition(f: str, t: int): 

52 def condition_fn(state: GraphState) -> str: 

53 return ( 

54 "true_branch" 

55 if state.context.get(f, 0) > t 

56 else "false_branch" 

57 ) 

58 

59 return condition_fn 

60 

61 builder.add_conditional_edge( 

62 from_node, _make_condition(field, threshold), edge_map 

63 ) 

64 

65 builder._db = self.db # type: ignore[attr-defined] 

66 knowledge_bases = [kb.model_dump() for kb in spec.knowledge_bases] 

67 extra_context: dict[str, Any] = { 

68 "graph_name": spec.name, 

69 "retrieval_config": spec.retrieval.model_dump(), 

70 } 

71 

72 return builder, knowledge_bases, extra_context