fabricatio 0.2.1.dev0__cp313-cp313-win_amd64.whl → 0.3.14.dev5__cp313-cp313-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 (75) hide show
  1. fabricatio/__init__.py +12 -20
  2. fabricatio/actions/__init__.py +1 -5
  3. fabricatio/actions/article.py +319 -0
  4. fabricatio/actions/article_rag.py +416 -0
  5. fabricatio/actions/fs.py +25 -0
  6. fabricatio/actions/output.py +248 -0
  7. fabricatio/actions/rag.py +96 -0
  8. fabricatio/actions/rules.py +83 -0
  9. fabricatio/capabilities/__init__.py +1 -0
  10. fabricatio/capabilities/advanced_judge.py +20 -0
  11. fabricatio/capabilities/advanced_rag.py +61 -0
  12. fabricatio/capabilities/censor.py +105 -0
  13. fabricatio/capabilities/check.py +212 -0
  14. fabricatio/capabilities/correct.py +228 -0
  15. fabricatio/capabilities/extract.py +74 -0
  16. fabricatio/capabilities/persist.py +103 -0
  17. fabricatio/capabilities/propose.py +65 -0
  18. fabricatio/capabilities/rag.py +263 -0
  19. fabricatio/capabilities/rating.py +404 -0
  20. fabricatio/capabilities/review.py +114 -0
  21. fabricatio/capabilities/task.py +113 -0
  22. fabricatio/decorators.py +251 -179
  23. fabricatio/{core.py → emitter.py} +31 -21
  24. fabricatio/fs/__init__.py +32 -2
  25. fabricatio/fs/curd.py +32 -9
  26. fabricatio/fs/readers.py +44 -7
  27. fabricatio/journal.py +3 -19
  28. fabricatio/models/action.py +185 -61
  29. fabricatio/models/adv_kwargs_types.py +63 -0
  30. fabricatio/models/extra/__init__.py +1 -0
  31. fabricatio/models/extra/advanced_judge.py +32 -0
  32. fabricatio/models/extra/aricle_rag.py +284 -0
  33. fabricatio/models/extra/article_base.py +422 -0
  34. fabricatio/models/extra/article_essence.py +101 -0
  35. fabricatio/models/extra/article_main.py +284 -0
  36. fabricatio/models/extra/article_outline.py +46 -0
  37. fabricatio/models/extra/article_proposal.py +52 -0
  38. fabricatio/models/extra/patches.py +20 -0
  39. fabricatio/models/extra/problem.py +165 -0
  40. fabricatio/models/extra/rag.py +98 -0
  41. fabricatio/models/extra/rule.py +52 -0
  42. fabricatio/models/generic.py +704 -36
  43. fabricatio/models/kwargs_types.py +112 -17
  44. fabricatio/models/role.py +74 -27
  45. fabricatio/models/task.py +94 -60
  46. fabricatio/models/tool.py +328 -188
  47. fabricatio/models/usages.py +791 -515
  48. fabricatio/parser.py +81 -60
  49. fabricatio/rust.cp313-win_amd64.pyd +0 -0
  50. fabricatio/rust.pyi +886 -0
  51. fabricatio/toolboxes/__init__.py +1 -3
  52. fabricatio/toolboxes/fs.py +17 -1
  53. fabricatio/utils.py +156 -0
  54. fabricatio/workflows/__init__.py +1 -0
  55. fabricatio/workflows/articles.py +24 -0
  56. fabricatio/workflows/rag.py +11 -0
  57. fabricatio-0.3.14.dev5.data/scripts/tdown.exe +0 -0
  58. fabricatio-0.3.14.dev5.data/scripts/ttm.exe +0 -0
  59. fabricatio-0.3.14.dev5.dist-info/METADATA +188 -0
  60. fabricatio-0.3.14.dev5.dist-info/RECORD +64 -0
  61. {fabricatio-0.2.1.dev0.dist-info → fabricatio-0.3.14.dev5.dist-info}/WHEEL +1 -1
  62. fabricatio/_rust.cp313-win_amd64.pyd +0 -0
  63. fabricatio/_rust.pyi +0 -53
  64. fabricatio/_rust_instances.py +0 -8
  65. fabricatio/actions/communication.py +0 -15
  66. fabricatio/actions/transmission.py +0 -23
  67. fabricatio/config.py +0 -263
  68. fabricatio/models/advanced.py +0 -128
  69. fabricatio/models/events.py +0 -82
  70. fabricatio/models/utils.py +0 -78
  71. fabricatio/toolboxes/task.py +0 -6
  72. fabricatio-0.2.1.dev0.data/scripts/tdown.exe +0 -0
  73. fabricatio-0.2.1.dev0.dist-info/METADATA +0 -420
  74. fabricatio-0.2.1.dev0.dist-info/RECORD +0 -35
  75. {fabricatio-0.2.1.dev0.dist-info → fabricatio-0.3.14.dev5.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,228 @@
1
+ """A module containing the Correct capability for reviewing, validating, and improving objects."""
2
+
3
+ from abc import ABC
4
+ from asyncio import gather
5
+ from typing import Optional, Type, Unpack, cast
6
+
7
+ from fabricatio.capabilities.propose import Propose
8
+ from fabricatio.capabilities.rating import Rating
9
+ from fabricatio.journal import logger
10
+ from fabricatio.models.adv_kwargs_types import CorrectKwargs
11
+ from fabricatio.models.extra.problem import Improvement, ProblemSolutions
12
+ from fabricatio.models.generic import ProposedUpdateAble, SketchedAble
13
+ from fabricatio.models.kwargs_types import (
14
+ BestKwargs,
15
+ ValidateKwargs,
16
+ )
17
+ from fabricatio.rust import CONFIG, TEMPLATE_MANAGER
18
+ from fabricatio.utils import fallback_kwargs, ok, override_kwargs
19
+
20
+
21
+ class Correct(Rating, Propose, ABC):
22
+ """A class that provides the capability to correct objects."""
23
+
24
+ async def decide_solution(
25
+ self, problem_solutions: ProblemSolutions, **kwargs: Unpack[BestKwargs]
26
+ ) -> ProblemSolutions:
27
+ """Decide the best solution from a list of problem solutions.
28
+
29
+ Args:
30
+ problem_solutions (ProblemSolutions): The problem solutions to evaluate.
31
+ **kwargs (Unpack[BestKwargs]): Additional keyword arguments for the decision process.
32
+
33
+ Returns:
34
+ ProblemSolutions: The problem solutions with the best solution selected.
35
+ """
36
+ if (leng := len(problem_solutions.solutions)) == 0:
37
+ logger.error(f"No solutions found in ProblemSolutions, Skip: `{problem_solutions.problem.name}`")
38
+ if leng > 1:
39
+ logger.info(f"{leng} solutions found in Problem `{problem_solutions.problem.name}`, select the best.")
40
+ problem_solutions.solutions = await self.best(problem_solutions.solutions, **kwargs)
41
+ return problem_solutions
42
+
43
+ async def decide_improvement(self, improvement: Improvement, **kwargs: Unpack[BestKwargs]) -> Improvement:
44
+ """Decide the best solution for each problem solution in an improvement.
45
+
46
+ Args:
47
+ improvement (Improvement): The improvement containing problem solutions to evaluate.
48
+ **kwargs (Unpack[BestKwargs]): Additional keyword arguments for the decision process.
49
+
50
+ Returns:
51
+ Improvement: The improvement with the best solutions selected for each problem solution.
52
+ """
53
+ if leng := len(improvement.problem_solutions):
54
+ logger.debug(f"{leng} problem_solutions found in Improvement, decide solution for each of them.")
55
+ await gather(
56
+ *[
57
+ self.decide_solution(
58
+ ps,
59
+ **fallback_kwargs(
60
+ kwargs, topic=f"which solution is better to deal this problem {ps.problem.description}\n\n"
61
+ ),
62
+ )
63
+ for ps in improvement.problem_solutions
64
+ ],
65
+ )
66
+ if any(not (violated := ps).decided() for ps in improvement.problem_solutions):
67
+ logger.error(f"Some problem_solutions are not decided: {violated}")
68
+ else:
69
+ logger.success(f"All problem_solutions are decided '{improvement.focused_on}'")
70
+ else:
71
+ logger.error(f"No problem_solutions found in Improvement, Skip: {improvement}")
72
+ return improvement
73
+
74
+ async def fix_troubled_obj[M: SketchedAble](
75
+ self,
76
+ obj: M,
77
+ problem_solutions: ProblemSolutions,
78
+ reference: str = "",
79
+ **kwargs: Unpack[ValidateKwargs[M]],
80
+ ) -> Optional[M]:
81
+ """Fix a troubled object based on problem solutions.
82
+
83
+ Args:
84
+ obj (M): The object to be fixed.
85
+ problem_solutions (ProblemSolutions): The problem solutions to apply.
86
+ reference (str): A reference or contextual information for the object.
87
+ **kwargs (Unpack[ValidateKwargs[M]]): Additional keyword arguments for the validation process.
88
+
89
+ Returns:
90
+ Optional[M]: The fixed object, or None if fixing fails.
91
+ """
92
+ return await self.propose(
93
+ cast("Type[M]", obj.__class__),
94
+ TEMPLATE_MANAGER.render_template(
95
+ CONFIG.templates.fix_troubled_obj_template,
96
+ {
97
+ "problem": problem_solutions.problem.display(),
98
+ "solution": ok(
99
+ problem_solutions.final_solution(),
100
+ f"{len(problem_solutions.solutions)} solution Found for `{problem_solutions.problem.name}`.",
101
+ ).display(),
102
+ "reference": reference,
103
+ },
104
+ ),
105
+ **kwargs,
106
+ )
107
+
108
+ async def fix_troubled_string(
109
+ self,
110
+ input_text: str,
111
+ problem_solutions: ProblemSolutions,
112
+ reference: str = "",
113
+ **kwargs: Unpack[ValidateKwargs[str]],
114
+ ) -> Optional[str]:
115
+ """Fix a troubled string based on problem solutions.
116
+
117
+ Args:
118
+ input_text (str): The string to be fixed.
119
+ problem_solutions (ProblemSolutions): The problem solutions to apply.
120
+ reference (str): A reference or contextual information for the string.
121
+ **kwargs (Unpack[ValidateKwargs[str]]): Additional keyword arguments for the validation process.
122
+
123
+ Returns:
124
+ Optional[str]: The fixed string, or None if fixing fails.
125
+ """
126
+ return await self.ageneric_string(
127
+ TEMPLATE_MANAGER.render_template(
128
+ CONFIG.templates.fix_troubled_string_template,
129
+ {
130
+ "problem": problem_solutions.problem.display(),
131
+ "solution": ok(
132
+ problem_solutions.final_solution(),
133
+ f"No solution found for problem: {problem_solutions.problem}",
134
+ ).display(),
135
+ "reference": reference,
136
+ "string_to_fix": input_text,
137
+ },
138
+ ),
139
+ **kwargs,
140
+ )
141
+
142
+ async def correct_obj[M: SketchedAble](
143
+ self,
144
+ obj: M,
145
+ improvement: Improvement,
146
+ reference: str = "",
147
+ **kwargs: Unpack[ValidateKwargs[M]],
148
+ ) -> Optional[M]:
149
+ """Review and correct an object based on defined criteria and templates.
150
+
151
+ This method first conducts a review of the given object, then uses the review results
152
+ to generate a corrected version of the object using appropriate templates.
153
+
154
+ Args:
155
+ obj (M): The object to be reviewed and corrected. Must implement ProposedAble.
156
+ improvement (Improvement): The improvement object containing the review results.
157
+ reference (str): A reference or contextual information for the object.
158
+ **kwargs (Unpack[ValidateKwargs[M]]): Review configuration parameters including criteria and review options.
159
+
160
+ Returns:
161
+ Optional[M]: A corrected version of the input object, or None if correction fails.
162
+
163
+ Raises:
164
+ TypeError: If the provided object doesn't implement Display or WithBriefing interfaces.
165
+ """
166
+ if not improvement.decided():
167
+ logger.info(f"Improvement {improvement.focused_on} not decided, start deciding...")
168
+ improvement = await self.decide_improvement(improvement, **override_kwargs(kwargs, default=None))
169
+
170
+ total = len(improvement.problem_solutions)
171
+ for idx, ps in enumerate(improvement.problem_solutions):
172
+ logger.info(f"[{idx + 1}/{total}] Fixing {obj.__class__.__name__} for problem `{ps.problem.name}`")
173
+ fixed_obj = await self.fix_troubled_obj(obj, ps, reference, **kwargs)
174
+ if fixed_obj is None:
175
+ logger.error(f"[{idx + 1}/{total}] Failed to fix problem `{ps.problem.name}`")
176
+ return None
177
+ obj = fixed_obj
178
+ return obj
179
+
180
+ async def correct_string(
181
+ self, input_text: str, improvement: Improvement, reference: str = "", **kwargs: Unpack[ValidateKwargs[str]]
182
+ ) -> Optional[str]:
183
+ """Review and correct a string based on defined criteria and templates.
184
+
185
+ This method first conducts a review of the given string, then uses the review results
186
+ to generate a corrected version of the string using appropriate templates.
187
+
188
+ Args:
189
+ input_text (str): The string to be reviewed and corrected.
190
+ improvement (Improvement): The improvement object containing the review results.
191
+ reference (str): A reference or contextual information for the string.
192
+ **kwargs (Unpack[ValidateKwargs[str]]): Review configuration parameters including criteria and review options.
193
+
194
+ Returns:
195
+ Optional[str]: A corrected version of the input string, or None if correction fails.
196
+ """
197
+ if not improvement.decided():
198
+ logger.info(f"Improvement {improvement.focused_on} not decided, start deciding...")
199
+
200
+ improvement = await self.decide_improvement(improvement, **override_kwargs(kwargs, default=None))
201
+
202
+ for ps in improvement.problem_solutions:
203
+ fixed_string = await self.fix_troubled_string(input_text, ps, reference, **kwargs)
204
+ if fixed_string is None:
205
+ logger.error(
206
+ f"Failed to fix troubling string when deal with problem: {ps.problem}",
207
+ )
208
+ return None
209
+ input_text = fixed_string
210
+ return input_text
211
+
212
+ async def correct_obj_inplace[M: ProposedUpdateAble](
213
+ self, obj: M, **kwargs: Unpack[CorrectKwargs[M]]
214
+ ) -> Optional[M]:
215
+ """Correct an object in place based on defined criteria and templates.
216
+
217
+ Args:
218
+ obj (M): The object to be corrected.
219
+ **kwargs (Unpack[CorrectKwargs[M]]): Additional keyword arguments for the correction process.
220
+
221
+ Returns:
222
+ Optional[M]: The corrected object, or None if correction fails.
223
+ """
224
+ corrected_obj = await self.correct_obj(obj, **kwargs)
225
+ if corrected_obj is None:
226
+ return corrected_obj
227
+ obj.update_from(corrected_obj)
228
+ return obj
@@ -0,0 +1,74 @@
1
+ """A module that provide capabilities for extracting information from a given source to a model."""
2
+
3
+ from abc import ABC
4
+ from typing import List, Optional, Type, Unpack, overload
5
+
6
+ from fabricatio import TEMPLATE_MANAGER
7
+ from fabricatio.capabilities.propose import Propose
8
+ from fabricatio.models.generic import ProposedAble
9
+ from fabricatio.models.kwargs_types import ValidateKwargs
10
+ from fabricatio.rust import CONFIG
11
+
12
+
13
+ class Extract(Propose, ABC):
14
+ """A class that extract information from a given source to a model."""
15
+
16
+ @overload
17
+ async def extract[M: ProposedAble](
18
+ self,
19
+ cls: Type[M],
20
+ source: str,
21
+ extract_requirement: Optional[str] = None,
22
+ align_language: bool = True,
23
+ **kwargs: Unpack[ValidateKwargs[M]],
24
+ ) -> M: ...
25
+
26
+ @overload
27
+ async def extract[M: ProposedAble](
28
+ self,
29
+ cls: Type[M],
30
+ source: str,
31
+ extract_requirement: Optional[str] = None,
32
+ align_language: bool = True,
33
+ **kwargs: Unpack[ValidateKwargs[None]],
34
+ ) -> Optional[M]: ...
35
+
36
+ @overload
37
+ async def extract[M: ProposedAble](
38
+ self,
39
+ cls: Type[M],
40
+ source: List[str],
41
+ extract_requirement: Optional[str] = None,
42
+ align_language: bool = True,
43
+ **kwargs: Unpack[ValidateKwargs[M]],
44
+ ) -> List[M]: ...
45
+
46
+ @overload
47
+ async def extract[M: ProposedAble](
48
+ self,
49
+ cls: Type[M],
50
+ source: List[str],
51
+ extract_requirement: Optional[str] = None,
52
+ align_language: bool = True,
53
+ **kwargs: Unpack[ValidateKwargs[None]],
54
+ ) -> List[Optional[M]]: ...
55
+
56
+ async def extract[M: ProposedAble](
57
+ self,
58
+ cls: Type[M],
59
+ source: List[str] | str,
60
+ extract_requirement: Optional[str] = None,
61
+ align_language: bool = True,
62
+ **kwargs: Unpack[ValidateKwargs[Optional[M]]],
63
+ ) -> M | List[M] | Optional[M] | List[Optional[M]]:
64
+ """Extract information from a given source to a model."""
65
+ return await self.propose(
66
+ cls,
67
+ prompt=TEMPLATE_MANAGER.render_template(
68
+ CONFIG.templates.extract_template,
69
+ [{"source": s, "extract_requirement": extract_requirement} for s in source]
70
+ if isinstance(source, list)
71
+ else {"source": source, "extract_requirement": extract_requirement, "align_language": align_language},
72
+ ),
73
+ **kwargs,
74
+ )
@@ -0,0 +1,103 @@
1
+ """Persistence capabilities for model instances."""
2
+
3
+ from abc import ABC
4
+ from datetime import datetime
5
+ from pathlib import Path
6
+ from typing import Optional, Self
7
+
8
+ from loguru import logger
9
+
10
+ from fabricatio.fs import safe_text_read
11
+ from fabricatio.models.generic import Base
12
+ from fabricatio.rust import blake3_hash
13
+
14
+
15
+ class PersistentAble(Base, ABC):
16
+ """Class providing file persistence capabilities.
17
+
18
+ Enables saving model instances to disk with timestamped filenames and loading from persisted files.
19
+ Implements basic versioning through filename hashing and timestamping.
20
+ """
21
+
22
+ def persist(self, path: str | Path) -> Self:
23
+ """Save model instance to disk with versioned filename.
24
+
25
+ Args:
26
+ path (str | Path): Target directory or file path. If directory, filename is auto-generated.
27
+
28
+ Returns:
29
+ Self: Current instance for method chaining
30
+
31
+ Notes:
32
+ - Filename format: <ClassName>_<YYYYMMDD_HHMMSS>_<6-char_hash>.json
33
+ - Hash generated from JSON content ensures uniqueness
34
+ """
35
+ p = Path(path)
36
+ out = self.model_dump_json(indent=1, by_alias=True)
37
+
38
+ # Generate a timestamp in the format YYYYMMDD_HHMMSS
39
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
40
+
41
+ # Generate the hash
42
+ file_hash = blake3_hash(out.encode())[:6]
43
+
44
+ # Construct the file name with timestamp and hash
45
+ file_name = f"{self.__class__.__name__}_{timestamp}_{file_hash}.json"
46
+
47
+ if p.is_dir():
48
+ p.joinpath(file_name).write_text(out, encoding="utf-8")
49
+ else:
50
+ p.mkdir(exist_ok=True, parents=True)
51
+ p.write_text(out, encoding="utf-8")
52
+
53
+ logger.info(f"Persisted `{self.__class__.__name__}` to {p.as_posix()}")
54
+ return self
55
+
56
+ @classmethod
57
+ def from_latest_persistent(cls, dir_path: str | Path) -> Optional[Self]:
58
+ """Load most recent persisted instance from directory.
59
+
60
+ Args:
61
+ dir_path (str | Path): Directory containing persisted files
62
+
63
+ Returns:
64
+ Self: Most recently modified instance
65
+
66
+ Raises:
67
+ NotADirectoryError: If path is not a valid directory
68
+ FileNotFoundError: If no matching files found
69
+ """
70
+ dir_path = Path(dir_path)
71
+ if not dir_path.is_dir():
72
+ return None
73
+
74
+ pattern = f"{cls.__name__}_*.json"
75
+ files = list(dir_path.glob(pattern))
76
+
77
+ if not files:
78
+ return None
79
+
80
+ def _get_timestamp(file_path: Path) -> datetime:
81
+ stem = file_path.stem
82
+ parts = stem.split("_")
83
+ return datetime.strptime(f"{parts[1]}_{parts[2]}", "%Y%m%d_%H%M%S")
84
+
85
+ files.sort(key=lambda f: _get_timestamp(f), reverse=True)
86
+
87
+ return cls.from_persistent(files.pop(0))
88
+
89
+ @classmethod
90
+ def from_persistent(cls, path: str | Path) -> Self:
91
+ """Load an instance from a specific persisted file.
92
+
93
+ Args:
94
+ path (str | Path): Path to the JSON file.
95
+
96
+ Returns:
97
+ Self: The loaded instance from the file.
98
+
99
+ Raises:
100
+ FileNotFoundError: If the specified file does not exist.
101
+ ValueError: If the file content is invalid for the model.
102
+ """
103
+ return cls.model_validate_json(safe_text_read(path))
@@ -0,0 +1,65 @@
1
+ """A module for the task capabilities of the Fabricatio library."""
2
+ from abc import ABC
3
+ from typing import List, Optional, Type, Unpack, overload
4
+
5
+ from fabricatio.models.generic import ProposedAble
6
+ from fabricatio.models.kwargs_types import ValidateKwargs
7
+ from fabricatio.models.usages import LLMUsage
8
+
9
+
10
+ class Propose(LLMUsage,ABC):
11
+ """A class that proposes an Obj based on a prompt."""
12
+
13
+ @overload
14
+ async def propose[M: ProposedAble](
15
+ self,
16
+ cls: Type[M],
17
+ prompt: List[str],
18
+ **kwargs: Unpack[ValidateKwargs[None]],
19
+ ) -> List[Optional[M]]: ...
20
+
21
+ @overload
22
+ async def propose[M: ProposedAble](
23
+ self,
24
+ cls: Type[M],
25
+ prompt: List[str],
26
+ **kwargs: Unpack[ValidateKwargs[M]],
27
+ ) -> List[M]: ...
28
+
29
+ @overload
30
+ async def propose[M: ProposedAble](
31
+ self,
32
+ cls: Type[M],
33
+ prompt: str,
34
+ **kwargs: Unpack[ValidateKwargs[None]],
35
+ ) -> Optional[M]: ...
36
+ @overload
37
+ async def propose[M: ProposedAble](
38
+ self,
39
+ cls: Type[M],
40
+ prompt: str,
41
+ **kwargs: Unpack[ValidateKwargs[M]],
42
+ ) -> M: ...
43
+
44
+ async def propose[M: ProposedAble](
45
+ self,
46
+ cls: Type[M],
47
+ prompt: List[str] | str,
48
+ **kwargs: Unpack[ValidateKwargs[Optional[M]]],
49
+ ) -> Optional[M] | List[Optional[M]] | M | List[M]:
50
+ """Asynchronously proposes a task based on a given prompt and parameters.
51
+
52
+ Parameters:
53
+ cls: The class type of the task to be proposed.
54
+ prompt: The prompt text for proposing a task, which is a string that must be provided.
55
+ **kwargs: The keyword arguments for the LLM (Large Language Model) usage.
56
+
57
+ Returns:
58
+ A Task object based on the proposal result.
59
+ """
60
+ return await self.aask_validate(
61
+ question=cls.create_json_prompt(prompt),
62
+ validator=cls.instantiate_from_string,
63
+ **kwargs,
64
+ )
65
+