feat: Phase 3 - Logic Nodes + Conditional Branching
Backend: - logic_evaluator.py (NEU, 307 Zeilen): Deterministischer Logic Evaluator - Vergleichsoperatoren: EQ, NEQ, IN, NOT_IN, GT, LT, GTE, LTE, CONTAINS - Logische Operatoren: AND, OR, NOT mit Verschachtelung - Resolve signal references (node_id.question_type) - Error handling für UNCLEAR/INVALID/NOT_DECIDABLE Signale - workflow_executor.py (ERWEITERT): - execute_logic_node(): Bedingungen evaluieren, Pfade aktivieren/deaktivieren - execute_workflow(): BFS-Traversierung mit Edge-Activation statt Sequential - _apply_fallback(): 4 Fallback-Strategien (CONSERVATIVE_SKIP, DEFAULT_PATH, UNCERTAINTY_PATH, DOCUMENT_ONLY) - _has_active_incoming_edge(): Prüft ob Node erreichbar ist - _get_edges_by_label(): Findet then/else/uncertainty Pfade - workflow_models.py (ERWEITERT): - LogicOperator.CONTAINS hinzugefügt - version.py: 0.9k → 0.9l, workflow 0.3.0 → 0.4.0 Tests: - test_phase3_logic_evaluator.py (NEU): 20 Unit Tests (alle passing) - Comparison operators (EQ, NEQ, IN, GT, LT, CONTAINS) - Logical operators (AND, OR, NOT) - Nested expressions - Error handling (missing refs, UNCLEAR/INVALID signals) - test_phase2_workflow_executor.py (AKTUALISIERT): 11 Tests (alle passing) - execute_node() graph parameter hinzugefügt (Phase 3 requirement) - test_execute_node_unknown_type: logic → join (logic jetzt implementiert) - test_phase3_workflow_branching.py (NEU): Integration Tests vorbereitet - Erfordert vollständige DB-Mock-Strategie (wird in E2E-Test nachgeholt) Phase 2 Backward Compatibility: ✅ Alle Phase 2 Tests bestehen weiterhin Konzept: .claude/task/Workflow_engine_prompting_engine/konzept_workflow_engine_konsolidated.md Anforderungsanalyse: .claude/task/Workflow_engine_prompting_engine/phase3_anforderungsanalyse.md Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
16dc08cd7d
commit
2ce0874dcb
7 files changed
+1735
-41
No files matched your search
+251
-24
@@ -1,12 +1,15 @@
|
||||
"""
|
||||
Workflow Executor (Phase 2)
|
||||
Workflow Executor (Phase 3)
|
||||
|
||||
Führt Workflows sequenziell aus (noch keine Verzweigung/Logik).
|
||||
Führt Workflows mit conditional branching aus (Logic Nodes).
|
||||
|
||||
Phase 2: Sequential execution
|
||||
Phase 3: Conditional branching, Logic Nodes, Fallback strategies
|
||||
|
||||
Konzept-Basis: konzept_workflow_engine_konsolidated.md
|
||||
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md (Phase 2)
|
||||
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md (Phase 2-3)
|
||||
"""
|
||||
from typing import Dict, Any, List, Optional
|
||||
from typing import Dict, Any, List, Optional, Set
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
import logging
|
||||
@@ -14,7 +17,7 @@ import json
|
||||
|
||||
from workflow_models import (
|
||||
WorkflowGraph, NodeExecutionState, ExecutionResult,
|
||||
NodeStatus, NormalizedSignal
|
||||
NodeStatus, NormalizedSignal, FallbackStrategy, SignalStatus
|
||||
)
|
||||
from workflow_engine import parse_workflow_graph, get_execution_order
|
||||
from question_augmenter import (
|
||||
@@ -23,6 +26,7 @@ from question_augmenter import (
|
||||
)
|
||||
from result_container_parser import parse_result_container
|
||||
from normalization_engine import normalize_all_signals, load_question_catalog
|
||||
from logic_evaluator import evaluate_logic_expression, resolve_signal_reference
|
||||
from db import get_db, get_cursor
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -36,10 +40,10 @@ async def execute_workflow(
|
||||
enable_debug: bool = False
|
||||
) -> ExecutionResult:
|
||||
"""
|
||||
Führt einen Workflow aus (sequenziell, ohne Verzweigung).
|
||||
Führt einen Workflow aus (mit conditional branching).
|
||||
|
||||
Phase 2: Linear execution in topological order.
|
||||
Phase 3: Conditional branching basierend auf normalized_signals.
|
||||
Phase 3: Conditional branching basierend auf logic nodes.
|
||||
|
||||
Args:
|
||||
workflow_id: UUID des Workflows
|
||||
@@ -86,39 +90,69 @@ async def execute_workflow(
|
||||
graph = parse_workflow_graph(graph_json)
|
||||
logger.debug(f"Parsed graph: {len(graph.nodes)} nodes, {len(graph.edges)} edges")
|
||||
|
||||
# 3. Topologische Sortierung
|
||||
execution_order = get_execution_order(graph)
|
||||
logger.info(f"Execution order: {execution_order}")
|
||||
|
||||
# 4. Lade Question Catalog
|
||||
with get_db() as conn:
|
||||
catalog = load_question_catalog(conn)
|
||||
logger.debug(f"Loaded catalog: {len(catalog)} question types")
|
||||
|
||||
# 5. Execute Nodes sequenziell
|
||||
# 5. Execute Nodes mit conditional branching (Phase 3)
|
||||
node_states: List[NodeExecutionState] = []
|
||||
context = {"variables": variables, "profile_id": profile_id}
|
||||
context = {
|
||||
"variables": variables,
|
||||
"profile_id": profile_id,
|
||||
"node_results": {}, # Phase 3: Store full NodeExecutionState
|
||||
"active_edges": {} # Phase 3: Track edge activation
|
||||
}
|
||||
|
||||
for node_id in execution_order:
|
||||
# Phase 3: BFS traversal mit edge activation
|
||||
start_node = next((n for n in graph.nodes if n.type == "start"), None)
|
||||
if not start_node:
|
||||
raise ValueError("No start node found in workflow")
|
||||
|
||||
visited: Set[str] = set()
|
||||
queue = [start_node.id]
|
||||
|
||||
while queue:
|
||||
node_id = queue.pop(0)
|
||||
|
||||
if node_id in visited:
|
||||
continue
|
||||
|
||||
visited.add(node_id)
|
||||
node = next(n for n in graph.nodes if n.id == node_id)
|
||||
|
||||
# Prüfe ob Node aktiv ist (mindestens eine incoming edge aktiv)
|
||||
if not _has_active_incoming_edge(node, graph, context):
|
||||
logger.info(f"Skipping node {node_id}: no active incoming edges")
|
||||
node_states.append(NodeExecutionState(
|
||||
node_id=node_id,
|
||||
status=NodeStatus.SKIPPED,
|
||||
error="no_active_incoming_edges",
|
||||
started_at=datetime.utcnow().isoformat(),
|
||||
completed_at=datetime.utcnow().isoformat()
|
||||
))
|
||||
continue
|
||||
|
||||
logger.info(f"Executing node: {node_id} (type: {node.type})")
|
||||
|
||||
node_state = await execute_node(
|
||||
node=node,
|
||||
context=context,
|
||||
catalog=catalog,
|
||||
graph=graph, # Phase 3: Needed for logic nodes
|
||||
openrouter_call_func=openrouter_call_func,
|
||||
enable_debug=enable_debug
|
||||
)
|
||||
|
||||
node_states.append(node_state)
|
||||
context["node_results"][node_id] = node_state
|
||||
|
||||
# Füge Ergebnisse zu Context hinzu (für späteren Zugriff in Phase 3)
|
||||
context[f"node_{node_id}"] = {
|
||||
"analysis_core": node_state.analysis_core,
|
||||
"normalized_signals": [s.model_dump() for s in node_state.normalized_signals]
|
||||
}
|
||||
# Füge Nachfolger zur Queue hinzu
|
||||
outgoing_edges = [e for e in graph.edges if e.from_node == node_id]
|
||||
for edge in outgoing_edges:
|
||||
# Prüfe ob Edge aktiv ist (default: True, Logic Nodes setzen auf False)
|
||||
if context["active_edges"].get(edge.id, True):
|
||||
queue.append(edge.to_node)
|
||||
|
||||
# 6. Aggregiere Ergebnisse
|
||||
aggregated = aggregate_results(node_states)
|
||||
@@ -179,6 +213,7 @@ async def execute_node(
|
||||
node,
|
||||
context: Dict[str, Any],
|
||||
catalog: Dict[str, Dict],
|
||||
graph: WorkflowGraph, # Phase 3: Needed for logic nodes
|
||||
openrouter_call_func,
|
||||
enable_debug: bool = False
|
||||
) -> NodeExecutionState:
|
||||
@@ -187,8 +222,9 @@ async def execute_node(
|
||||
|
||||
Args:
|
||||
node: WorkflowNode (aus graph.nodes)
|
||||
context: Execution context (variables, profile_id, prior results)
|
||||
context: Execution context (variables, profile_id, node_results, active_edges)
|
||||
catalog: Question catalog
|
||||
graph: WorkflowGraph (für Logic Nodes)
|
||||
openrouter_call_func: LLM callback: async (prompt, model) -> str
|
||||
enable_debug: Debug mode
|
||||
|
||||
@@ -198,7 +234,8 @@ async def execute_node(
|
||||
Node Types:
|
||||
- start/end: No-op
|
||||
- analysis: Load prompt → augment → LLM → parse → normalize
|
||||
- logic/join: Not implemented in Phase 2
|
||||
- logic: Evaluate condition → activate/deactivate edges (Phase 3)
|
||||
- join: Not implemented (Phase 4)
|
||||
"""
|
||||
started_at = datetime.utcnow().isoformat()
|
||||
|
||||
@@ -213,6 +250,10 @@ async def execute_node(
|
||||
completed_at=datetime.utcnow().isoformat()
|
||||
)
|
||||
|
||||
# Logic Nodes (Phase 3)
|
||||
if node.type == "logic":
|
||||
return execute_logic_node(node, context, graph)
|
||||
|
||||
# Analysis Nodes
|
||||
if node.type == "analysis":
|
||||
# 1. Lade Prompt
|
||||
@@ -278,8 +319,8 @@ async def execute_node(
|
||||
completed_at=datetime.utcnow().isoformat()
|
||||
)
|
||||
|
||||
# Unbekannter Node-Typ (Phase 3: logic, join)
|
||||
raise ValueError(f"Node type '{node.type}' not implemented in Phase 2")
|
||||
# Unbekannter Node-Typ (Phase 4: join)
|
||||
raise ValueError(f"Node type '{node.type}' not implemented yet (Phase 4+)")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Node execution failed ({node.id}): {e}", exc_info=True)
|
||||
@@ -292,6 +333,191 @@ async def execute_node(
|
||||
)
|
||||
|
||||
|
||||
def execute_logic_node(
|
||||
node,
|
||||
context: Dict[str, Any],
|
||||
graph: WorkflowGraph
|
||||
) -> NodeExecutionState:
|
||||
"""
|
||||
Führt Logic Node aus (Phase 3).
|
||||
|
||||
Args:
|
||||
node: WorkflowNode vom Typ "logic"
|
||||
context: Execution context mit node_results
|
||||
graph: WorkflowGraph
|
||||
|
||||
Returns:
|
||||
NodeExecutionState mit evaluation_result in metadata
|
||||
|
||||
Logic:
|
||||
1. Evaluiere node.condition.expression
|
||||
2. Wähle then_path oder else_path basierend auf Ergebnis
|
||||
3. Bei Fehler/Unsicherheit: Wende fallback an
|
||||
4. Markiere gewählte Edge(s) als aktiv, andere als inaktiv
|
||||
5. Return NodeExecutionState mit evaluation_result
|
||||
"""
|
||||
started_at = datetime.utcnow().isoformat()
|
||||
|
||||
try:
|
||||
if not node.condition:
|
||||
raise ValueError(f"Logic node {node.id} has no condition")
|
||||
|
||||
# 1. Evaluiere Bedingung
|
||||
result, error = evaluate_logic_expression(node.condition.expression, context)
|
||||
|
||||
if error:
|
||||
# Fehler bei Evaluation → Fallback anwenden
|
||||
logger.warning(f"Logic node {node.id}: evaluation error: {error}")
|
||||
activated_edges = _apply_fallback(node, graph, context, error)
|
||||
else:
|
||||
# Erfolgreiche Evaluation
|
||||
logger.info(f"Logic node {node.id}: evaluated to {result}")
|
||||
|
||||
# 2. Wähle Pfad basierend auf Ergebnis
|
||||
if result:
|
||||
# Condition TRUE → then_path aktivieren
|
||||
activated_edges = _get_edges_by_label(node.id, "then", graph)
|
||||
else:
|
||||
# Condition FALSE → else_path aktivieren
|
||||
activated_edges = _get_edges_by_label(node.id, "else", graph)
|
||||
|
||||
# 3. Markiere Edges als aktiv/inaktiv
|
||||
outgoing_edges = [e for e in graph.edges if e.from_node == node.id]
|
||||
for edge in outgoing_edges:
|
||||
context["active_edges"][edge.id] = edge.id in activated_edges
|
||||
|
||||
logger.debug(f"Logic node {node.id}: activated edges: {activated_edges}")
|
||||
|
||||
return NodeExecutionState(
|
||||
node_id=node.id,
|
||||
status=NodeStatus.EXECUTED,
|
||||
started_at=started_at,
|
||||
completed_at=datetime.utcnow().isoformat(),
|
||||
analysis_core=json.dumps({
|
||||
"evaluation_result": result if not error else None,
|
||||
"error": error,
|
||||
"activated_edges": activated_edges
|
||||
})
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Logic node execution failed ({node.id}): {e}", exc_info=True)
|
||||
return NodeExecutionState(
|
||||
node_id=node.id,
|
||||
status=NodeStatus.FAILED,
|
||||
error=str(e),
|
||||
started_at=started_at,
|
||||
completed_at=datetime.utcnow().isoformat()
|
||||
)
|
||||
|
||||
|
||||
def _apply_fallback(
|
||||
node,
|
||||
graph: WorkflowGraph,
|
||||
context: Dict[str, Any],
|
||||
error: str
|
||||
) -> List[str]:
|
||||
"""
|
||||
Wendet Fallback-Strategie an.
|
||||
|
||||
Args:
|
||||
node: WorkflowNode
|
||||
graph: WorkflowGraph
|
||||
context: Execution context
|
||||
error: Fehler bei Evaluation
|
||||
|
||||
Returns:
|
||||
Liste von Edge-IDs die aktiviert werden sollen
|
||||
"""
|
||||
if not node.fallback:
|
||||
# Default: Konservativ (else-Pfad nehmen)
|
||||
logger.warning(f"Node {node.id}: No fallback configured, using DEFAULT_PATH")
|
||||
return _get_edges_by_label(node.id, "else", graph)
|
||||
|
||||
strategy = node.fallback.strategy
|
||||
|
||||
if strategy == FallbackStrategy.CONSERVATIVE_SKIP:
|
||||
# Skip alle outgoing edges
|
||||
logger.info(f"Node {node.id}: CONSERVATIVE_SKIP - deactivating all paths")
|
||||
return []
|
||||
|
||||
elif strategy == FallbackStrategy.DEFAULT_PATH:
|
||||
# Nimm else-Pfad
|
||||
logger.info(f"Node {node.id}: DEFAULT_PATH - taking else path")
|
||||
return _get_edges_by_label(node.id, "else", graph)
|
||||
|
||||
elif strategy == FallbackStrategy.UNCERTAINTY_PATH:
|
||||
# Expliziter Unsicherheits-Pfad (falls vorhanden)
|
||||
logger.info(f"Node {node.id}: UNCERTAINTY_PATH")
|
||||
uncertainty_edges = _get_edges_by_label(node.id, "uncertainty", graph)
|
||||
if uncertainty_edges:
|
||||
return uncertainty_edges
|
||||
else:
|
||||
# Fallback to else
|
||||
logger.warning(f"Node {node.id}: No uncertainty path found, using else")
|
||||
return _get_edges_by_label(node.id, "else", graph)
|
||||
|
||||
elif strategy == FallbackStrategy.DOCUMENT_ONLY:
|
||||
# Alle Pfade aktiv lassen (wie ohne Bedingung)
|
||||
logger.info(f"Node {node.id}: DOCUMENT_ONLY - all paths remain active")
|
||||
outgoing_edges = [e for e in graph.edges if e.from_node == node.id]
|
||||
return [e.id for e in outgoing_edges]
|
||||
|
||||
else:
|
||||
logger.warning(f"Node {node.id}: Unknown fallback strategy {strategy}, using DEFAULT_PATH")
|
||||
return _get_edges_by_label(node.id, "else", graph)
|
||||
|
||||
|
||||
def _get_edges_by_label(node_id: str, label: str, graph: WorkflowGraph) -> List[str]:
|
||||
"""
|
||||
Findet alle ausgehenden Edges mit bestimmtem Label.
|
||||
|
||||
Args:
|
||||
node_id: Node-ID
|
||||
label: Edge-Label (z.B. "then", "else", "uncertainty")
|
||||
graph: WorkflowGraph
|
||||
|
||||
Returns:
|
||||
Liste von Edge-IDs
|
||||
"""
|
||||
matching_edges = [
|
||||
e.id for e in graph.edges
|
||||
if e.from_node == node_id and e.label == label
|
||||
]
|
||||
return matching_edges
|
||||
|
||||
|
||||
def _has_active_incoming_edge(node, graph: WorkflowGraph, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Prüft ob Node mindestens eine aktive incoming edge hat.
|
||||
|
||||
Args:
|
||||
node: WorkflowNode
|
||||
graph: WorkflowGraph
|
||||
context: Execution context mit active_edges
|
||||
|
||||
Returns:
|
||||
True wenn mindestens eine incoming edge aktiv ist
|
||||
"""
|
||||
# Start-Node hat keine incoming edges → immer aktiv
|
||||
if node.type == "start":
|
||||
return True
|
||||
|
||||
incoming_edges = [e for e in graph.edges if e.to_node == node.id]
|
||||
|
||||
# Keine incoming edges → nicht erreichbar
|
||||
if not incoming_edges:
|
||||
return False
|
||||
|
||||
# Prüfe ob mindestens eine aktiv ist
|
||||
active_edges = context.get("active_edges", {})
|
||||
for edge in incoming_edges:
|
||||
if active_edges.get(edge.id, True): # Default: True (Phase 2 Kompatibilität)
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
async def load_prompt_template(prompt_slug: str, context: Dict[str, Any]) -> str:
|
||||
"""
|
||||
Lädt Prompt-Template aus DB und resolved Platzhalter.
|
||||
@@ -375,7 +601,8 @@ def aggregate_results(node_states: List[NodeExecutionState]) -> Dict[str, Any]:
|
||||
"all_signals": all_signals,
|
||||
"total_nodes": len(node_states),
|
||||
"executed_nodes": sum(1 for s in node_states if s.status == NodeStatus.EXECUTED),
|
||||
"failed_nodes": sum(1 for s in node_states if s.status == NodeStatus.FAILED)
|
||||
"failed_nodes": sum(1 for s in node_states if s.status == NodeStatus.FAILED),
|
||||
"skipped_nodes": sum(1 for s in node_states if s.status == NodeStatus.SKIPPED) # Phase 3
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user