fabricatio 0.2.6.dev1__cp312-cp312-win_amd64.whl → 0.2.7.dev2__cp312-cp312-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,8 @@
1
- """Module that contains the classes for actions and workflows."""
1
+ """Module that contains the classes for actions and workflows.
2
+
3
+ This module defines the Action and WorkFlow classes, which are used for
4
+ creating and executing sequences of actions in a task-based context.
5
+ """
2
6
 
3
7
  import traceback
4
8
  from abc import abstractmethod
@@ -15,20 +19,27 @@ from pydantic import Field, PrivateAttr
15
19
 
16
20
 
17
21
  class Action(HandleTask, ProposeTask, Correct):
18
- """Class that represents an action to be executed in a workflow."""
22
+ """Class that represents an action to be executed in a workflow.
23
+
24
+ Actions are the atomic units of work in a workflow. Each action performs
25
+ a specific operation and can modify the shared context data.
26
+ """
19
27
 
20
28
  name: str = Field(default="")
21
29
  """The name of the action."""
30
+
22
31
  description: str = Field(default="")
23
32
  """The description of the action."""
33
+
24
34
  personality: str = Field(default="")
25
- """The personality of whom the action belongs to."""
35
+ """The personality traits or context for the action executor."""
36
+
26
37
  output_key: str = Field(default="")
27
- """The key of the output data."""
38
+ """The key used to store this action's output in the context dictionary."""
28
39
 
29
40
  @final
30
41
  def model_post_init(self, __context: Any) -> None:
31
- """Initialize the action by setting the name if not provided.
42
+ """Initialize the action by setting default name and description if not provided.
32
43
 
33
44
  Args:
34
45
  __context: The context to be used for initialization.
@@ -37,122 +48,185 @@ class Action(HandleTask, ProposeTask, Correct):
37
48
  self.description = self.description or self.__class__.__doc__ or ""
38
49
 
39
50
  @abstractmethod
40
- async def _execute(self, **cxt) -> Any:
41
- """Execute the action with the provided arguments.
51
+ async def _execute(self, *_, **cxt) -> Any: # noqa: ANN002
52
+ """Execute the action logic with the provided context arguments.
53
+
54
+ This method must be implemented by subclasses to define the actual behavior.
42
55
 
43
56
  Args:
44
57
  **cxt: The context dictionary containing input and output data.
45
58
 
46
59
  Returns:
47
- The result of the action execution.
60
+ Any: The result of the action execution.
48
61
  """
49
62
  pass
50
63
 
51
64
  @final
52
65
  async def act(self, cxt: Dict[str, Any]) -> Dict[str, Any]:
53
- """Perform the action by executing it and setting the output data.
66
+ """Perform the action and update the context with results.
54
67
 
55
68
  Args:
56
69
  cxt: The context dictionary containing input and output data.
70
+
71
+ Returns:
72
+ Dict[str, Any]: The updated context dictionary.
57
73
  """
58
74
  ret = await self._execute(**cxt)
75
+
59
76
  if self.output_key:
60
77
  logger.debug(f"Setting output: {self.output_key}")
61
78
  cxt[self.output_key] = ret
79
+
62
80
  return cxt
63
81
 
64
82
  @property
65
83
  def briefing(self) -> str:
66
- """Return a brief description of the action."""
84
+ """Return a formatted description of the action including personality context if available.
85
+
86
+ Returns:
87
+ str: Formatted briefing text with personality and action description.
88
+ """
67
89
  if self.personality:
68
90
  return f"## Your personality: \n{self.personality}\n# The action you are going to perform: \n{super().briefing}"
69
91
  return f"# The action you are going to perform: \n{super().briefing}"
70
92
 
71
93
 
72
94
  class WorkFlow(WithBriefing, ToolBoxUsage):
73
- """Class that represents a workflow to be executed in a task."""
95
+ """Class that represents a sequence of actions to be executed for a task.
96
+
97
+ A workflow manages the execution of multiple actions in sequence, passing
98
+ a shared context between them and handling task lifecycle events.
99
+ """
74
100
 
75
101
  _context: Queue[Dict[str, Any]] = PrivateAttr(default_factory=lambda: Queue(maxsize=1))
76
- """ The context dictionary to be used for workflow execution."""
102
+ """Queue for storing the workflow execution context."""
77
103
 
78
104
  _instances: Tuple[Action, ...] = PrivateAttr(default_factory=tuple)
79
- """ The instances of the workflow steps."""
105
+ """Instantiated action objects to be executed in this workflow."""
80
106
 
81
107
  steps: Tuple[Union[Type[Action], Action], ...] = Field(...)
82
- """ The steps to be executed in the workflow, actions or action classes."""
108
+ """The sequence of actions to be executed, can be action classes or instances."""
109
+
83
110
  task_input_key: str = Field(default="task_input")
84
- """ The key of the task input data."""
111
+ """Key used to store the input task in the context dictionary."""
112
+
85
113
  task_output_key: str = Field(default="task_output")
86
- """ The key of the task output data."""
114
+ """Key used to extract the final result from the context dictionary."""
115
+
87
116
  extra_init_context: Dict[str, Any] = Field(default_factory=dict, frozen=True)
88
- """ The extra context dictionary to be used for workflow initialization."""
117
+ """Additional initial context values to be included at workflow start."""
89
118
 
90
119
  def model_post_init(self, __context: Any) -> None:
91
- """Initialize the workflow by setting fallbacks for each step.
120
+ """Initialize the workflow by instantiating any action classes.
92
121
 
