fabricatio 0.2.8.dev3__cp312-cp312-win_amd64.whl → 0.2.9.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 +4 -11
- fabricatio/actions/__init__.py +1 -0
- fabricatio/actions/article.py +63 -87
- fabricatio/actions/article_rag.py +54 -43
- fabricatio/actions/rag.py +2 -1
- fabricatio/actions/rules.py +39 -0
- fabricatio/capabilities/__init__.py +1 -0
- fabricatio/capabilities/censor.py +90 -0
- fabricatio/capabilities/check.py +127 -29
- fabricatio/capabilities/correct.py +143 -100
- fabricatio/capabilities/rag.py +5 -4
- fabricatio/capabilities/rating.py +65 -16
- fabricatio/capabilities/review.py +1 -1
- fabricatio/capabilities/task.py +2 -1
- fabricatio/config.py +11 -3
- fabricatio/models/action.py +14 -7
- fabricatio/models/adv_kwargs_types.py +25 -0
- fabricatio/models/extra/__init__.py +1 -0
- fabricatio/models/extra/advanced_judge.py +5 -2
- fabricatio/models/extra/article_base.py +3 -20
- fabricatio/models/extra/article_main.py +2 -3
- fabricatio/models/extra/patches.py +20 -0
- fabricatio/models/extra/problem.py +41 -8
- fabricatio/models/extra/rule.py +26 -9
- fabricatio/models/generic.py +310 -55
- fabricatio/models/kwargs_types.py +23 -17
- fabricatio/models/task.py +1 -1
- fabricatio/models/tool.py +149 -14
- fabricatio/models/usages.py +50 -42
- fabricatio/parser.py +7 -8
- fabricatio/rust.cp312-win_amd64.pyd +0 -0
- fabricatio/{_rust_instances.py → rust_instances.py} +1 -1
- fabricatio/workflows/__init__.py +1 -0
- fabricatio-0.2.9.dev0.data/scripts/tdown.exe +0 -0
- {fabricatio-0.2.8.dev3.dist-info → fabricatio-0.2.9.dev0.dist-info}/METADATA +1 -1
- fabricatio-0.2.9.dev0.dist-info/RECORD +61 -0
- fabricatio/_rust.cp312-win_amd64.pyd +0 -0
- fabricatio-0.2.8.dev3.data/scripts/tdown.exe +0 -0
- fabricatio-0.2.8.dev3.dist-info/RECORD +0 -53
- /fabricatio/{_rust.pyi → rust.pyi} +0 -0
- {fabricatio-0.2.8.dev3.dist-info → fabricatio-0.2.9.dev0.dist-info}/WHEEL +0 -0
- {fabricatio-0.2.8.dev3.dist-info → fabricatio-0.2.9.dev0.dist-info}/licenses/LICENSE +0 -0
fabricatio/models/generic.py
CHANGED
@@ -1,18 +1,18 @@
|
|
1
|
-
"""This module defines generic classes for models in the Fabricatio library."""
|
1
|
+
"""This module defines generic classes for models in the Fabricatio library, providing a foundation for various model functionalities."""
|
2
2
|
|
3
3
|
from abc import ABC, abstractmethod
|
4
4
|
from datetime import datetime
|
5
5
|
from pathlib import Path
|
6
|
-
from typing import Any, Callable, Dict, Iterable, List, Optional, Self, Union, final, overload
|
6
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Self, Type, Union, final, overload
|
7
7
|
|
8
8
|
import orjson
|
9
9
|
import rtoml
|
10
|
-
from fabricatio._rust import blake3_hash
|
11
|
-
from fabricatio._rust_instances import TEMPLATE_MANAGER
|
12
10
|
from fabricatio.config import configs
|
13
11
|
from fabricatio.fs.readers import MAGIKA, safe_text_read
|
14
12
|
from fabricatio.journal import logger
|
15
13
|
from fabricatio.parser import JsonCapture
|
14
|
+
from fabricatio.rust import blake3_hash
|
15
|
+
from fabricatio.rust_instances import TEMPLATE_MANAGER
|
16
16
|
from fabricatio.utils import ok
|
17
17
|
from litellm.utils import token_counter
|
18
18
|
from pydantic import (
|
@@ -30,13 +30,19 @@ from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
|
|
30
30
|
|
31
31
|
|
32
32
|
class Base(BaseModel):
|
33
|
-
"""Base class for all models with Pydantic configuration.
|
33
|
+
"""Base class for all models with Pydantic configuration.
|
34
|
+
|
35
|
+
This class sets up the basic Pydantic configuration for all models in the Fabricatio library.
|
36
|
+
"""
|
34
37
|
|
35
38
|
model_config = ConfigDict(use_attribute_docstrings=True)
|
36
39
|
|
37
40
|
|
38
41
|
class Display(Base):
|
39
|
-
"""Class that provides a method to display the model in a formatted JSON string.
|
42
|
+
"""Class that provides a method to display the model in a formatted JSON string.
|
43
|
+
|
44
|
+
This class includes methods to display the model in both formatted and compact JSON strings.
|
45
|
+
"""
|
40
46
|
|
41
47
|
def display(self) -> str:
|
42
48
|
"""Display the model in a formatted JSON string.
|
@@ -54,23 +60,48 @@ class Display(Base):
|
|
54
60
|
"""
|
55
61
|
return self.model_dump_json()
|
56
62
|
|
63
|
+
@staticmethod
|
64
|
+
def seq_display(seq: Iterable["Display"], compact: bool = False) -> str:
|
65
|
+
"""Display a sequence of Display objects in a formatted JSON string.
|
66
|
+
|
67
|
+
Args:
|
68
|
+
seq (Iterable[Display]): The sequence of Display objects to display.
|
69
|
+
compact (bool): Whether to display the sequence in a compact format. Defaults to False.
|
70
|
+
|
71
|
+
Returns:
|
72
|
+
str: The formatted JSON string of the sequence.
|
73
|
+
"""
|
74
|
+
return "\n".join(d.compact() if compact else d.display() for d in seq)
|
75
|
+
|
57
76
|
|
58
77
|
class Named(Base):
|
59
|
-
"""Class that includes a name attribute.
|
78
|
+
"""Class that includes a name attribute.
|
79
|
+
|
80
|
+
This class adds a name attribute to models, which is intended to be a unique identifier.
|
81
|
+
"""
|
60
82
|
|
61
|
-
name: str
|
62
|
-
"""The name of
|
83
|
+
name: str
|
84
|
+
"""The name of this object,briefly and conclusively."""
|
63
85
|
|
64
86
|
|
65
87
|
class Described(Base):
|
66
|
-
"""Class that includes a description attribute.
|
88
|
+
"""Class that includes a description attribute.
|
67
89
|
|
68
|
-
description
|
69
|
-
"""
|
90
|
+
This class adds a description attribute to models, providing additional context or information.
|
91
|
+
"""
|
92
|
+
|
93
|
+
description: str
|
94
|
+
"""A comprehensive description of this object, including its purpose, scope, and context.
|
95
|
+
This should clearly explain what this object is about, why it exists, and in what situations
|
96
|
+
it applies. The description should be detailed enough to provide full understanding of
|
97
|
+
this object's intent and application."""
|
70
98
|
|
71
99
|
|
72
100
|
class AsPrompt(Base):
|
73
|
-
"""Class that provides a method to generate a prompt from the model.
|
101
|
+
"""Class that provides a method to generate a prompt from the model.
|
102
|
+
|
103
|
+
This class includes a method to generate a prompt based on the model's attributes.
|
104
|
+
"""
|
74
105
|
|
75
106
|
@final
|
76
107
|
def as_prompt(self) -> str:
|
@@ -85,31 +116,53 @@ class AsPrompt(Base):
|
|
85
116
|
)
|
86
117
|
|
87
118
|
@abstractmethod
|
88
|
-
def _as_prompt_inner(self) -> Dict[str, str]:
|
119
|
+
def _as_prompt_inner(self) -> Dict[str, str]:
|
120
|
+
"""Generate the inner part of the prompt.
|
121
|
+
|
122
|
+
This method should be implemented by subclasses to provide the specific data for the prompt.
|
123
|
+
|
124
|
+
Returns:
|
125
|
+
Dict[str, str]: The data for the prompt.
|
126
|
+
"""
|
89
127
|
|
90
128
|
|
91
129
|
class WithRef[T](Base):
|
92
|
-
"""Class that provides a reference to another object.
|
130
|
+
"""Class that provides a reference to another object.
|
131
|
+
|
132
|
+
This class manages a reference to another object, allowing for easy access and updates.
|
133
|
+
"""
|
93
134
|
|
94
135
|
_reference: Optional[T] = PrivateAttr(None)
|
95
136
|
|
96
137
|
@property
|
97
138
|
def referenced(self) -> T:
|
98
|
-
"""Get the referenced object.
|
139
|
+
"""Get the referenced object.
|
140
|
+
|
141
|
+
Returns:
|
142
|
+
T: The referenced object.
|
143
|
+
|
144
|
+
Raises:
|
145
|
+
ValueError: If the reference is not set.
|
146
|
+
"""
|
99
147
|
return ok(
|
100
|
-
self._reference, f"`{self.__class__.__name__}`'
|
148
|
+
self._reference, f"`{self.__class__.__name__}`'s `_reference` field is None. Have you called `update_ref`?"
|
101
149
|
)
|
102
150
|
|
103
151
|
@overload
|
104
152
|
def update_ref[S: WithRef](self: S, reference: T) -> S: ...
|
105
|
-
|
106
153
|
@overload
|
107
154
|
def update_ref[S: WithRef](self: S, reference: "WithRef[T]") -> S: ...
|
108
|
-
|
109
155
|
@overload
|
110
156
|
def update_ref[S: WithRef](self: S, reference: None = None) -> S: ...
|
111
157
|
def update_ref[S: WithRef](self: S, reference: Union[T, "WithRef[T]", None] = None) -> S: # noqa: PYI019
|
112
|
-
"""Update the reference of the object.
|
158
|
+
"""Update the reference of the object.
|
159
|
+
|
160
|
+
Args:
|
161
|
+
reference (Union[T, WithRef[T], None]): The new reference to set.
|
162
|
+
|
163
|
+
Returns:
|
164
|
+
S: The current instance with the updated reference.
|
165
|
+
"""
|
113
166
|
if isinstance(reference, self.__class__):
|
114
167
|
self._reference = reference.referenced
|
115
168
|
else:
|
@@ -117,14 +170,24 @@ class WithRef[T](Base):
|
|
117
170
|
return self
|
118
171
|
|
119
172
|
def derive[S: WithRef](self: S, reference: Any) -> S: # noqa: PYI019
|
120
|
-
"""Derive a new object from the current object.
|
173
|
+
"""Derive a new object from the current object.
|
174
|
+
|
175
|
+
Args:
|
176
|
+
reference (Any): The reference for the new object.
|
177
|
+
|
178
|
+
Returns:
|
179
|
+
S: A new instance derived from the current object with the provided reference.
|
180
|
+
"""
|
121
181
|
new = self.model_copy()
|
122
182
|
new._reference = reference
|
123
183
|
return new
|
124
184
|
|
125
185
|
|
126
186
|
class PersistentAble(Base):
|
127
|
-
"""Class that provides a method to persist the object.
|
187
|
+
"""Class that provides a method to persist the object.
|
188
|
+
|
189
|
+
This class includes methods to persist the object to a file or directory.
|
190
|
+
"""
|
128
191
|
|
129
192
|
def persist(self, path: str | Path) -> Self:
|
130
193
|
"""Persist the object to a file or directory.
|
@@ -136,7 +199,7 @@ class PersistentAble(Base):
|
|
136
199
|
Self: The current instance of the object.
|
137
200
|
"""
|
138
201
|
p = Path(path)
|
139
|
-
out =
|
202
|
+
out = self.model_dump_json()
|
140
203
|
|
141
204
|
# Generate a timestamp in the format YYYYMMDD_HHMMSS
|
142
205
|
timestamp = datetime.now().strftime("%Y%m%d")
|
@@ -166,22 +229,50 @@ class PersistentAble(Base):
|
|
166
229
|
Returns:
|
167
230
|
Self: The current instance of the object.
|
168
231
|
"""
|
169
|
-
return cls.
|
232
|
+
return cls.model_validate_json(safe_text_read(path))
|
233
|
+
|
234
|
+
|
235
|
+
class Language(Base):
|
236
|
+
"""Class that provides a language attribute."""
|
237
|
+
|
238
|
+
language: str
|
239
|
+
"""The written language of this object, which should be aligned to the original requirement
|
240
|
+
For example if the requirement is in Chinese, the language should be set to `zh`, if the requirement is in English, the language should be set to `en` and etc."""
|
170
241
|
|
171
242
|
|
172
243
|
class ModelHash(Base):
|
173
|
-
"""Class that provides a hash value for the object.
|
244
|
+
"""Class that provides a hash value for the object.
|
245
|
+
|
246
|
+
This class includes a method to calculate a hash value for the object based on its JSON representation.
|
247
|
+
"""
|
174
248
|
|
175
249
|
def __hash__(self) -> int:
|
176
|
-
"""Calculates a hash value for the
|
250
|
+
"""Calculates a hash value for the object based on its model_dump_json representation.
|
251
|
+
|
252
|
+
Returns:
|
253
|
+
int: The hash value of the object.
|
254
|
+
"""
|
177
255
|
return hash(self.model_dump_json())
|
178
256
|
|
179
257
|
|
180
258
|
class UpdateFrom(Base):
|
181
|
-
"""Class that provides a method to update the object from another object.
|
259
|
+
"""Class that provides a method to update the object from another object.
|
260
|
+
|
261
|
+
This class includes methods to update the current object with the attributes of another object.
|
262
|
+
"""
|
182
263
|
|
183
264
|
def update_pre_check(self, other: Self) -> Self:
|
184
|
-
"""Pre-check for updating the object from another object.
|
265
|
+
"""Pre-check for updating the object from another object.
|
266
|
+
|
267
|
+
Args:
|
268
|
+
other (Self): The other object to update from.
|
269
|
+
|
270
|
+
Returns:
|
271
|
+
Self: The current instance after pre-check.
|
272
|
+
|
273
|
+
Raises:
|
274
|
+
TypeError: If the other object is not of the same type.
|
275
|
+
"""
|
185
276
|
if not isinstance(other, self.__class__):
|
186
277
|
raise TypeError(f"Cannot update from a non-{self.__class__.__name__} instance.")
|
187
278
|
|
@@ -189,16 +280,35 @@ class UpdateFrom(Base):
|
|
189
280
|
|
190
281
|
@abstractmethod
|
191
282
|
def update_from_inner(self, other: Self) -> Self:
|
192
|
-
"""Updates the current instance with the attributes of another instance.
|
283
|
+
"""Updates the current instance with the attributes of another instance.
|
284
|
+
|
285
|
+
This method should be implemented by subclasses to provide the specific update logic.
|
286
|
+
|
287
|
+
Args:
|
288
|
+
other (Self): The other instance to update from.
|
289
|
+
|
290
|
+
Returns:
|
291
|
+
Self: The current instance with updated attributes.
|
292
|
+
"""
|
193
293
|
|
194
294
|
@final
|
195
295
|
def update_from(self, other: Self) -> Self:
|
196
|
-
"""Updates the current instance with the attributes of another instance.
|
296
|
+
"""Updates the current instance with the attributes of another instance.
|
297
|
+
|
298
|
+
Args:
|
299
|
+
other (Self): The other instance to update from.
|
300
|
+
|
301
|
+
Returns:
|
302
|
+
Self: The current instance with updated attributes.
|
303
|
+
"""
|
197
304
|
return self.update_pre_check(other).update_from_inner(other)
|
198
305
|
|
199
306
|
|
200
307
|
class ResolveUpdateConflict(Base):
|
201
|
-
"""Class that provides a method to update the object from another object.
|
308
|
+
"""Class that provides a method to update the object from another object.
|
309
|
+
|
310
|
+
This class includes a method to resolve conflicts when updating the object from another object.
|
311
|
+
"""
|
202
312
|
|
203
313
|
@abstractmethod
|
204
314
|
def resolve_update_conflict(self, other: Self) -> str:
|
@@ -213,7 +323,10 @@ class ResolveUpdateConflict(Base):
|
|
213
323
|
|
214
324
|
|
215
325
|
class Introspect(Base):
|
216
|
-
"""Class that provides a method to introspect the object.
|
326
|
+
"""Class that provides a method to introspect the object.
|
327
|
+
|
328
|
+
This class includes a method to perform internal introspection of the object.
|
329
|
+
"""
|
217
330
|
|
218
331
|
@abstractmethod
|
219
332
|
def introspect(self) -> str:
|
@@ -225,7 +338,10 @@ class Introspect(Base):
|
|
225
338
|
|
226
339
|
|
227
340
|
class WithBriefing(Named, Described):
|
228
|
-
"""Class that provides a briefing based on the name and description.
|
341
|
+
"""Class that provides a briefing based on the name and description.
|
342
|
+
|
343
|
+
This class combines the name and description attributes to provide a brief summary of the object.
|
344
|
+
"""
|
229
345
|
|
230
346
|
@property
|
231
347
|
def briefing(self) -> str:
|
@@ -238,15 +354,29 @@ class WithBriefing(Named, Described):
|
|
238
354
|
|
239
355
|
|
240
356
|
class UnsortGenerate(GenerateJsonSchema):
|
241
|
-
"""Class that provides a reverse JSON schema of the model.
|
357
|
+
"""Class that provides a reverse JSON schema of the model.
|
358
|
+
|
359
|
+
This class overrides the sorting behavior of the JSON schema generation to maintain the original order.
|
360
|
+
"""
|
242
361
|
|
243
362
|
def sort(self, value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue:
|
244
|
-
"""Not sort.
|
363
|
+
"""Not sort.
|
364
|
+
|
365
|
+
Args:
|
366
|
+
value (JsonSchemaValue): The JSON schema value to sort.
|
367
|
+
parent_key (str | None): The parent key of the JSON schema value.
|
368
|
+
|
369
|
+
Returns:
|
370
|
+
JsonSchemaValue: The JSON schema value without sorting.
|
371
|
+
"""
|
245
372
|
return value
|
246
373
|
|
247
374
|
|
248
375
|
class WithFormatedJsonSchema(Base):
|
249
|
-
"""Class that provides a formatted JSON schema of the model.
|
376
|
+
"""Class that provides a formatted JSON schema of the model.
|
377
|
+
|
378
|
+
This class includes a method to generate a formatted JSON schema of the model.
|
379
|
+
"""
|
250
380
|
|
251
381
|
@classmethod
|
252
382
|
def formated_json_schema(cls) -> str:
|
@@ -262,25 +392,26 @@ class WithFormatedJsonSchema(Base):
|
|
262
392
|
|
263
393
|
|
264
394
|
class CreateJsonObjPrompt(WithFormatedJsonSchema):
|
265
|
-
"""Class that provides a prompt for creating a JSON object.
|
395
|
+
"""Class that provides a prompt for creating a JSON object.
|
396
|
+
|
397
|
+
This class includes a method to create a prompt for creating a JSON object based on the model's schema and a requirement.
|
398
|
+
"""
|
266
399
|
|
267
400
|
@classmethod
|
268
401
|
@overload
|
269
402
|
def create_json_prompt(cls, requirement: List[str]) -> List[str]: ...
|
270
|
-
|
271
403
|
@classmethod
|
272
404
|
@overload
|
273
405
|
def create_json_prompt(cls, requirement: str) -> str: ...
|
274
|
-
|
275
406
|
@classmethod
|
276
407
|
def create_json_prompt(cls, requirement: str | List[str]) -> str | List[str]:
|
277
408
|
"""Create the prompt for creating a JSON object with given requirement.
|
278
409
|
|
279
410
|
Args:
|
280
|
-
requirement (str): The requirement for the JSON object.
|
411
|
+
requirement (str | List[str]): The requirement for the JSON object.
|
281
412
|
|
282
413
|
Returns:
|
283
|
-
str: The prompt for creating a JSON object with given requirement.
|
414
|
+
str | List[str]: The prompt for creating a JSON object with given requirement.
|
284
415
|
"""
|
285
416
|
if isinstance(requirement, str):
|
286
417
|
return TEMPLATE_MANAGER.render_template(
|
@@ -297,7 +428,10 @@ class CreateJsonObjPrompt(WithFormatedJsonSchema):
|
|
297
428
|
|
298
429
|
|
299
430
|
class InstantiateFromString(Base):
|
300
|
-
"""Class that provides a method to instantiate the class from a string.
|
431
|
+
"""Class that provides a method to instantiate the class from a string.
|
432
|
+
|
433
|
+
This class includes a method to instantiate the class from a JSON string representation.
|
434
|
+
"""
|
301
435
|
|
302
436
|
@classmethod
|
303
437
|
def instantiate_from_string(cls, string: str) -> Self | None:
|
@@ -309,19 +443,37 @@ class InstantiateFromString(Base):
|
|
309
443
|
Returns:
|
310
444
|
Self | None: The instance of the class or None if the string is not valid.
|
311
445
|
"""
|
312
|
-
|
446
|
+
obj = JsonCapture.convert_with(string, cls.model_validate_json)
|
447
|
+
logger.debug(f"Instantiate `{cls.__name__}` from string, {'Failed' if obj is None else 'Success'}.")
|
448
|
+
return obj
|
313
449
|
|
314
450
|
|
315
451
|
class ProposedAble(CreateJsonObjPrompt, InstantiateFromString):
|
316
|
-
"""Class that provides a method to propose a JSON object based on the requirement.
|
452
|
+
"""Class that provides a method to propose a JSON object based on the requirement.
|
453
|
+
|
454
|
+
This class combines the functionality to create a prompt for a JSON object and instantiate it from a string.
|
455
|
+
"""
|
456
|
+
|
457
|
+
|
458
|
+
class SketchedAble(ProposedAble, Display):
|
459
|
+
"""Class that provides a method to scratch the object.
|
317
460
|
|
461
|
+
This class combines the functionality to propose a JSON object, instantiate it from a string, and display it.
|
462
|
+
"""
|
318
463
|
|
319
|
-
|
320
|
-
|
464
|
+
|
465
|
+
class ProposedUpdateAble(SketchedAble, UpdateFrom, ABC):
|
466
|
+
"""Make the obj can be updated from the proposed obj in place.
|
467
|
+
|
468
|
+
This class provides the ability to update an object in place from a proposed object.
|
469
|
+
"""
|
321
470
|
|
322
471
|
|
323
472
|
class FinalizedDumpAble(Base):
|
324
|
-
"""Class that provides a method to finalize the dump of the object.
|
473
|
+
"""Class that provides a method to finalize the dump of the object.
|
474
|
+
|
475
|
+
This class includes methods to finalize the JSON representation of the object and dump it to a file.
|
476
|
+
"""
|
325
477
|
|
326
478
|
def finalized_dump(self) -> str:
|
327
479
|
"""Finalize the dump of the object.
|
@@ -344,12 +496,11 @@ class FinalizedDumpAble(Base):
|
|
344
496
|
return self
|
345
497
|
|
346
498
|
|
347
|
-
class CensoredAble(ProposedAble, FinalizedDumpAble):
|
348
|
-
"""Class that provides a method to censor the object."""
|
349
|
-
|
350
|
-
|
351
499
|
class WithDependency(Base):
|
352
|
-
"""Class that manages file dependencies.
|
500
|
+
"""Class that manages file dependencies.
|
501
|
+
|
502
|
+
This class includes methods to manage file dependencies required for reading or writing.
|
503
|
+
"""
|
353
504
|
|
354
505
|
dependencies: List[str] = Field(default_factory=list)
|
355
506
|
"""The file dependencies which is needed to read or write to meet a specific requirement, a list of file paths."""
|
@@ -437,7 +588,10 @@ class WithDependency(Base):
|
|
437
588
|
|
438
589
|
|
439
590
|
class Vectorizable(Base):
|
440
|
-
"""Class that prepares the vectorization of the model.
|
591
|
+
"""Class that prepares the vectorization of the model.
|
592
|
+
|
593
|
+
This class includes methods to prepare the model for vectorization, ensuring it fits within a specified token length.
|
594
|
+
"""
|
441
595
|
|
442
596
|
def _prepare_vectorization_inner(self) -> str:
|
443
597
|
return rtoml.dumps(self.model_dump())
|
@@ -446,20 +600,29 @@ class Vectorizable(Base):
|
|
446
600
|
def prepare_vectorization(self, max_length: Optional[int] = None) -> str:
|
447
601
|
"""Prepare the vectorization of the model.
|
448
602
|
|
603
|
+
Args:
|
604
|
+
max_length (Optional[int]): The maximum token length for the vectorization. Defaults to the configuration.
|
605
|
+
|
449
606
|
Returns:
|
450
607
|
str: The prepared vectorization of the model.
|
608
|
+
|
609
|
+
Raises:
|
610
|
+
ValueError: If the chunk exceeds the maximum sequence length.
|
451
611
|
"""
|
452
612
|
max_length = max_length or configs.embedding.max_sequence_length
|
453
613
|
chunk = self._prepare_vectorization_inner()
|
454
614
|
if max_length and (length := token_counter(text=chunk)) > max_length:
|
455
|
-
logger.error(err := f"Chunk exceeds maximum sequence length {max_length}, got {length},see {chunk}")
|
615
|
+
logger.error(err := f"Chunk exceeds maximum sequence length {max_length}, got {length}, see {chunk}")
|
456
616
|
raise ValueError(err)
|
457
617
|
|
458
618
|
return chunk
|
459
619
|
|
460
620
|
|
461
621
|
class ScopedConfig(Base):
|
462
|
-
"""Class that manages a scoped configuration.
|
622
|
+
"""Class that manages a scoped configuration.
|
623
|
+
|
624
|
+
This class includes attributes and methods to manage configuration settings scoped to the instance.
|
625
|
+
"""
|
463
626
|
|
464
627
|
llm_api_endpoint: Optional[HttpUrl] = None
|
465
628
|
"""The OpenAI API endpoint."""
|
@@ -517,15 +680,19 @@ class ScopedConfig(Base):
|
|
517
680
|
|
518
681
|
embedding_dimensions: Optional[PositiveInt] = None
|
519
682
|
"""The dimensions of the embedding."""
|
683
|
+
|
520
684
|
embedding_caching: Optional[bool] = False
|
521
685
|
"""Whether to cache the embedding result."""
|
522
686
|
|
523
687
|
milvus_uri: Optional[HttpUrl] = Field(default=None)
|
524
688
|
"""The URI of the Milvus server."""
|
689
|
+
|
525
690
|
milvus_token: Optional[SecretStr] = Field(default=None)
|
526
691
|
"""The token for the Milvus server."""
|
692
|
+
|
527
693
|
milvus_timeout: Optional[PositiveFloat] = Field(default=None)
|
528
694
|
"""The timeout for the Milvus server."""
|
695
|
+
|
529
696
|
milvus_dimensions: Optional[PositiveInt] = Field(default=None)
|
530
697
|
"""The dimensions of the Milvus server."""
|
531
698
|
|
@@ -567,3 +734,91 @@ class ScopedConfig(Base):
|
|
567
734
|
if (attr := getattr(self, attr_name)) is not None and getattr(other, attr_name) is None:
|
568
735
|
setattr(other, attr_name, attr)
|
569
736
|
return self
|
737
|
+
|
738
|
+
|
739
|
+
class Patch[T](ProposedAble):
|
740
|
+
"""Base class for patches.
|
741
|
+
|
742
|
+
This class provides a base implementation for patches that can be applied to other objects.
|
743
|
+
"""
|
744
|
+
|
745
|
+
def apply(self, other: T) -> T:
|
746
|
+
"""Apply the patch to another instance.
|
747
|
+
|
748
|
+
Args:
|
749
|
+
other (T): The instance to apply the patch to.
|
750
|
+
|
751
|
+
Returns:
|
752
|
+
T: The instance with the patch applied.
|
753
|
+
|
754
|
+
Raises:
|
755
|
+
ValueError: If a field in the patch is not found in the target instance.
|
756
|
+
"""
|
757
|
+
for field in self.__class__.model_fields:
|
758
|
+
if not hasattr(other, field):
|
759
|
+
raise ValueError(f"{field} not found in {other}, are you applying to the wrong type?")
|
760
|
+
setattr(other, field, getattr(self, field))
|
761
|
+
return other
|
762
|
+
|
763
|
+
def as_kwargs(self) -> Dict[str, Any]:
|
764
|
+
"""Get the kwargs of the patch."""
|
765
|
+
return self.model_dump()
|
766
|
+
|
767
|
+
@staticmethod
|
768
|
+
def ref_cls() -> Optional[Type[BaseModel]]:
|
769
|
+
"""Get the reference class of the model."""
|
770
|
+
return None
|
771
|
+
|
772
|
+
@classmethod
|
773
|
+
def formated_json_schema(cls) -> str:
|
774
|
+
"""Get the JSON schema of the model in a formatted string.
|
775
|
+
|
776
|
+
Returns:
|
777
|
+
str: The JSON schema of the model in a formatted string.
|
778
|
+
"""
|
779
|
+
my_schema = cls.model_json_schema(schema_generator=UnsortGenerate)
|
780
|
+
if (ref_cls := cls.ref_cls()) is not None:
|
781
|
+
# copy the desc info of each corresponding fields from `ref_cls`
|
782
|
+
for field_name, field_info in cls.model_fields.items():
|
783
|
+
if (ref_field := getattr(ref_cls, field_name, None)) is not None:
|
784
|
+
if (desc := ref_field.field_info.description) is not None:
|
785
|
+
my_schema["properties"][field_name]["description"] = desc
|
786
|
+
if (example := ref_field.field_info.examples) is not None:
|
787
|
+
my_schema["properties"][field_name]["examples"] = example
|
788
|
+
|
789
|
+
return orjson.dumps(
|
790
|
+
my_schema,
|
791
|
+
option=orjson.OPT_INDENT_2,
|
792
|
+
).decode()
|
793
|
+
|
794
|
+
|
795
|
+
class SequencePatch[T](ProposedUpdateAble):
|
796
|
+
"""Base class for patches.
|
797
|
+
|
798
|
+
This class provides a base implementation for patches that can be applied to sequences of objects.
|
799
|
+
"""
|
800
|
+
|
801
|
+
tweaked: List[T]
|
802
|
+
"""Tweaked content list"""
|
803
|
+
|
804
|
+
def update_from_inner(self, other: Self) -> Self:
|
805
|
+
"""Updates the current instance with the attributes of another instance.
|
806
|
+
|
807
|
+
Args:
|
808
|
+
other (Self): The other instance to update from.
|
809
|
+
|
810
|
+
Returns:
|
811
|
+
Self: The current instance with updated attributes.
|
812
|
+
"""
|
813
|
+
self.tweaked.clear()
|
814
|
+
self.tweaked.extend(other.tweaked)
|
815
|
+
return self
|
816
|
+
|
817
|
+
@classmethod
|
818
|
+
def default(cls) -> Self:
|
819
|
+
"""Defaults to empty list.
|
820
|
+
|
821
|
+
Returns:
|
822
|
+
Self: A new instance with an empty list of tweaks.
|
823
|
+
"""
|
824
|
+
return cls(tweaked=[])
|
@@ -1,7 +1,7 @@
|
|
1
1
|
"""This module contains the types for the keyword arguments of the methods in the models module."""
|
2
2
|
|
3
3
|
from importlib.util import find_spec
|
4
|
-
from typing import Any, Dict, Required, TypedDict
|
4
|
+
from typing import Any, Dict, List, Optional, Required, TypedDict
|
5
5
|
|
6
6
|
from litellm.caching.caching import CacheMode
|
7
7
|
from litellm.types.caching import CachingSupportedCallTypes
|
@@ -95,11 +95,30 @@ class ValidateKwargs[T](GenerateKwargs, total=False):
|
|
95
95
|
such as limiting the number of validation attempts.
|
96
96
|
"""
|
97
97
|
|
98
|
-
default: T
|
98
|
+
default: Optional[T]
|
99
99
|
max_validations: int
|
100
100
|
co_extractor: GenerateKwargs
|
101
101
|
|
102
102
|
|
103
|
+
class CompositeScoreKwargs(ValidateKwargs[List[Dict[str, float]]], total=False):
|
104
|
+
"""Arguments for composite score generation operations.
|
105
|
+
|
106
|
+
Extends GenerateKwargs with parameters for generating composite scores
|
107
|
+
based on specific criteria and weights.
|
108
|
+
"""
|
109
|
+
|
110
|
+
topic: str
|
111
|
+
criteria: set[str]
|
112
|
+
weights: Dict[str, float]
|
113
|
+
manual: Dict[str, str]
|
114
|
+
|
115
|
+
|
116
|
+
class BestKwargs(CompositeScoreKwargs, total=False):
|
117
|
+
"""Arguments for choose top-k operations."""
|
118
|
+
|
119
|
+
k: int
|
120
|
+
|
121
|
+
|
103
122
|
class ReviewInnerKwargs[T](ValidateKwargs[T], total=False):
|
104
123
|
"""Arguments for content review operations."""
|
105
124
|
|
@@ -118,22 +137,9 @@ class ReviewKwargs[T](ReviewInnerKwargs[T], total=False):
|
|
118
137
|
topic: Required[str]
|
119
138
|
|
120
139
|
|
121
|
-
class
|
122
|
-
"""Arguments for content
|
123
|
-
|
124
|
-
Extends GenerateKwargs with parameters for correcting content based on
|
125
|
-
specific criteria and templates.
|
126
|
-
"""
|
127
|
-
|
128
|
-
reference: str
|
129
|
-
supervisor_check: bool
|
130
|
-
|
131
|
-
|
132
|
-
class CensoredCorrectKwargs[T](ReviewInnerKwargs[T], total=False):
|
133
|
-
"""Arguments for content censorship operations."""
|
134
|
-
|
140
|
+
class ReferencedKwargs[T](ValidateKwargs[T], total=False):
|
141
|
+
"""Arguments for content review operations."""
|
135
142
|
reference: str
|
136
|
-
supervisor_check: bool
|
137
143
|
|
138
144
|
|
139
145
|
# noinspection PyTypedDict
|
fabricatio/models/task.py
CHANGED
@@ -6,13 +6,13 @@ It includes methods to manage the task's lifecycle, such as starting, finishing,
|
|
6
6
|
from asyncio import Queue
|
7
7
|
from typing import Any, List, Optional, Self
|
8
8
|
|
9
|
-
from fabricatio._rust_instances import TEMPLATE_MANAGER
|
10
9
|
from fabricatio.config import configs
|
11
10
|
from fabricatio.core import env
|
12
11
|
from fabricatio.journal import logger
|
13
12
|
from fabricatio.models.events import Event, EventLike
|
14
13
|
from fabricatio.models.generic import ProposedAble, WithBriefing, WithDependency
|
15
14
|
from fabricatio.models.utils import TaskStatus
|
15
|
+
from fabricatio.rust_instances import TEMPLATE_MANAGER
|
16
16
|
from pydantic import Field, PrivateAttr
|
17
17
|
|
18
18
|
|