fabricatio 0.2.6.dev2__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.
@@ -10,6 +10,7 @@ from fabricatio._rust_instances import TEMPLATE_MANAGER
10
10
  from fabricatio.config import configs
11
11
  from fabricatio.fs.readers import MAGIKA, safe_text_read
12
12
  from fabricatio.journal import logger
13
+ from fabricatio.models.utils import ok
13
14
  from fabricatio.parser import JsonCapture
14
15
  from pydantic import (
15
16
  BaseModel,
@@ -19,6 +20,7 @@ from pydantic import (
19
20
  NonNegativeFloat,
20
21
  PositiveFloat,
21
22
  PositiveInt,
23
+ PrivateAttr,
22
24
  SecretStr,
23
25
  )
24
26
 
@@ -63,6 +65,44 @@ class Described(Base):
63
65
  """The description of the object."""
64
66
 
65
67
 
68
+ class AsPrompt(Base):
69
+ """Class that provides a method to generate a prompt from the model."""
70
+
71
+ @final
72
+ def as_prompt(self) -> str:
73
+ """Generate a prompt from the model.
74
+
75
+ Returns:
76
+ str: The generated prompt.
77
+ """
78
+ return TEMPLATE_MANAGER.render_template(
79
+ configs.templates.as_prompt_template,
80
+ self._as_prompt_inner(),
81
+ )
82
+
83
+ @abstractmethod
84
+ def _as_prompt_inner(self) -> Dict[str, str]: ...
85
+
86
+
87
+ class WithRef[T](Base):
88
+ """Class that provides a reference to another object."""
89
+
90
+ _reference: Optional[T] = PrivateAttr(None)
91
+
92
+ @property
93
+ def referenced(self) -> T:
94
+ """Get the referenced object."""
95
+ return ok(self._reference, "_reference is None")
96
+
97
+ def update_ref[S](self: S, reference: T | S) -> S: # noqa: PYI019
98
+ """Update the reference of the object."""
99
+ if isinstance(reference, self.__class__):
100
+ self._reference = reference.referenced
101
+ else:
102
+ self._reference = reference
103
+ return self
104
+
105
+
66
106
  class WithBriefing(Named, Described):
67
107
  """Class that provides a briefing based on the name and description."""
68
108
 
@@ -75,17 +115,26 @@ class WithBriefing(Named, Described):
75
115
  """
76
116
  return f"{self.name}: {self.description}" if self.description else self.name
77
117
 
78
- def prepend[D: Dict[str, Any]](self, kwargs: D) -> D:
79
- """Prepend the briefing to the system message in the kwargs.
118
+ def _prepend_inner(self, input_text: str) -> str:
119
+ return f"# your personal briefing: \n{self.briefing}\n{input_text}"
120
+
121
+ def prepend_sys_msg[D: (Dict[str, Any], str)](self, system_msg_like: D = "") -> Dict[str, Any]:
122
+ """Prepend the system message with the briefing.
80
123
 
81
124
  Args:
82
- kwargs (Dict[str, Any]): The keyword arguments to modify.
125
+ system_msg_like (str | dict): The system message or a dictionary containing the system message.
83
126
 
84
127
  Returns:
85
- Dict[str, Any]: The modified keyword arguments.
128
+ dict: The system message with the briefing prepended.
86
129
  """
87
- kwargs["system_message"] = f"# your personal briefing: \n{self.briefing}\n" + kwargs.get("system_message", "")
88
- return kwargs
130
+ match system_msg_like:
131
+ case dict(d):
132
+ d["system_message"] = self._prepend_inner(d.get("system_message", ""))
133
+ return d
134
+ case str(s):
135
+ return {"system_message": self._prepend_inner(s)}
136
+ case _:
137
+ raise TypeError(f"{system_msg_like} is not a dict or str")
89
138
 
90
139
 
91
140
  class WithFormatedJsonSchema(Base):
@@ -158,19 +207,17 @@ class InstantiateFromString(Base):
158
207
  class ProposedAble(CreateJsonObjPrompt, InstantiateFromString):
159
208
  """Class that provides a method to propose a JSON object based on the requirement."""
160
209
 
161
- pass
162
-
163
210
 
164
211
  class FinalizedDumpAble(Base):
165
212
  """Class that provides a method to finalize the dump of the object."""
166
213
 
167
- @abstractmethod
168
214
  def finalized_dump(self) -> str:
169
215
  """Finalize the dump of the object.
170
216
 
171
217
  Returns:
172
218
  str: The finalized dump of the object.
173
219
  """
220
+ return self.model_dump_json()
174
221
 
175
222
  def finalized_dump_to(self, path: str | Path) -> Self:
176
223
  """Finalize the dump of the object to a file.
@@ -185,6 +232,10 @@ class FinalizedDumpAble(Base):
185
232
  return self
186
233
 
187
234
 
235
+ class CensoredAble(ProposedAble, FinalizedDumpAble):
236
+ """Class that provides a method to censor the object."""
237
+
238
+
188
239
  class WithDependency(Base):
189
240
  """Class that manages file dependencies."""
190
241
 
@@ -1,19 +1,29 @@
1
1
  """This module contains the types for the keyword arguments of the methods in the models module."""
2
2
 
3
- from typing import Any, TypedDict
3
+ from importlib.util import find_spec
4
+ from typing import Any, Dict, Required, TypedDict
4
5
 
5
6
  from litellm.caching.caching import CacheMode
6
7
  from litellm.types.caching import CachingSupportedCallTypes
7
8
 
9
+ if find_spec("pymilvus"):
10
+ from pymilvus import CollectionSchema
11
+ from pymilvus.milvus_client import IndexParams
8
12
 
9
- class CollectionSimpleConfigKwargs(TypedDict, total=False):
10
- """Configuration parameters for a vector collection.
13
+ class CollectionConfigKwargs(TypedDict, total=False):
14
+ """Configuration parameters for a vector collection.
11
15
 
12
- These arguments are typically used when configuring connections to vector databases.
13
- """
16
+ These arguments are typically used when configuring connections to vector databases.
17
+ """
14
18
 
15
- dimension: int | None
16
- timeout: float
19
+ dimension: int | None
20
+ primary_field_name: str
21
+ id_type: str
22
+ vector_field_name: str
23
+ metric_type: str
24
+ timeout: float | None
25
+ schema: CollectionSchema | None
26
+ index_params: IndexParams | None
17
27
 
18
28
 
19
29
  class FetchKwargs(TypedDict, total=False):
@@ -28,6 +38,12 @@ class FetchKwargs(TypedDict, total=False):
28
38
  result_per_query: int
29
39
 
30
40
 
41
+ class RetrievalKwargs(FetchKwargs, total=False):
42
+ """Arguments for retrieval operations."""
43
+
44
+ final_limit: int
45
+
46
+
31
47
  class EmbeddingKwargs(TypedDict, total=False):
32
48
  """Configuration parameters for text embedding operations.
33
49
 
@@ -81,18 +97,25 @@ class ValidateKwargs[T](GenerateKwargs, total=False):
81
97
 
82
98
  default: T
83
99
  max_validations: int
100
+ co_extractor: GenerateKwargs
101
+
102
+
103
+ class ReviewInnerKwargs[T](ValidateKwargs[T], total=False):
104
+ """Arguments for content review operations."""
105
+
106
+ criteria: set[str]
84
107
 
85
108
 
86
109
  # noinspection PyTypedDict
87
- class ReviewKwargs[T](ValidateKwargs[T], total=False):
110
+ class ReviewKwargs[T](ReviewInnerKwargs[T], total=False):
88
111
  """Arguments for content review operations.
89
112
 
90
113
  Extends GenerateKwargs with parameters for evaluating content against
91
114
  specific topics and review criteria.
92
115
  """
93
116
 
94
- topic: str
95
- criteria: set[str]
117
+ rating_manual: Dict[str, str]
118
+ topic: Required[str]
96
119
 
97
120
 
98
121
  class CorrectKwargs[T](ReviewKwargs[T], total=False):
@@ -106,6 +129,13 @@ class CorrectKwargs[T](ReviewKwargs[T], total=False):
106
129
  supervisor_check: bool
107
130
 
108
131
 
132
+ class CensoredCorrectKwargs[T](ReviewInnerKwargs[T], total=False):
133
+ """Arguments for content censorship operations."""
134
+
135
+ reference: str
136
+ supervisor_check: bool
137
+
138
+
109
139
  # noinspection PyTypedDict
110
140
  class ChooseKwargs[T](ValidateKwargs[T], total=False):
111
141
  """Arguments for selection operations.
fabricatio/models/role.py CHANGED
@@ -1,4 +1,4 @@
1
- """Module that contains the Role class."""
1
+ """Module that contains the Role class for managing workflows and their event registrations."""
2
2
 
3
3
  from typing import Any, Self, Set
4
4
 
@@ -13,19 +13,36 @@ from pydantic import Field
13
13
 
14
14
 
15
15
  class Role(ProposeTask, HandleTask, Correct):
16
- """Class that represents a role with a registry of events and workflows."""
16
+ """Class that represents a role with a registry of events and workflows.
17
+
18
+ A Role serves as a container for workflows, managing their registration to events
19
+ and providing them with shared configuration like tools and personality.
20
+
21
+ Attributes:
22
+ registry: Mapping of events to workflows that handle them
23
+ toolboxes: Set of toolboxes available to this role and its workflows
24
+ """
17
25
 
18
26
  registry: dict[Event | str, WorkFlow] = Field(default_factory=dict)
19
- """ The registry of events and workflows."""
27
+ """The registry of events and workflows."""
20
28
 
21
29
  toolboxes: Set[ToolBox] = Field(default_factory=set)
30
+ """Collection of tools available to this role."""
22
31
 
23
32
  def model_post_init(self, __context: Any) -> None:
24
- """Register the workflows in the role to the event bus."""
33
+ """Initialize the role by resolving configurations and registering workflows.
34
+
35
+ Args:
36
+ __context: The context used for initialization
37
+ """
25
38
  self.resolve_configuration().register_workflows()
26
39
 
27
40
  def register_workflows(self) -> Self:
28
- """Register the workflows in the role to the event bus."""
41
+ """Register each workflow in the registry to its corresponding event in the event bus.
42
+
43
+ Returns:
44
+ Self: The role instance for method chaining
45
+ """
29
46
  for event, workflow in self.registry.items():
30
47
  logger.debug(
31
48
  f"Registering workflow: `{workflow.name}` for event: `{Event.instantiate_from(event).collapse()}`"
@@ -34,7 +51,14 @@ class Role(ProposeTask, HandleTask, Correct):
34
51
  return self
35
52
 
36
53
  def resolve_configuration(self) -> Self:
37
- """Resolve the configuration of the role."""
54
+ """Apply role-level configuration to all workflows in the registry.
55
+
56
+ This includes setting up fallback configurations, injecting personality traits,
57
+ and providing tool access to workflows and their steps.
58
+
59
+ Returns:
60
+ Self: The role instance for method chaining
61
+ """
38
62
  for workflow in self.registry.values():
39
63
  logger.debug(f"Resolving config for workflow: `{workflow.name}`")
40
64
  (
fabricatio/models/tool.py CHANGED
@@ -136,7 +136,9 @@ class ToolExecutor(BaseModel):
136
136
 
137
137
  def inject_tools[M: ModuleType](self, module: Optional[M] = None) -> M:
138
138
  """Inject the tools into the provided module or default."""
139
- module = module or cast(M, module_from_spec(spec=ModuleSpec(name=configs.toolbox.tool_module_name, loader=None)))
139
+ module = module or cast(
140
+ "M", module_from_spec(spec=ModuleSpec(name=configs.toolbox.tool_module_name, loader=None))
141
+ )
140
142
  for tool in self.candidates:
141
143
  logger.debug(f"Injecting tool: {tool.name}")
142
144
  setattr(module, tool.name, tool.invoke)
@@ -144,7 +146,9 @@ class ToolExecutor(BaseModel):
144
146
 
145
147
  def inject_data[M: ModuleType](self, module: Optional[M] = None) -> M:
146
148
  """Inject the data into the provided module or default."""
147
- module = module or cast(M,module_from_spec(spec=ModuleSpec(name=configs.toolbox.data_module_name, loader=None)))
149
+ module = module or cast(
150
+ 'M', module_from_spec(spec=ModuleSpec(name=configs.toolbox.data_module_name, loader=None))
151
+ )
148
152
  for key, value in self.data.items():
149
153
  logger.debug(f"Injecting data: {key}")
150
154
  setattr(module, key, value)