fabricatio 0.3.13__cp312-cp312-win_amd64.whl → 0.3.14.dev0__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.
fabricatio/__init__.py CHANGED
@@ -3,32 +3,27 @@
3
3
  from fabricatio.rust import CONFIG, TEMPLATE_MANAGER, BibManager, Event
4
4
 
5
5
  from fabricatio import actions, capabilities, toolboxes, workflows
6
- from fabricatio.core import env
6
+ from fabricatio import parser
7
7
  from fabricatio.journal import logger
8
8
  from fabricatio.models import extra
9
9
  from fabricatio.models.action import Action, WorkFlow
10
10
  from fabricatio.models.role import Role
11
11
  from fabricatio.models.task import Task
12
12
  from fabricatio.models.tool import ToolBox
13
- from fabricatio.parser import Capture, GenericCapture, JsonCapture, PythonCapture
14
13
 
15
14
  __all__ = [
16
15
  "CONFIG",
17
16
  "TEMPLATE_MANAGER",
18
17
  "Action",
19
18
  "BibManager",
20
- "Capture",
19
+ "parser",
21
20
  "Event",
22
- "GenericCapture",
23
- "JsonCapture",
24
- "PythonCapture",
25
21
  "Role",
26
22
  "Task",
27
23
  "ToolBox",
28
24
  "WorkFlow",
29
25
  "actions",
30
26
  "capabilities",
31
- "env",
32
27
  "extra",
33
28
  "logger",
34
29
  "toolboxes",
@@ -12,14 +12,13 @@ Classes:
12
12
  import traceback
13
13
  from abc import abstractmethod
14
14
  from asyncio import Queue, create_task
15
- from typing import Any, ClassVar, Dict, Self, Sequence, Tuple, Type, Union, final
15
+ from typing import Any, ClassVar, Dict, Self, Sequence, Tuple, Type, Union, final, Generator
16
16
 
17
17
  from pydantic import Field, PrivateAttr
18
18
 
19
19
  from fabricatio.journal import logger
20
20
  from fabricatio.models.generic import WithBriefing
21
21
  from fabricatio.models.task import Task
22
- from fabricatio.models.usages import ToolBoxUsage
23
22
  from fabricatio.utils import override_kwargs
24
23
 
25
24
  OUTPUT_KEY = "task_output"
@@ -106,7 +105,7 @@ class Action(WithBriefing):
106
105
  return self
107
106
 
108
107
 
109
- class WorkFlow(WithBriefing, ToolBoxUsage):
108
+ class WorkFlow(WithBriefing):
110
109
  """Manages sequences of actions to fulfill tasks.
111
110
 
112
111
  Handles context propagation between actions, error handling, and task lifecycle
@@ -148,6 +147,10 @@ class WorkFlow(WithBriefing, ToolBoxUsage):
148
147
  # Convert any action classes to instances
149
148
  self._instances = tuple(step if isinstance(step, Action) else step() for step in self.steps)
150
149
 
150
+ def iter_actions(self) -> Generator[Action, None, None]:
151
+ """Iterate over action instances."""
152
+ yield from self._instances
153
+
151
154
  def inject_personality(self, personality: str) -> Self:
152
155
  """Set personality for actions without existing personality.
153
156
 
@@ -249,24 +252,6 @@ class WorkFlow(WithBriefing, ToolBoxUsage):
249
252
 
250
253
  await self._context.put({self.task_input_key: task, **ctx})
251
254
 
252
- def steps_fallback_to_self(self) -> Self:
253
- """Configure all steps to use this workflow's configuration as fallback.
254
-
255
- Returns:
256
- Self: The workflow instance for method chaining.
257
- """
258
- self.hold_to(self._instances)
259
- return self
260
-
261
- def steps_supply_tools_from_self(self) -> Self:
262
- """Provide this workflow's tools to all steps in the workflow.
263
-
264
- Returns:
265
- Self: The workflow instance for method chaining.
266
- """
267
- self.provide_tools_to(i for i in self._instances if isinstance(i, ToolBoxUsage))
268
- return self
269
-
270
255
  def update_init_context(self, /, **kwargs) -> Self:
271
256
  """Update the initial context with additional key-value pairs.
272
257
 
@@ -7,7 +7,6 @@ from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Self,
7
7
 
8
8
  import ujson
9
9
  from fabricatio.rust import CONFIG, TEMPLATE_MANAGER, blake3_hash, detect_language
10
- from litellm.utils import token_counter
11
10
  from pydantic import (
12
11
  BaseModel,
13
12
  ConfigDict,
@@ -666,6 +665,8 @@ class Vectorizable:
666
665
  Raises:
667
666
  ValueError: If the chunk exceeds the maximum sequence length.
668
667
  """
668
+ from litellm.utils import token_counter
669
+
669
670
  max_length = max_length or CONFIG.embedding.max_sequence_length
670
671
  chunk = self._prepare_vectorization_inner()
671
672
  if max_length and (length := token_counter(text=chunk)) > max_length:
@@ -1,9 +1,6 @@
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, Dict, List, Literal, NotRequired, Optional, Required, TypedDict
4
-
5
- from litellm.caching.caching import CacheMode
6
- from litellm.types.caching import CachingSupportedCallTypes
3
+ from typing import Dict, List, Literal, NotRequired, Optional, Required, TypedDict
7
4
 
8
5
 
9
6
  class ChunkKwargs(TypedDict):
@@ -70,7 +67,6 @@ class ValidateKwargs[T](GenerateKwargs, total=False):
70
67
  max_validations: int
71
68
 
72
69
 
73
-
74
70
  class CompositeScoreKwargs(ValidateKwargs[List[Dict[str, float]]], total=False):
75
71
  """Arguments for composite score generation operations.
76
72
 
@@ -125,47 +121,6 @@ class ChooseKwargs[T](ValidateKwargs[T], total=False):
125
121
  k: int
126
122
 
127
123
 
128
- class CacheKwargs(TypedDict, total=False):
129
- """Configuration parameters for the caching system.
130
-
131
- These arguments control the behavior of various caching backends,
132
- including in-memory, Redis, S3, and vector database caching options.
133
- """
134
-
135
- mode: CacheMode # when default_on cache is always on, when default_off cache is opt in
136
- host: str
137
- port: str
138
- password: str
139
- namespace: str
140
- ttl: float
141
- default_in_memory_ttl: float
142
- default_in_redis_ttl: float
143
- similarity_threshold: float
144
- supported_call_types: list[CachingSupportedCallTypes]
145
- # s3 Bucket, boto3 configuration
146
- s3_bucket_name: str
147
- s3_region_name: str
148
- s3_api_version: str
149
- s3_use_ssl: bool
150
- s3_verify: bool | str
151
- s3_endpoint_url: str
152
- s3_aws_access_key_id: str
153
- s3_aws_secret_access_key: str
154
- s3_aws_session_token: str
155
- s3_config: Any
156
- s3_path: str
157
- redis_semantic_cache_use_async: bool
158
- redis_semantic_cache_embedding_model: str
159
- redis_flush_size: int
160
- redis_startup_nodes: list
161
- disk_cache_dir: Any
162
- qdrant_api_base: str
163
- qdrant_api_key: str
164
- qdrant_collection_name: str
165
- qdrant_quantization_config: str
166
- qdrant_semantic_cache_embedding_model: str
167
-
168
-
169
124
  class RerankOptions(TypedDict, total=False):
170
125
  """Optional keyword arguments for the rerank method."""
171
126
 
fabricatio/models/role.py CHANGED
@@ -1,40 +1,35 @@
1
1
  """Module that contains the Role class for managing workflows and their event registrations."""
2
-
3
- from typing import Any, Self, Set
2
+ from functools import partial
3
+ from typing import Any, Self, Dict
4
4
 
5
5
  from fabricatio.rust import Event
6
6
  from pydantic import Field, ConfigDict
7
7
 
8
- from fabricatio.capabilities.propose import Propose
9
8
  from fabricatio.core import env
10
9
  from fabricatio.journal import logger
11
10
  from fabricatio.models.action import WorkFlow
12
11
  from fabricatio.models.generic import WithBriefing
13
- from fabricatio.models.tool import ToolBox
14
- from fabricatio.models.usages import ToolBoxUsage
12
+ from fabricatio.utils import is_subclass_of_base
13
+
14
+ is_toolbox_usage = partial(is_subclass_of_base, base_module="fabricatio.models.usages",
15
+ base_name="ToolBoxUsage")
16
+ is_scoped_config = partial(is_subclass_of_base, base_module="fabricatio.models.generic",
17
+ base_name="ScopedConfig")
15
18
 
16
19
 
17
- class Role(WithBriefing, Propose, ToolBoxUsage):
20
+ class Role(WithBriefing):
18
21
  """Class that represents a role with a registry of events and workflows.
19
22
 
20
23
  A Role serves as a container for workflows, managing their registration to events
21
24
  and providing them with shared configuration like tools and personality.
22
-
23
- Attributes:
24
- registry: Mapping of events to workflows that handle them
25
- toolboxes: Set of toolboxes available to this role and its workflows
26
25
  """
27
- # fixme: not use arbitrary_types_allowed
28
26
  model_config = ConfigDict(use_attribute_docstrings=True, arbitrary_types_allowed=True)
29
27
  description: str = ""
30
28
  """A brief description of the role's responsibilities and capabilities."""
31
29
 
32
- registry: dict[Event | str, WorkFlow] = Field(default_factory=dict)
30
+ registry: Dict[Event, WorkFlow] = Field(default_factory=dict)
33
31
  """The registry of events and workflows."""
34
32
 
35
- toolboxes: Set[ToolBox] = Field(default_factory=set)
36
- """Collection of tools available to this role."""
37
-
38
33
  def model_post_init(self, __context: Any) -> None:
39
34
  """Initialize the role by resolving configurations and registering workflows.
40
35
 
@@ -51,7 +46,7 @@ class Role(WithBriefing, Propose, ToolBoxUsage):
51
46
  """
52
47
  for event, workflow in self.registry.items():
53
48
  logger.debug(
54
- f"Registering workflow: `{workflow.name}` for event: `{Event.instantiate_from(event).collapse()}`"
49
+ f"Registering workflow: `{workflow.name}` for event: `{event.collapse()}`"
55
50
  )
56
51
  env.on(event, workflow.serve)
57
52
  return self
@@ -67,12 +62,35 @@ class Role(WithBriefing, Propose, ToolBoxUsage):
67
62
  """
68
63
  for workflow in self.registry.values():
69
64
  logger.debug(f"Resolving config for workflow: `{workflow.name}`")
70
- (
71
- workflow.fallback_to(self)
72
- .steps_fallback_to_self()
73
- .inject_personality(self.briefing)
74
- .supply_tools_from(self)
75
- .steps_supply_tools_from_self()
76
- )
77
-
65
+ self._configure_scoped_config(workflow)
66
+ self._configure_toolbox_usage(workflow)
67
+ workflow.inject_personality(self.briefing)
78
68
  return self
69
+
70
+ def _configure_scoped_config(self, workflow) -> None:
71
+ """Configure scoped configuration for workflow and its actions."""
72
+
73
+ if not is_scoped_config(self.__class__):
74
+ return
75
+
76
+ fallback_target = self
77
+ if is_scoped_config(workflow):
78
+ workflow.fallback_to(self)
79
+ fallback_target = workflow
80
+
81
+ for action in (a for a in workflow.iter_actions() if is_scoped_config(a)):
82
+ action.fallback_to(fallback_target)
83
+
84
+ def _configure_toolbox_usage(self, workflow) -> None:
85
+ """Configure toolbox usage for workflow and its actions."""
86
+
87
+ if not is_toolbox_usage(self.__class__):
88
+ return
89
+
90
+ supply_target = self
91
+ if is_toolbox_usage(workflow):
92
+ workflow.supply_tools_from(self)
93
+ supply_target = workflow
94
+
95
+ for action in (a for a in workflow.iter_actions() if is_toolbox_usage(a)):
96
+ action.supply_tools_from(supply_target)
Binary file
fabricatio/utils.py CHANGED
@@ -1,15 +1,46 @@
1
1
  """A collection of utility functions for the fabricatio package."""
2
2
 
3
- from typing import Any, Dict, List, Mapping, Optional, TypedDict, Unpack, overload
4
-
5
- import aiohttp
6
- import requests
3
+ from typing import Any, Dict, List, Mapping, Optional, TypedDict, Unpack, overload, Type, Tuple
7
4
 
8
5
  from fabricatio.decorators import precheck_package
9
6
  from fabricatio.journal import logger
10
7
  from fabricatio.models.kwargs_types import RerankOptions
11
8
 
12
9
 
10
+ def is_subclass_of_base(cls: Type, base_module: str, base_name: str) -> bool:
11
+ """Determines if the given class is a subclass of an unimported base class.
12
+
13
+ Args:
14
+ cls: The class to check
15
+ base_module: The module name of the base class
16
+ base_name: The class name of the base class
17
+
18
+ Returns:
19
+ bool: True if cls is a subclass of the specified base class, False otherwise
20
+ """
21
+ for ancestor in cls.__mro__:
22
+ if ancestor.__module__ == base_module and ancestor.__name__ == base_name:
23
+ return True
24
+ return False
25
+
26
+
27
+ def is_subclass_of_any_base(cls: Type, bases: List[Tuple[str, str]]) -> bool:
28
+ """Determines if the given class is a subclass of the candidate base classes.
29
+
30
+ Args:
31
+ cls: The class to check
32
+ bases: A list of tuples where each tuple contains (module_name, class_name)
33
+
34
+ Returns:
35
+ bool: True if cls is a subclass of the specified base classes, False otherwise
36
+ """
37
+ for ancestor in cls.__mro__:
38
+ for base_module, base_name in bases:
39
+ if ancestor.__module__ == base_module and ancestor.__name__ == base_name:
40
+ return True
41
+ return False
42
+
43
+
13
44
  @precheck_package(
14
45
  "questionary", "'questionary' is required to run this function. Have you installed `fabricatio[qa]`?."
15
46
  )
@@ -164,6 +195,7 @@ class RerankerAPI:
164
195
  ValueError: If input parameters are invalid or the API returns a client-side error.
165
196
  RuntimeError: If the API call fails or returns a server-side error.
166
197
  """
198
+ import requests
167
199
  # Validate inputs
168
200
  if not isinstance(query, str) or not query.strip():
169
201
  raise ValueError("Query must be a non-empty string.")
@@ -219,6 +251,8 @@ class RerankerAPI:
219
251
  ValueError: If input parameters are invalid or the API returns a client-side error.
220
252
  RuntimeError: If the API call fails or returns a server-side error.
221
253
  """
254
+ import aiohttp
255
+
222
256
  # Validate inputs
223
257
  if not isinstance(query, str) or not query.strip():
224
258
  raise ValueError("Query must be a non-empty string.")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fabricatio
3
- Version: 0.3.13
3
+ Version: 0.3.14.dev0
4
4
  Classifier: License :: OSI Approved :: MIT License
5
5
  Classifier: Programming Language :: Rust
6
6
  Classifier: Programming Language :: Python :: 3.12
@@ -1,6 +1,6 @@
1
- fabricatio-0.3.13.dist-info/METADATA,sha256=x8-6ILA6zUw7fVZQ9ENH_KSspPWqd6R90e2fflasNBg,5241
2
- fabricatio-0.3.13.dist-info/WHEEL,sha256=jABKVkLC9kJr8mi_er5jOqpiQUjARSLXDUIIxDqsS50,96
3
- fabricatio-0.3.13.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
1
+ fabricatio-0.3.14.dev0.dist-info/METADATA,sha256=wYdyUN-54xDS1x4TkCPzO8tQ8XZKmMOz5O33vlSWGSg,5246
2
+ fabricatio-0.3.14.dev0.dist-info/WHEEL,sha256=jABKVkLC9kJr8mi_er5jOqpiQUjARSLXDUIIxDqsS50,96
3
+ fabricatio-0.3.14.dev0.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
4
4
  fabricatio/actions/article.py,sha256=vkYbzRy4SSJL73SFdgdsMfUy3nbjNFc44mu1-uPjqBo,12627
5
5
  fabricatio/actions/article_rag.py,sha256=Ahij8TSNvE5T1rHhJM5zNj57SaORldNj1YEHFTj0xm8,18631
6
6
  fabricatio/actions/fs.py,sha256=gJR14U4ln35nt8Z7OWLVAZpqGaLnED-r1Yi-lX22tkI,959
@@ -26,7 +26,7 @@ fabricatio/fs/curd.py,sha256=652nHulbJ3gwt0Z3nywtPMmjhEyglDvEfc3p7ieJNNA,4777
26
26
  fabricatio/fs/readers.py,sha256=UXvcJO3UCsxHu9PPkg34Yh55Zi-miv61jD_wZQJgKRs,1751
27
27
  fabricatio/fs/__init__.py,sha256=USoMI_HcIr3Yc77_JQYYsXrsplYPXtFTaNB9YgFfC4s,713
28
28
  fabricatio/journal.py,sha256=I02_ntN7_WyI_m1RsHB1gEv8LfWtcVGmOqppEV8XjKI,289
29
- fabricatio/models/action.py,sha256=X29OWzMTLUkcRmFWFgcMG3SDj7l7OlRSObviMYeXUIM,10611
29
+ fabricatio/models/action.py,sha256=-XIzuE-LE38GWuj_0WdSGSQ7kVUMzXUUnfqJ-XcA20o,10084
30
30
  fabricatio/models/adv_kwargs_types.py,sha256=IBV3ZcsNLvvEjO_2hBpYg_wLSpNKaMx6Ndam3qXJCw8,2097
31
31
  fabricatio/models/extra/advanced_judge.py,sha256=INUl_41C8jkausDekkjnEmTwNfLCJ23TwFjq2cM23Cw,1092
32
32
  fabricatio/models/extra/aricle_rag.py,sha256=2dHQOz7Br8xpf3PTtdZmrIw49kC4_YGa89evta67LYg,11707
@@ -40,9 +40,9 @@ fabricatio/models/extra/problem.py,sha256=8tTU-3giFHOi5j7NJsvH__JJyYcaGrcfsRnkzQ
40
40
  fabricatio/models/extra/rag.py,sha256=RMi8vhEPB0I5mVmjRLRLxYHUnm9pFhvVwysaIwmW2s0,3955
41
41
  fabricatio/models/extra/rule.py,sha256=KQQELVhCLUXhEZ35jU3WGYqKHuCYEAkn0p6pxAE-hOU,2625
42
42
  fabricatio/models/extra/__init__.py,sha256=XlYnS_2B9nhLhtQkjE7rvvfPmAAtXVdNi9bSDAR-Ge8,54
43
- fabricatio/models/generic.py,sha256=qqMJBckUdWqGv5iegLtYamfIATePoTlywadNa3JEZy8,30414
44
- fabricatio/models/kwargs_types.py,sha256=gIvLSof3XE-B0cGE5d1BrOQB1HO8Pd666_scd-9JaF4,5000
45
- fabricatio/models/role.py,sha256=UlEtpeBBqF4_uXhloqeevLS17aOtAeg2Q0vmd45vQpk,3072
43
+ fabricatio/models/generic.py,sha256=c-_VogsBUbNaU11KZizCI4AzLgg5_FCRLbNYcQKHyks,30424
44
+ fabricatio/models/kwargs_types.py,sha256=tDeF0B_TnumYGCKU58f-llAApn6ng_Joz8CcGq5GiLk,3619
45
+ fabricatio/models/role.py,sha256=Uukgh3Nxk5N2QEnyg9CMfsngW9GSgKV_Z7nnvafUYfc,3810
46
46
  fabricatio/models/task.py,sha256=vOL8mzwBRMWC8R_59zh4SDXkjWuAL6WTtsAGfcxp_eE,11032
47
47
  fabricatio/models/tool.py,sha256=uNYVCNr9KUBWQ_KAtekGECdNPZREGJ9Aioyk4lrvtTE,12503
48
48
  fabricatio/models/usages.py,sha256=FyWdKAce2Am10zByISBuf_Tdd4hRnhkAxcXIzyV77LU,33474
@@ -52,12 +52,12 @@ fabricatio/rust.pyi,sha256=fWK5q3b-TEDfSYQh9vlZq-kTpA9NBXttGszPMVEnODs,25221
52
52
  fabricatio/toolboxes/arithmetic.py,sha256=WLqhY-Pikv11Y_0SGajwZx3WhsLNpHKf9drzAqOf_nY,1369
53
53
  fabricatio/toolboxes/fs.py,sha256=l4L1CVxJmjw9Ld2XUpIlWfV0_Fu_2Og6d3E13I-S4aE,736
54
54
  fabricatio/toolboxes/__init__.py,sha256=KBJi5OG_pExscdlM7Bnt_UF43j4I3Lv6G71kPVu4KQU,395
55
- fabricatio/utils.py,sha256=IBKfs2Rg3bJnazzvj1-Fz1rMWNKhiuQG5_rZ1nxQeMI,10299
55
+ fabricatio/utils.py,sha256=_kNYzLzBudhjZ3RwgeIPKSxKbOVMgCwoj-BzjYPB0G8,11566
56
56
  fabricatio/workflows/articles.py,sha256=ObYTFUqLUk_CzdmmnX6S7APfxcGmPFqnFr9pdjU7Z4Y,969
57
57
  fabricatio/workflows/rag.py,sha256=-YYp2tlE9Vtfgpg6ROpu6QVO8j8yVSPa6yDzlN3qVxs,520
58
58
  fabricatio/workflows/__init__.py,sha256=5ScFSTA-bvhCesj3U9Mnmi6Law6N1fmh5UKyh58L3u8,51
59
- fabricatio/__init__.py,sha256=pNEikVxeJF3KD1z8U4Z9U7NVL8-2RE6WNOKIH9c83mY,972
60
- fabricatio/rust.cp312-win_amd64.pyd,sha256=5x-26VvrnKgGHbYpirikKS5ZqA7bDc8xGNODnPru1aQ,6016512
61
- fabricatio-0.3.13.data/scripts/tdown.exe,sha256=9maLvPkwy5oQsA7fvEcJy_7U1l43wSubMB-MudebYus,3357184
62
- fabricatio-0.3.13.data/scripts/ttm.exe,sha256=_cFlVm0Xz6eo1v_rz7swwZ6ghOZ4BGj9pg9Hvn0Hig8,2553856
63
- fabricatio-0.3.13.dist-info/RECORD,,
59
+ fabricatio/__init__.py,sha256=QoZ1WNvK5UVaMGed2GOE781TvF76om3LHe5eVEBSSUE,809
60
+ fabricatio/rust.cp312-win_amd64.pyd,sha256=lvRcjPuXO8XglnZ9J7QX4AJx1z7Zfj13Msia4orfs-A,6022144
61
+ fabricatio-0.3.14.dev0.data/scripts/tdown.exe,sha256=dNcSMR1zfpD8t_QYEP0xfqCfEZZ1P1EBWYOxroxTWSU,3356160
62
+ fabricatio-0.3.14.dev0.data/scripts/ttm.exe,sha256=Q4kRd27t8Fv--kYuoHqhK0NyvFt2jCY8Q11vrWDa2z0,2554880
63
+ fabricatio-0.3.14.dev0.dist-info/RECORD,,
Binary file
Binary file