fabricatio 0.2.13.dev3__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.
Files changed (42) hide show
  1. fabricatio/__init__.py +5 -10
  2. fabricatio/actions/article.py +32 -34
  3. fabricatio/actions/article_rag.py +58 -58
  4. fabricatio/actions/output.py +22 -21
  5. fabricatio/actions/rag.py +4 -3
  6. fabricatio/capabilities/check.py +29 -30
  7. fabricatio/capabilities/correct.py +23 -23
  8. fabricatio/capabilities/extract.py +36 -32
  9. fabricatio/capabilities/rag.py +34 -35
  10. fabricatio/capabilities/rating.py +77 -72
  11. fabricatio/capabilities/review.py +12 -11
  12. fabricatio/capabilities/task.py +4 -5
  13. fabricatio/core.py +22 -24
  14. fabricatio/decorators.py +10 -10
  15. fabricatio/fs/__init__.py +1 -2
  16. fabricatio/journal.py +2 -9
  17. fabricatio/models/action.py +8 -22
  18. fabricatio/models/extra/aricle_rag.py +10 -9
  19. fabricatio/models/extra/article_base.py +5 -6
  20. fabricatio/models/extra/article_main.py +11 -10
  21. fabricatio/models/generic.py +33 -60
  22. fabricatio/models/kwargs_types.py +1 -46
  23. fabricatio/models/role.py +45 -25
  24. fabricatio/models/task.py +9 -9
  25. fabricatio/models/tool.py +5 -4
  26. fabricatio/models/usages.py +170 -161
  27. fabricatio/parser.py +2 -2
  28. fabricatio/rust.cp312-win_amd64.pyd +0 -0
  29. fabricatio/rust.pyi +435 -17
  30. fabricatio/utils.py +38 -4
  31. fabricatio-0.3.14.dev0.data/scripts/tdown.exe +0 -0
  32. {fabricatio-0.2.13.dev3.data → fabricatio-0.3.14.dev0.data}/scripts/ttm.exe +0 -0
  33. {fabricatio-0.2.13.dev3.dist-info → fabricatio-0.3.14.dev0.dist-info}/METADATA +1 -3
  34. fabricatio-0.3.14.dev0.dist-info/RECORD +63 -0
  35. fabricatio/config.py +0 -430
  36. fabricatio/constants.py +0 -20
  37. fabricatio/models/events.py +0 -120
  38. fabricatio/rust_instances.py +0 -10
  39. fabricatio-0.2.13.dev3.data/scripts/tdown.exe +0 -0
  40. fabricatio-0.2.13.dev3.dist-info/RECORD +0 -67
  41. {fabricatio-0.2.13.dev3.dist-info → fabricatio-0.3.14.dev0.dist-info}/WHEEL +0 -0
  42. {fabricatio-0.2.13.dev3.dist-info → fabricatio-0.3.14.dev0.dist-info}/licenses/LICENSE +0 -0
@@ -6,14 +6,7 @@ from pathlib import Path
6
6
  from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Self, Type, Union, final, overload
7
7
 
8
8
  import ujson