93
122
  Args:
94
123
  __context: The context to be used for initialization.
95
124
  """
96
- temp = []
97
- for step in self.steps:
98
- temp.append(step if isinstance(step, Action) else step())
99
- self._instances = tuple(temp)
125
+ # Convert any action classes to instances
126
+ self._instances = tuple(step if isinstance(step, Action) else step() for step in self.steps)
100
127
 
101
128
  def inject_personality(self, personality: str) -> Self:
102
- """Inject the personality of the workflow.
129
+ """Set the personality for all actions that don't have one defined.
103
130
 
104
131
  Args:
105
- personality: The personality to be injected.
132
+ personality: The personality text to inject.
106
133
 
107
134
  Returns:
108
- Self: The instance of the workflow with the injected personality.
135
+ Self: The workflow instance for method chaining.
109
136
  """
110
- for a in filter(lambda action: not action.personality, self._instances):
111
- a.personality = personality
137
+ for action in filter(lambda a: not a.personality, self._instances):
138
+ action.personality = personality
112
139
  return self
113
140
 
114
141
  async def serve(self, task: Task) -> None:
115
- """Serve the task by executing the workflow steps.
142
+ """Execute the workflow to fulfill the given task.
143
+
144
+ This method manages the complete lifecycle of processing a task through
145
+ the workflow's sequence of actions.
116
146
 
117
147
  Args:
118
- task: The task to be served.
148
+ task: The task to be processed.
119
149
  """
150
+ logger.info(f"Start execute workflow: {self.name}")
151
+
120
152
  await task.start()
121
153
  await self._init_context(task)
154
+
122
155
  current_action = None
123
156
  try:
157
+ # Process each action in sequence
124
158
  for step in self._instances:
125
- logger.debug(f"Executing step: {(current_action := step.name)}")
126
- act_task = create_task(step.act(await self._context.get()))
159
+ current_action = step.name
160
+ logger.info(f"Executing step: {current_action}")
161
+
162
+ # Get current context and execute action
163
+ context = await self._context.get()
164
+ act_task = create_task(step.act(context))
165
+ # Handle task cancellation
127
166
  if task.is_cancelled():
128
167
  act_task.cancel(f"Cancelled by task: {task.name}")
129
168
  break
169
+
170
+ # Update context with modified values
130
171
  modified_ctx = await act_task
172
+ logger.success(f"Step execution finished: {current_action}")
131
173
  await self._context.put(modified_ctx)
132
- logger.info(f"Finished executing workflow: {self.name}")
133
174
 
134
- if self.task_output_key not in (final_ctx := await self._context.get()):
175
+ logger.success(f"Workflow execution finished: {self.name}")
176
+
177
+ # Get final context and extract result
178
+ final_ctx = await self._context.get()
179
+ result = final_ctx.get(self.task_output_key)
180
+
181
+ if self.task_output_key not in final_ctx:
135
182
  logger.warning(
136
- f"Task output key: {self.task_output_key} not found in the context, None will be returned. You can check if `Action.output_key` is set the same as `WorkFlow.task_output_key`."
183
+ f"Task output key: {self.task_output_key} not found in the context, None will be returned. "
184
+ f"You can check if `Action.output_key` is set the same as `WorkFlow.task_output_key`."
137
185
  )
138
186
 
139
- await task.finish(final_ctx.get(self.task_output_key, None))
140
- except RuntimeError as e:
141
- logger.error(f"Error during task: {current_action} execution: {e}") # Log the exception
142
- logger.error(traceback.format_exc()) # Add this line to log the traceback
143
- await task.fail() # Mark the task as failed
187
+ await task.finish(result)
188
+
189
+ except Exception as e: # noqa: BLE001
190
+ logger.critical(f"Error during task: {current_action} execution: {e}")
191
+ logger.critical(traceback.format_exc())
192
+ await task.fail()
144
193
 
145
194
  async def _init_context[T](self, task: Task[T]) -> None:
146
- """Initialize the context dictionary for workflow execution."""
195
+ """Initialize the context dictionary for workflow execution.
196
+
197
+ Args:
198
+ task: The task being served by this workflow.
199
+ """
147
200
  logger.debug(f"Initializing context for workflow: {self.name}")
148
- await self._context.put({self.task_input_key: task, **dict(self.extra_init_context)})
201
+ initial_context = {self.task_input_key: task, **dict(self.extra_init_context)}
202
+ await self._context.put(initial_context)
149
203
 
150
204
  def steps_fallback_to_self(self) -> Self:
151
- """Set the fallback for each step to the workflow itself."""
205
+ """Configure all steps to use this workflow's configuration as fallback.
206
+
207
+ Returns:
208
+ Self: The workflow instance for method chaining.
209
+ """
152
210
  self.hold_to(self._instances)
153
211
  return self
154
212
 
155
213
  def steps_supply_tools_from_self(self) -> Self:
156
- """Supply the tools from the workflow to each step."""
214
+ """Provide this workflow's tools to all steps in the workflow.
215
+
216
+ Returns:
217
+ Self: The workflow instance for method chaining.
218
+ """
157
219
  self.provide_tools_to(self._instances)
158
220
  return self
221
+
222
+ def update_init_context(self, **kwargs) -> Self:
223
+ """Update the initial context with additional key-value pairs.
224
+
225
+ Args:
226
+ **kwargs: Key-value pairs to add to the initial context.
227
+
228
+ Returns:
229
+ Self: The workflow instance for method chaining.
230
+ """
231
+ self.extra_init_context.update(kwargs)
232
+ return self