Internal loop controller that decides continue vs terminate.
| 123 | self._output = message |
| 124 | self._gate = Gate.OPEN |
| 125 | class Controller(InternalGraphNode): |
| 126 | """Internal loop controller that decides continue vs terminate.""" |
| 127 | def __init__(self, |
| 128 | name, |
| 129 | max_iterations:int=10, |
| 130 | model:Model|None=None, |
| 131 | terminate_condition:str|None=None, |
| 132 | terminate_condition_function:Callable|None=None, |
| 133 | gate_close_callback:Callable|None=None, |
| 134 | pull_keys:dict[str,dict|str]|None=None, |
| 135 | push_keys:dict[str,dict|str]|None=None): |
| 136 | """ |
| 137 | Args: |
| 138 | name: Controller name. |
| 139 | max_iterations: Maximum loop iterations. |
| 140 | model: Optional model used for termination checks. |
| 141 | terminate_condition: Optional natural-language terminate condition. |
| 142 | terminate_condition_function: Optional custom terminate function. |
| 143 | """ |
| 144 | super().__init__(name, gate_close_callback, pull_keys, push_keys) |
| 145 | |
| 146 | self.outsource_input: dict[str,object] = {} |
| 147 | self._message_cache: dict[str,object] = {} |
| 148 | self._output: dict[str,object] = {} |
| 149 | self._is_from_outside = True |
| 150 | self._max_iterations = max_iterations |
| 151 | self._terminate_condition_prompt = terminate_condition |
| 152 | self._terminate_condition_function = terminate_condition_function |
| 153 | self._terminate_condition_model = model |
| 154 | self._current_iteration = 0 |
| 155 | self._terminated = False |
| 156 | self._iteration_limited = self._max_iterations is not None and self._max_iterations > 0 |
| 157 | |
| 158 | |
| 159 | # Optional context objects for terminate_condition_function (may be empty). |
| 160 | self._memories = [] |
| 161 | self._tools = [] |
| 162 | self._retrievers = [] |
| 163 | |
| 164 | agent_terminate_condition_setting:bool = self._terminate_condition_model != None and self._terminate_condition_prompt != None |
| 165 | |
| 166 | if not agent_terminate_condition_setting and not self._iteration_limited and not self._terminate_condition_function: |
| 167 | raise ValueError("To avoid infinite loop, either terminate_condition_model and it's prompt or max_iterations or terminate_condition_function must be provided. ") |
| 168 | def reset(self): |
| 169 | """Reset controller runtime state.""" |
| 170 | self._is_from_outside = True |
| 171 | self._current_iteration = 0 |
| 172 | self._terminated = False |
| 173 | self.outsource_input = {} |
| 174 | self._message_cache = initial_messages_template.copy() |
| 175 | self._output = {} |
| 176 | super().reset() |
| 177 | def reset_gate(self): |
| 178 | """Reset controller gate state.""" |
| 179 | self._is_from_outside = True |
| 180 | self._current_iteration = 0 |
| 181 | self._terminated = False |
| 182 | self.outsource_input = {} |