9
- from fabricatio.config import configs
10
- from fabricatio.fs.readers import safe_text_read
11
- from fabricatio.journal import logger
12
- from fabricatio.parser import JsonCapture
13
- from fabricatio.rust import blake3_hash, detect_language
14
- from fabricatio.rust_instances import TEMPLATE_MANAGER
15
- from fabricatio.utils import ok
16
- from litellm.utils import token_counter
9
+ from fabricatio.rust import CONFIG, TEMPLATE_MANAGER, blake3_hash, detect_language
17
10
  from pydantic import (
18
11
  BaseModel,
19
12
  ConfigDict,
@@ -27,6 +20,12 @@ from pydantic import (
27
20
  )
28
21
  from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
29
22
 
23
+ from fabricatio.fs import dump_text
24
+ from fabricatio.fs.readers import safe_text_read
25
+ from fabricatio.journal import logger
26
+ from fabricatio.parser import JsonCapture
27
+ from fabricatio.utils import ok
28
+
30
29
 
31
30
  class Base(BaseModel):
32
31
  """Base class for all models with Pydantic configuration.
@@ -74,9 +73,9 @@ class Display(Base):
74
73
  str: Combined display output with boundary markers
75
74
  """
76
75
  return (
77
- "--- Start of Extra Info Sequence ---"
78
- + "\n".join(d.compact() if compact else d.display() for d in seq)
79
- + "--- End of Extra Info Sequence ---"
76
+ "--- Start of Extra Info Sequence ---"
77
+ + "\n".join(d.compact() if compact else d.display() for d in seq)
78
+ + "--- End of Extra Info Sequence ---"
80
79
  )
81
80
 
82
81
 
@@ -117,7 +116,7 @@ class WordCount(Base):
117
116
  """Expected word count of this research component."""
118
117
 
119
118
 
120
- class FromMapping(Base):
119
+ class FromMapping:
121
120
  """Class that provides a method to generate a list of objects from a mapping."""
122
121
 
123
122
  @classmethod
@@ -126,7 +125,7 @@ class FromMapping(Base):
126
125
  """Generate a list of objects from a mapping."""
127
126
 
128
127
 
129
- class AsPrompt(Base):
128
+ class AsPrompt:
130
129
  """Class that provides a method to generate a prompt from the model.
131
130
 
132
131
  This class includes a method to generate a prompt based on the model's attributes.
@@ -140,7 +139,7 @@ class AsPrompt(Base):
140
139
  str: The generated prompt.
141
140
  """
142
141
  return TEMPLATE_MANAGER.render_template(
143
- configs.templates.as_prompt_template,
142
+ CONFIG.templates.as_prompt_template,
144
143
  self._as_prompt_inner(),
145
144
  )
146
145
 
@@ -178,13 +177,16 @@ class WithRef[T](Base):
178
177
  )
179
178
 
180
179
  @overload
181
- def update_ref[S: WithRef](self: S, reference: T) -> S: ...
180
+ def update_ref[S: WithRef](self: S, reference: T) -> S:
181
+ ...
182
182
 
183
183
  @overload
184
- def update_ref[S: WithRef](self: S, reference: "WithRef[T]") -> S: ...
184
+ def update_ref[S: WithRef](self: S, reference: "WithRef[T]") -> S:
185
+ ...
185
186
 
186
187
  @overload
187
- def update_ref[S: WithRef](self: S, reference: None = None) -> S: ...
188
+ def update_ref[S: WithRef](self: S, reference: None = None) -> S:
189
+ ...
188
190
 
189
191
  def update_ref[S: WithRef](self: S, reference: Union[T, "WithRef[T]", None] = None) -> S:
190
192
  """Update the reference of the object.
@@ -201,19 +203,6 @@ class WithRef[T](Base):
201
203
  self._reference = reference # pyright: ignore [reportAttributeAccessIssue]
202
204
  return self
203
205
 
204
- def derive[S: WithRef](self: S, reference: Any) -> S:
205
- """Derive a new object from the current object.
206
-
207
- Args:
208
- reference (Any): The reference for the new object.
209
-
210
- Returns:
211
- S: A new instance derived from the current object with the provided reference.
212
- """
213
- new = self.model_copy()
214
- new._reference = reference
215
- return new
216
-
217
206
 
218
207
  class PersistentAble(Base):
219
208
  """Class providing file persistence capabilities.
@@ -306,7 +295,7 @@ class PersistentAble(Base):
306
295
  return cls.model_validate_json(safe_text_read(path))
307
296
 
308
297
 
309
- class Language(Base):
298
+ class Language:
310
299
  """Class that provides a language attribute."""
311
300
 
312
301
  @property
@@ -318,8 +307,7 @@ class Language(Base):
318
307
  return detect_language(self.title)
319
308
  if isinstance(self, Named) and self.name:
320
309
  return detect_language(self.name)
321
-
322
- return detect_language(self.model_dump_json(by_alias=True))
310
+ raise RuntimeError(f"Cannot determine language! class that not support language: {self.__class__.__name__}")
323
311
 
324
312
 
