|
| 1 | +"""FunctionNode implementation for executing deterministic Python functions as graph nodes. |
| 2 | +
|
| 3 | +This module provides the FunctionNode class that extends MultiAgentBase to execute |
| 4 | +regular Python functions while maintaining compatibility with the existing graph |
| 5 | +execution framework, proper error handling, metrics collection, and result formatting. |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +import time |
| 10 | +from typing import Any, Protocol, Union |
| 11 | + |
| 12 | +from opentelemetry import trace as trace_api |
| 13 | + |
| 14 | +from ..agent import AgentResult |
| 15 | +from ..telemetry import get_tracer |
| 16 | +from ..telemetry.metrics import EventLoopMetrics |
| 17 | +from ..types.content import ContentBlock, Message |
| 18 | +from ..types.event_loop import Metrics, Usage |
| 19 | +from .base import MultiAgentBase, MultiAgentResult, NodeResult, Status |
| 20 | + |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | + |
| 23 | + |
| 24 | +class FunctionNodeCallable(Protocol): |
| 25 | + """Protocol defining the required signature for functions used in FunctionNode. |
| 26 | +
|
| 27 | + Functions must accept: |
| 28 | + - task: The input task (string or ContentBlock list) |
| 29 | + - invocation_state: Additional state/context from the calling environment |
| 30 | + - **kwargs: Additional keyword arguments for future extensibility |
| 31 | +
|
| 32 | + Functions must return: |
| 33 | + - A string result that will be converted to a Message |
| 34 | + """ |
| 35 | + |
| 36 | + def __call__( |
| 37 | + self, task: Union[str, list[ContentBlock]], invocation_state: dict[str, Any] | None = None, **kwargs: Any |
| 38 | + ) -> str: |
| 39 | + """Execute the node with the given task.""" |
| 40 | + ... |
| 41 | + |
| 42 | + |
| 43 | +class FunctionNode(MultiAgentBase): |
| 44 | + """Execute deterministic Python functions as graph nodes. |
| 45 | +
|
| 46 | + FunctionNode wraps any callable Python function and executes it within the |
| 47 | + established multiagent framework, handling input conversion, error management, |
| 48 | + metrics collection, and result formatting automatically. |
| 49 | +
|
| 50 | + Args: |
| 51 | + func: The callable function to wrap and execute |
| 52 | + name: Required name for the node |
| 53 | + """ |
| 54 | + |
| 55 | + def __init__(self, func: FunctionNodeCallable, name: str): |
| 56 | + """Initialize FunctionNode with a callable function and required name. |
| 57 | +
|
| 58 | + Args: |
| 59 | + func: The callable function to wrap and execute |
| 60 | + name: Required name for the node |
| 61 | + """ |
| 62 | + self.func = func |
| 63 | + self.name = name |
| 64 | + self.tracer = get_tracer() |
| 65 | + |
| 66 | + async def invoke_async( |
| 67 | + self, task: Union[str, list[ContentBlock]], invocation_state: dict[str, Any] | None = None, **kwargs: Any |
| 68 | + ) -> MultiAgentResult: |
| 69 | + """Execute the wrapped function and return formatted results. |
| 70 | +
|
| 71 | + Args: |
| 72 | + task: The task input (string or ContentBlock list) to pass to the function |
| 73 | + invocation_state: Additional state/context (preserved for interface compatibility) |
| 74 | + **kwargs: Additional keyword arguments (preserved for future extensibility) |
| 75 | +
|
| 76 | + Returns: |
| 77 | + MultiAgentResult containing the function execution results and metadata |
| 78 | + """ |
| 79 | + if invocation_state is None: |
| 80 | + invocation_state = {} |
| 81 | + |
| 82 | + logger.debug("task=<%s> | starting function node execution", task) |
| 83 | + logger.debug("function_name=<%s> | executing function", self.name) |
| 84 | + |
| 85 | + start_time = time.time() |
| 86 | + span = self.tracer.start_multiagent_span(task, "function_node") |
| 87 | + with trace_api.use_span(span, end_on_exit=True): |
| 88 | + try: |
| 89 | + # Execute the wrapped function with proper parameters |
| 90 | + function_result = self.func(task, invocation_state, **kwargs) |
| 91 | + logger.debug("function_result=<%s> | function executed successfully", function_result) |
| 92 | + |
| 93 | + # Calculate execution time |
| 94 | + execution_time = int((time.time() - start_time) * 1000) # Convert to milliseconds |
| 95 | + |
| 96 | + # Convert function result to Message |
| 97 | + message = Message(role="assistant", content=[ContentBlock(text=str(function_result))]) |
| 98 | + agent_result = AgentResult( |
| 99 | + stop_reason="end_turn", # "Normal completion of the response" - function executed successfully |
| 100 | + message=message, |
| 101 | + metrics=EventLoopMetrics(), |
| 102 | + state={}, |
| 103 | + ) |
| 104 | + |
| 105 | + # Create NodeResult for this function execution |
| 106 | + node_result = NodeResult( |
| 107 | + result=agent_result, # type is AgentResult |
| 108 | + execution_time=execution_time, |
| 109 | + status=Status.COMPLETED, |
| 110 | + execution_count=1, |
| 111 | + ) |
| 112 | + |
| 113 | + # Create MultiAgentResult with the NodeResult |
| 114 | + multi_agent_result = MultiAgentResult( |
| 115 | + status=Status.COMPLETED, |
| 116 | + results={self.name: node_result}, |
| 117 | + execution_count=1, |
| 118 | + execution_time=execution_time, |
| 119 | + ) |
| 120 | + |
| 121 | + logger.debug( |
| 122 | + "function_name=<%s>, execution_time=<%dms> | function node completed successfully", |
| 123 | + self.name, |
| 124 | + execution_time, |
| 125 | + ) |
| 126 | + |
| 127 | + return multi_agent_result |
| 128 | + |
| 129 | + except Exception as e: |
| 130 | + # Calculate execution time even for failed executions |
| 131 | + execution_time = int((time.time() - start_time) * 1000) # Convert to milliseconds |
| 132 | + |
| 133 | + logger.error("function_name=<%s>, error=<%s> | function node failed", self.name, e) |
| 134 | + |
| 135 | + # Create failed NodeResult with exception |
| 136 | + node_result = NodeResult( |
| 137 | + result=e, |
| 138 | + execution_time=execution_time, |
| 139 | + status=Status.FAILED, |
| 140 | + accumulated_usage=Usage(inputTokens=0, outputTokens=0, totalTokens=0), |
| 141 | + accumulated_metrics=Metrics(latencyMs=execution_time), |
| 142 | + execution_count=1, |
| 143 | + ) |
| 144 | + |
| 145 | + # Create failed MultiAgentResult |
| 146 | + multi_agent_result = MultiAgentResult( |
| 147 | + status=Status.FAILED, |
| 148 | + results={self.name: node_result}, |
| 149 | + accumulated_usage=Usage(inputTokens=0, outputTokens=0, totalTokens=0), |
| 150 | + accumulated_metrics=Metrics(latencyMs=execution_time), |
| 151 | + execution_count=1, |
| 152 | + execution_time=execution_time, |
| 153 | + ) |
| 154 | + |
| 155 | + return multi_agent_result |
0 commit comments