325
313
  class ModelHash(Base):
@@ -337,7 +325,7 @@ class ModelHash(Base):
337
325
  return hash(self.model_dump_json())
338
326
 
339
327
 
340
- class UpdateFrom(Base):
328
+ class UpdateFrom:
341
329
  """Class that provides a method to update the object from another object.
342
330
 
343
331
  This class includes methods to update the current object with the attributes of another object.
@@ -386,25 +374,7 @@ class UpdateFrom(Base):
386
374
  return self.update_pre_check(other).update_from_inner(other)
387
375
 
388
376
 
389
- class ResolveUpdateConflict(Base):
390
- """Class that provides a method to update the object from another object.
391
-
392
- This class includes a method to resolve conflicts when updating the object from another object.
393
- """
394
-
395
- @abstractmethod
396
- def resolve_update_conflict(self, other: Self) -> str:
397
- """Resolve the update conflict between two objects.
398
-
399
- Args:
400
- other (Self): The other object to resolve the update conflict with.
401
-
402
- Returns:
403
- str: The resolved update conflict.
404
- """
405
-
406
-
407
- class Introspect(Base):
377
+ class Introspect:
408
378
  """Class that provides a method to introspect the object.
409
379
 
410
380
  This class includes a method to perform internal introspection of the object.
@@ -498,12 +468,12 @@ class CreateJsonObjPrompt(WithFormatedJsonSchema):
498
468
  """
499
469
  if isinstance(requirement, str):
500
470
  return TEMPLATE_MANAGER.render_template(
501
- configs.templates.create_json_obj_template,
471
+ CONFIG.templates.create_json_obj_template,
502
472
  {"requirement": requirement, "json_schema": cls.formated_json_schema()},
503
473
  )
504
474
  return [
505
475
  TEMPLATE_MANAGER.render_template(
506
- configs.templates.create_json_obj_template,
476
+ CONFIG.templates.create_json_obj_template,
507
477
  {"requirement": r, "json_schema": cls.formated_json_schema()},
508
478
  )
509
479
  for r in requirement
@@ -575,7 +545,7 @@ class FinalizedDumpAble(Base):
575
545
  Returns:
576
546
  Self: The current instance of the object.
577
547
  """
578
- Path(path).write_text(self.finalized_dump(), encoding="utf-8")
548
+ dump_text(path, self.finalized_dump())
579
549
  return self
580
550
 
581
551
 
@@ -655,7 +625,7 @@ class WithDependency(Base):
655
625
  from fabricatio.fs import MAGIKA
656
626
 
657
627
  return TEMPLATE_MANAGER.render_template(
658
- configs.templates.dependencies_template,
628
+ CONFIG.templates.dependencies_template,
659
629
  {
660
630
  (pth := Path(p)).name: {
661
631
  "path": pth.as_posix(),
@@ -672,7 +642,7 @@ class WithDependency(Base):
672
642
  )
673
643
 
674
644
 
675
- class Vectorizable(Base):
645
+ class Vectorizable:
676
646
  """Class that prepares the vectorization of the model.
677
647
 
678
648
  This class includes methods to prepare the model for vectorization, ensuring it fits within a specified token length.
@@ -695,7 +665,9 @@ class Vectorizable(Base):
695
665
  Raises:
696
666
  ValueError: If the chunk exceeds the maximum sequence length.
697
667
  """
698
- max_length = max_length or configs.embedding.max_sequence_length
668
+ from litellm.utils import token_counter
669
+
670
+ max_length = max_length or CONFIG.embedding.max_sequence_length
699
671
  chunk = self._prepare_vectorization_inner()
700
672
  if max_length and (length := token_counter(text=chunk)) > max_length:
701
673
  raise ValueError(f"Chunk exceeds maximum sequence length {max_length}, got {length}, see \n{chunk}")
@@ -883,7 +855,8 @@ class Patch[T](ProposedAble):
883
855
  # copy the desc info of each corresponding fields from `ref_cls`
884
856
  for field_name in [f for f in cls.model_fields if f in ref_cls.model_fields]:
885
857
  my_schema["properties"][field_name]["description"] = (
886
- ref_cls.model_fields[field_name].description or my_schema["properties"][field_name]["description"]
858
+ ref_cls.model_fields[field_name].description or my_schema["properties"][field_name][
859
+ "description"]
887
860
  )
888
861
  my_schema["description"] = ref_cls.__doc__
889
862
 
@@ -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,38 +1,35 @@
1
1
  """Module that contains the Role class for managing workflows and their event registrations."""
2
+ from functools import partial
3
+ from typing import Any, Self, Dict
2
4
 
3
- from typing import Any, Self, Set
5
+ from fabricatio.rust import Event
6
+ from pydantic import Field, ConfigDict
4
7
 
5
- from fabricatio.capabilities.propose import Propose
6
8
  from fabricatio.core import env
7
9
  from fabricatio.journal import logger
8
10
  from fabricatio.models.action import WorkFlow
9
- from fabricatio.models.events import Event
10
11
  from fabricatio.models.generic import WithBriefing
11
- from fabricatio.models.tool import ToolBox
12
- from fabricatio.models.usages import ToolBoxUsage
13
- from pydantic import Field
12
+ from fabricatio.utils import is_subclass_of_base
14
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
- class Role(WithBriefing, Propose, ToolBoxUsage):
19
+
20
+ class Role(WithBriefing):
17
21
  """Class that represents a role with a registry of events and workflows.
18
22
 
19
23
  A Role serves as a container for workflows, managing their registration to events
20
24
  and providing them with shared configuration like tools and personality.
21
-
22
- Attributes:
23
- registry: Mapping of events to workflows that handle them
24
- toolboxes: Set of toolboxes available to this role and its workflows
25
25
  """
26
-
26
+ model_config = ConfigDict(use_attribute_docstrings=True, arbitrary_types_allowed=True)
27
27
  description: str = ""
28
28
  """A brief description of the role's responsibilities and capabilities."""
29
29
 
30
- registry: dict[Event | str, WorkFlow] = Field(default_factory=dict)
30
+ registry: Dict[Event, WorkFlow] = Field(default_factory=dict)
31
31
  """The registry of events and workflows."""
32
32
 
33
- toolboxes: Set[ToolBox] = Field(default_factory=set)
34
- """Collection of tools available to this role."""
35
-
36
33
  def model_post_init(self, __context: Any) -> None:
37
34
  """Initialize the role by resolving configurations and registering workflows.
38
35
 
@@ -49,7 +46,7 @@ class Role(WithBriefing, Propose, ToolBoxUsage):
49
46
  """
50
47
  for event, workflow in self.registry.items():
51
48
  logger.debug(
52
- f"Registering workflow: `{workflow.name}` for event: `{Event.instantiate_from(event).collapse()}`"
49
+ f"Registering workflow: `{workflow.name}` for event: `{event.collapse()}`"
53
50
  )
54
51
  env.on(event, workflow.serve)
55
52
  return self
@@ -65,12 +62,35 @@ class Role(WithBriefing, Propose, ToolBoxUsage):
65
62
  """
66
63
  for workflow in self.registry.values():
67
64
  logger.debug(f"Resolving config for workflow: `{workflow.name}`")
68
- (
69
- workflow.fallback_to(self)
70
- .steps_fallback_to_self()
71
- .inject_personality(self.briefing)
72
- .supply_tools_from(self)
73
- .steps_supply_tools_from_self()
74
- )
75
-
65
+ self._configure_scoped_config(workflow)
66
+ self._configure_toolbox_usage(workflow)
67
+ workflow.inject_personality(self.briefing)
76
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)
fabricatio/models/task.py CHANGED
@@ -4,16 +4,16 @@ It includes methods to manage the task's lifecycle, such as starting, finishing,
4
4
  """
5
5
 
6
6
  from asyncio import Queue
7
- from typing import Any, Dict, List, Optional, Self
7
+ from typing import Any, Dict, List, Optional, Self, Union
8
+
9
+ from fabricatio.rust import CONFIG, TEMPLATE_MANAGER, Event, TaskStatus
10
+ from pydantic import Field, PrivateAttr
8
11
 
9
- from fabricatio.config import configs
10
- from fabricatio.constants import TaskStatus
11
12
  from fabricatio.core import env
12
13
  from fabricatio.journal import logger
13
- from fabricatio.models.events import Event, EventLike
14
14
  from fabricatio.models.generic import ProposedAble, WithBriefing, WithDependency
15
- from fabricatio.rust_instances import TEMPLATE_MANAGER
16
- from pydantic import Field, PrivateAttr
15
+
16
+ type EventLike = Union[str, Event, List[str]]
17
17
 
18
18
 
19
19
  class Task[T](WithBriefing, ProposedAble, WithDependency):
@@ -33,7 +33,7 @@ class Task[T](WithBriefing, ProposedAble, WithDependency):
33
33
  description: str = Field(default="")
34
34
  """A detailed explanation of the task that includes all necessary information. Should be clear and answer what, why, when, where, who, and how questions."""
35
35
 
36
- goals: List[str] = Field(default=[])
36
+ goals: List[str] = Field(default_factory=list)
37
37
  """A list of objectives that the task aims to accomplish. Each goal should be clear and specific. Complex tasks should be broken into multiple smaller goals."""
38
38
 
39
39
  namespace: List[str] = Field(default_factory=list)
@@ -65,7 +65,7 @@ class Task[T](WithBriefing, ProposedAble, WithDependency):
65
65
 
66
66
  def model_post_init(self, __context: Any) -> None:
67
67
  """Initialize the task with a namespace event."""
68
- self._namespace.segments.extend(self.namespace)
68
+ self._namespace.concat(self.namespace)
69
69
 
70
70
  def move_to(self, new_namespace: EventLike) -> Self:
71
71
  """Move the task to a new namespace.
@@ -266,7 +266,7 @@ class Task[T](WithBriefing, ProposedAble, WithDependency):
266
266
  str: The briefing of the task.
267
267
  """
268
268
  return TEMPLATE_MANAGER.render_template(
269
- configs.templates.task_briefing_template,
269
+ CONFIG.templates.task_briefing_template,
270
270
  self.model_dump(),
271
271
  )
272
272
 
fabricatio/models/tool.py CHANGED
@@ -10,11 +10,12 @@ from inspect import iscoroutinefunction, signature
10
10
  from types import CodeType, ModuleType
11
11
  from typing import Any, Callable, Dict, List, Optional, Self, cast, overload
12
12
 
13
- from fabricatio.config import configs
13
+ from fabricatio.rust import CONFIG
14
+ from pydantic import BaseModel, ConfigDict, Field
15
+
14
16
  from fabricatio.decorators import logging_execution_info, use_temp_module
15
17
  from fabricatio.journal import logger
16
18
  from fabricatio.models.generic import WithBriefing
17
- from pydantic import BaseModel, ConfigDict, Field
18
19
 
19
20
 
20
21
  class Tool[**P, R](WithBriefing):
@@ -210,7 +211,7 @@ class ToolExecutor(BaseModel):
210
211
  M: The module with injected tools.
211
212
  """
212
213
  module = module or cast(
213
- "M", module_from_spec(spec=ModuleSpec(name=configs.toolbox.tool_module_name, loader=None))
214
+ "M", module_from_spec(spec=ModuleSpec(name=CONFIG.toolbox.tool_module_name, loader=None))
214
215
  )
215
216
  for tool in self.candidates:
216
217
  logger.debug(f"Injecting tool: {tool.name}")
@@ -229,7 +230,7 @@ class ToolExecutor(BaseModel):
229
230
  M: The module with injected data.
230
231
  """
231
232
  module = module or cast(
232
- 'M', module_from_spec(spec=ModuleSpec(name=configs.toolbox.data_module_name, loader=None))
233
+ 'M', module_from_spec(spec=ModuleSpec(name=CONFIG.toolbox.data_module_name, loader=None))
233
234
  )
234
235
  for key, value in self.data.items():
235
236
  logger.debug(f"Injecting data: {key}")