fabricatio 0.2.8.dev2__cp312-cp312-win_amd64.whl → 0.2.8.dev3__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/_rust.cp312-win_amd64.pyd +0 -0
- fabricatio/_rust.pyi +1 -1
- fabricatio/actions/article.py +72 -56
- fabricatio/actions/article_rag.py +4 -5
- fabricatio/actions/output.py +4 -3
- fabricatio/actions/rag.py +3 -3
- fabricatio/capabilities/check.py +97 -0
- fabricatio/capabilities/correct.py +7 -6
- fabricatio/capabilities/propose.py +20 -4
- fabricatio/capabilities/rag.py +3 -2
- fabricatio/capabilities/rating.py +7 -10
- fabricatio/capabilities/review.py +18 -187
- fabricatio/capabilities/task.py +8 -9
- fabricatio/config.py +2 -0
- fabricatio/models/action.py +6 -2
- fabricatio/models/extra/advanced_judge.py +7 -7
- fabricatio/models/extra/article_base.py +45 -8
- fabricatio/models/extra/article_essence.py +40 -209
- fabricatio/models/extra/article_main.py +1 -1
- fabricatio/models/extra/problem.py +120 -0
- fabricatio/models/extra/rule.py +23 -0
- fabricatio/models/generic.py +28 -33
- fabricatio/models/role.py +4 -1
- fabricatio/models/usages.py +8 -6
- fabricatio/models/utils.py +0 -46
- fabricatio/utils.py +54 -0
- {fabricatio-0.2.8.dev2.data → fabricatio-0.2.8.dev3.data}/scripts/tdown.exe +0 -0
- {fabricatio-0.2.8.dev2.dist-info → fabricatio-0.2.8.dev3.dist-info}/METADATA +2 -1
- fabricatio-0.2.8.dev3.dist-info/RECORD +53 -0
- fabricatio-0.2.8.dev2.dist-info/RECORD +0 -49
- {fabricatio-0.2.8.dev2.dist-info → fabricatio-0.2.8.dev3.dist-info}/WHEEL +0 -0
- {fabricatio-0.2.8.dev2.dist-info → fabricatio-0.2.8.dev3.dist-info}/licenses/LICENSE +0 -0
Binary file
|
fabricatio/_rust.pyi
CHANGED
fabricatio/actions/article.py
CHANGED
@@ -15,7 +15,8 @@ from fabricatio.models.extra.article_main import Article
|
|
15
15
|
from fabricatio.models.extra.article_outline import ArticleOutline
|
16
16
|
from fabricatio.models.extra.article_proposal import ArticleProposal
|
17
17
|
from fabricatio.models.task import Task
|
18
|
-
from fabricatio.
|
18
|
+
from fabricatio.utils import ok
|
19
|
+
from more_itertools import filter_map
|
19
20
|
|
20
21
|
|
21
22
|
class ExtractArticleEssence(Action):
|
@@ -32,36 +33,62 @@ class ExtractArticleEssence(Action):
|
|
32
33
|
async def _execute(
|
33
34
|
self,
|
34
35
|
task_input: Task,
|
35
|
-
reader: Callable[[str], str] = lambda p: Path(p).read_text(encoding="utf-8"),
|
36
|
+
reader: Callable[[str], Optional[str]] = lambda p: Path(p).read_text(encoding="utf-8"),
|
36
37
|
**_,
|
37
|
-
) ->
|
38
|
+
) -> List[ArticleEssence]:
|
38
39
|
if not task_input.dependencies:
|
39
40
|
logger.info(err := "Task not approved, since no dependencies are provided.")
|
40
41
|
raise RuntimeError(err)
|
41
|
-
|
42
|
+
logger.info(f"Extracting article essence from {len(task_input.dependencies)} files.")
|
42
43
|
# trim the references
|
43
|
-
contents =
|
44
|
-
|
44
|
+
contents = list(filter_map(reader, task_input.dependencies))
|
45
|
+
logger.info(f"Read {len(task_input.dependencies)} to get {len(contents)} contents.")
|
46
|
+
|
47
|
+
out = []
|
48
|
+
|
49
|
+
for ess in await self.propose(
|
50
|
+
ArticleEssence,
|
51
|
+
[
|
52
|
+
f"{c}\n\n\nBased the provided academic article above, you need to extract the essence from it."
|
53
|
+
for c in contents
|
54
|
+
],
|
55
|
+
):
|
56
|
+
if ess is None:
|
57
|
+
logger.warning("Could not extract article essence")
|
58
|
+
else:
|
59
|
+
out.append(ess)
|
60
|
+
logger.info(f"Extracted {len(out)} article essence from {len(task_input.dependencies)} files.")
|
61
|
+
return out
|
45
62
|
|
46
63
|
|
47
64
|
class FixArticleEssence(Action):
|
48
65
|
"""Fix the article essence based on the bibtex key."""
|
49
66
|
|
67
|
+
output_key: str = "fixed_article_essence"
|
68
|
+
"""The key of the output data."""
|
69
|
+
|
50
70
|
async def _execute(
|
51
71
|
self,
|
52
72
|
bib_mgr: BibManager,
|
53
73
|
article_essence: List[ArticleEssence],
|
54
74
|
**_,
|
55
|
-
) ->
|
75
|
+
) -> List[ArticleEssence]:
|
76
|
+
out = []
|
77
|
+
count = 0
|
56
78
|
for a in article_essence:
|
57
79
|
if key := (bib_mgr.get_cite_key(a.title) or bib_mgr.get_cite_key_fuzzy(a.title)):
|
58
80
|
a.title = bib_mgr.get_title_by_key(key) or a.title
|
59
81
|
a.authors = bib_mgr.get_author_by_key(key) or a.authors
|
60
82
|
a.publication_year = bib_mgr.get_year_by_key(key) or a.publication_year
|
61
83
|
a.bibtex_cite_key = key
|
62
|
-
logger.info(f
|
84
|
+
logger.info(f"Updated {a.title} with {key}")
|
85
|
+
out.append(a)
|
63
86
|
else:
|
64
87
|
logger.warning(f"No key found for {a.title}")
|
88
|
+
count += 1
|
89
|
+
if count:
|
90
|
+
logger.warning(f"{count} articles have no key")
|
91
|
+
return out
|
65
92
|
|
66
93
|
|
67
94
|
class GenerateArticleProposal(Action):
|
@@ -97,7 +124,6 @@ class GenerateArticleProposal(Action):
|
|
97
124
|
)
|
98
125
|
)
|
99
126
|
),
|
100
|
-
**self.prepend_sys_msg(),
|
101
127
|
),
|
102
128
|
"Could not generate the proposal.",
|
103
129
|
).update_ref(briefing)
|
@@ -122,7 +148,6 @@ class GenerateInitialOutline(Action):
|
|
122
148
|
await self.propose(
|
123
149
|
ArticleOutline,
|
124
150
|
article_proposal.as_prompt(),
|
125
|
-
**self.prepend_sys_msg(),
|
126
151
|
),
|
127
152
|
"Could not generate the initial outline.",
|
128
153
|
).update_ref(article_proposal)
|
@@ -190,90 +215,81 @@ class FixIllegalReferences(Action):
|
|
190
215
|
"Could not generate the rating manual.",
|
191
216
|
)
|
192
217
|
|
193
|
-
while pack := article_outline.find_illegal_ref():
|
194
|
-
|
218
|
+
while pack := article_outline.find_illegal_ref(gather_identical=True):
|
219
|
+
refs, err = ok(pack)
|
195
220
|
logger.warning(f"Found illegal referring error: {err}")
|
196
|
-
ok(
|
197
|
-
await self.
|
198
|
-
|
221
|
+
corrected_ref = ok(
|
222
|
+
await self.correct_obj(
|
223
|
+
refs[0], # pyright: ignore [reportIndexIssue]
|
199
224
|
reference=f"# Original Article Outline\n{article_outline.display()}\n# Error Need to be fixed\n{err}",
|
200
225
|
topic=ref_topic,
|
201
226
|
rating_manual=ref_manual,
|
202
227
|
supervisor_check=supervisor_check,
|
203
228
|
)
|
204
229
|
)
|
230
|
+
for ref in refs:
|
231
|
+
ref.update_from(corrected_ref) # pyright: ignore [reportAttributeAccessIssue]
|
232
|
+
|
205
233
|
return article_outline.update_ref(article_outline)
|
206
234
|
|
207
235
|
|
208
|
-
class
|
209
|
-
"""Tweak the
|
236
|
+
class TweakOutlineForwardRef(Action, AdvancedJudge):
|
237
|
+
"""Tweak the forward references in the article outline.
|
210
238
|
|
211
|
-
Ensures that the
|
239
|
+
Ensures that the conclusions of the current chapter effectively support the analysis of subsequent chapters.
|
212
240
|
"""
|
213
241
|
|
214
|
-
output_key: str = "
|
242
|
+
output_key: str = "article_outline_fw_ref_checked"
|
215
243
|
|
216
244
|
async def _execute(self, article_outline: ArticleOutline, supervisor_check: bool = False, **cxt) -> ArticleOutline:
|
217
|
-
|
218
|
-
|
219
|
-
|
220
|
-
|
221
|
-
"
|
245
|
+
return await self._inner(
|
246
|
+
article_outline,
|
247
|
+
supervisor_check,
|
248
|
+
topic="Ensure conclusions support the analysis of subsequent chapters, sections or subsections.",
|
249
|
+
field_name="support_to",
|
222
250
|
)
|
223
251
|
|
252
|
+
async def _inner(
|
253
|
+
self, article_outline: ArticleOutline, supervisor_check: bool, topic: str, field_name: str
|
254
|
+
) -> ArticleOutline:
|
255
|
+
tweak_support_to_manual = ok(
|
256
|
+
await self.draft_rating_manual(topic),
|
257
|
+
"Could not generate the rating manual.",
|
258
|
+
)
|
224
259
|
for a in article_outline.iter_dfs():
|
225
260
|
if await self.evidently_judge(
|
226
261
|
f"{article_outline.as_prompt()}\n\n{a.display()}\n"
|
227
|
-
f"Does the `{a.__class__.__name__}`'s `
|
262
|
+
f"Does the `{a.__class__.__name__}`'s `{field_name}` field need to be extended or tweaked?"
|
228
263
|
):
|
229
264
|
patch = ArticleRefPatch.default()
|
230
|
-
patch.tweaked = a
|
265
|
+
patch.tweaked = getattr(a, field_name)
|
231
266
|
|
232
267
|
await self.correct_obj_inplace(
|
233
268
|
patch,
|
234
269
|
topic=topic,
|
235
|
-
reference=f"{article_outline.as_prompt()}\nThe Article component whose `
|
236
|
-
rating_manual=
|
270
|
+
reference=f"{article_outline.as_prompt()}\nThe Article component whose `{field_name}` field needs to be extended or tweaked",
|
271
|
+
rating_manual=tweak_support_to_manual,
|
237
272
|
supervisor_check=supervisor_check,
|
238
273
|
)
|
239
|
-
|
240
274
|
return article_outline
|
241
275
|
|
242
276
|
|
243
|
-
class TweakOutlineForwardRef
|
244
|
-
"""Tweak the
|
277
|
+
class TweakOutlineBackwardRef(TweakOutlineForwardRef):
|
278
|
+
"""Tweak the backward references in the article outline.
|
245
279
|
|
246
|
-
Ensures that the
|
280
|
+
Ensures that the prerequisites of the current chapter are correctly referenced in the `depend_on` field.
|
247
281
|
"""
|
248
282
|
|
249
|
-
output_key: str = "
|
283
|
+
output_key: str = "article_outline_bw_ref_checked"
|
250
284
|
|
251
285
|
async def _execute(self, article_outline: ArticleOutline, supervisor_check: bool = False, **cxt) -> ArticleOutline:
|
252
|
-
|
253
|
-
|
254
|
-
|
255
|
-
|
256
|
-
"
|
286
|
+
return await self._inner(
|
287
|
+
article_outline,
|
288
|
+
supervisor_check,
|
289
|
+
topic="Ensure the dependencies of the current chapter are neither abused nor missing.",
|
290
|
+
field_name="depend_on",
|
257
291
|
)
|
258
292
|
|
259
|
-
for a in article_outline.iter_dfs():
|
260
|
-
if await self.evidently_judge(
|
261
|
-
f"{article_outline.as_prompt()}\n\n{a.display()}\n"
|
262
|
-
f"Does the `{a.__class__.__name__}`'s `support_to` field need to be extended or tweaked?"
|
263
|
-
):
|
264
|
-
patch = ArticleRefPatch.default()
|
265
|
-
patch.tweaked = a.support_to
|
266
|
-
|
267
|
-
await self.correct_obj_inplace(
|
268
|
-
patch,
|
269
|
-
topic=topic,
|
270
|
-
reference=f"{article_outline.as_prompt()}\nThe Article component whose `support_to` field needs to be extended or tweaked",
|
271
|
-
rating_manual=tweak_support_to_manual,
|
272
|
-
supervisor_check=supervisor_check,
|
273
|
-
)
|
274
|
-
|
275
|
-
return article_outline
|
276
|
-
|
277
293
|
|
278
294
|
class GenerateArticle(Action):
|
279
295
|
"""Generate the article based on the outline."""
|
@@ -6,7 +6,7 @@ from typing import Dict, Optional
|
|
6
6
|
from fabricatio.capabilities.rag import RAG
|
7
7
|
from fabricatio.models.action import Action
|
8
8
|
from fabricatio.models.extra.article_main import Article, ArticleParagraphPatch, ArticleSubsection
|
9
|
-
from fabricatio.
|
9
|
+
from fabricatio.utils import ok
|
10
10
|
|
11
11
|
|
12
12
|
class TweakArticleRAG(Action, RAG):
|
@@ -25,7 +25,8 @@ class TweakArticleRAG(Action, RAG):
|
|
25
25
|
"Single author: 'Author1 (YYYY)'"
|
26
26
|
"Multiple citations: 'Author1 (YYYY), Author2 (YYYY)'"
|
27
27
|
"Prioritize formulas from reference highlights."
|
28
|
-
"Specify authors/years only
|
28
|
+
"Specify authors/years only."
|
29
|
+
"You can create numeric citation numbers for article whose `bibtex_cite_key` is 'wangWind2024' by using notation like `#cite(<wangWind2024>)`."
|
29
30
|
"Paragraphs must exceed 2-3 sentences",
|
30
31
|
supervisor_check: bool = False,
|
31
32
|
parallel: bool = False,
|
@@ -41,9 +42,7 @@ class TweakArticleRAG(Action, RAG):
|
|
41
42
|
criteria_count=13,
|
42
43
|
)
|
43
44
|
|
44
|
-
tweak_manual = ok(
|
45
|
-
await self.draft_rating_manual(topic, criteria=criteria, co_extractor={"model": "openai/qwen-max"})
|
46
|
-
)
|
45
|
+
tweak_manual = ok(await self.draft_rating_manual(topic, criteria=criteria))
|
47
46
|
self.view(collection_name)
|
48
47
|
|
49
48
|
if parallel:
|
fabricatio/actions/output.py
CHANGED
@@ -7,7 +7,7 @@ from fabricatio.journal import logger
|
|
7
7
|
from fabricatio.models.action import Action
|
8
8
|
from fabricatio.models.generic import FinalizedDumpAble, PersistentAble
|
9
9
|
from fabricatio.models.task import Task
|
10
|
-
from fabricatio.
|
10
|
+
from fabricatio.utils import ok
|
11
11
|
|
12
12
|
|
13
13
|
class DumpFinalizedOutput(Action):
|
@@ -67,17 +67,18 @@ class PersistentAll(Action):
|
|
67
67
|
|
68
68
|
for k, v in cxt.items():
|
69
69
|
final_dir = persist_dir.joinpath(k)
|
70
|
-
final_dir.mkdir(parents=True, exist_ok=True)
|
71
70
|
if isinstance(v, PersistentAble):
|
71
|
+
final_dir.mkdir(parents=True, exist_ok=True)
|
72
72
|
v.persist(final_dir)
|
73
73
|
count += 1
|
74
74
|
if isinstance(v, Iterable) and any(
|
75
75
|
persistent_ables := (pers for pers in v if isinstance(pers, PersistentAble))
|
76
76
|
):
|
77
|
+
final_dir.mkdir(parents=True, exist_ok=True)
|
77
78
|
for per in persistent_ables:
|
78
79
|
per.persist(final_dir)
|
79
80
|
count += 1
|
80
|
-
|
81
|
+
logger.info(f"Persisted {count} objects to {persist_dir}")
|
81
82
|
return count
|
82
83
|
|
83
84
|
|
fabricatio/actions/rag.py
CHANGED
@@ -5,7 +5,7 @@ from typing import List, Optional
|
|
5
5
|
from fabricatio.capabilities.rag import RAG
|
6
6
|
from fabricatio.journal import logger
|
7
7
|
from fabricatio.models.action import Action
|
8
|
-
from fabricatio.models.generic import
|
8
|
+
from fabricatio.models.generic import Vectorizable
|
9
9
|
from fabricatio.models.task import Task
|
10
10
|
from questionary import text
|
11
11
|
|
@@ -15,7 +15,7 @@ class InjectToDB(Action, RAG):
|
|
15
15
|
|
16
16
|
output_key: str = "collection_name"
|
17
17
|
|
18
|
-
async def _execute[T:
|
18
|
+
async def _execute[T: Vectorizable](
|
19
19
|
self, to_inject: Optional[T] | List[Optional[T]], collection_name: str = "my_collection",override_inject:bool=False, **_
|
20
20
|
) -> Optional[str]:
|
21
21
|
if not isinstance(to_inject, list):
|
@@ -27,7 +27,7 @@ class InjectToDB(Action, RAG):
|
|
27
27
|
[
|
28
28
|
t.prepare_vectorization(self.embedding_max_sequence_length)
|
29
29
|
for t in to_inject
|
30
|
-
if isinstance(t,
|
30
|
+
if isinstance(t, Vectorizable)
|
31
31
|
],
|
32
32
|
)
|
33
33
|
|
@@ -0,0 +1,97 @@
|
|
1
|
+
"""A class that provides the capability to check strings and objects against rules and guidelines."""
|
2
|
+
from typing import Optional, Unpack
|
3
|
+
|
4
|
+
from fabricatio import TEMPLATE_MANAGER
|
5
|
+
from fabricatio.capabilities.advanced_judge import AdvancedJudge
|
6
|
+
from fabricatio.capabilities.propose import Propose
|
7
|
+
from fabricatio.config import configs
|
8
|
+
from fabricatio.models.extra.problem import Improvement
|
9
|
+
from fabricatio.models.extra.rule import Rule, RuleSet
|
10
|
+
from fabricatio.models.generic import Display, WithBriefing
|
11
|
+
from fabricatio.models.kwargs_types import ValidateKwargs
|
12
|
+
from fabricatio.utils import override_kwargs
|
13
|
+
|
14
|
+
|
15
|
+
class Check(AdvancedJudge, Propose):
|
16
|
+
"""Class that provides the capability to validate strings/objects against predefined rules and guidelines."""
|
17
|
+
|
18
|
+
async def draft_ruleset(
|
19
|
+
self, ruleset_requirement: str, **kwargs: Unpack[ValidateKwargs[RuleSet]]
|
20
|
+
) -> Optional[RuleSet]:
|
21
|
+
"""Generate a rule set based on specified requirements.
|
22
|
+
|
23
|
+
Args:
|
24
|
+
ruleset_requirement (str): Description of desired rule set characteristics
|
25
|
+
**kwargs: Validation configuration parameters
|
26
|
+
|
27
|
+
Returns:
|
28
|
+
Optional[RuleSet]: Generated rule set if successful
|
29
|
+
"""
|
30
|
+
return await self.propose(RuleSet, ruleset_requirement, **kwargs)
|
31
|
+
|
32
|
+
async def draft_rule(self, rule_requirement: str, **kwargs: Unpack[ValidateKwargs[Rule]]) -> Optional[Rule]:
|
33
|
+
"""Create a specific rule based on given specifications.
|
34
|
+
|
35
|
+
Args:
|
36
|
+
rule_requirement (str): Detailed rule description requirements
|
37
|
+
**kwargs: Validation configuration parameters
|
38
|
+
|
39
|
+
Returns:
|
40
|
+
Optional[Rule]: Generated rule instance if successful
|
41
|
+
"""
|
42
|
+
return await self.propose(Rule, rule_requirement, **kwargs)
|
43
|
+
|
44
|
+
async def check_string(
|
45
|
+
self,
|
46
|
+
input_text: str,
|
47
|
+
rule: Rule,
|
48
|
+
**kwargs: Unpack[ValidateKwargs[Improvement]],
|
49
|
+
) -> Optional[Improvement]:
|
50
|
+
"""Evaluate text against a specific rule.
|
51
|
+
|
52
|
+
Args:
|
53
|
+
input_text (str): Text content to be evaluated
|
54
|
+
rule (Rule): Rule instance used for validation
|
55
|
+
**kwargs: Validation configuration parameters
|
56
|
+
|
57
|
+
Returns:
|
58
|
+
Optional[Improvement]: Suggested improvement if violations found, else None
|
59
|
+
"""
|
60
|
+
if judge := await self.evidently_judge(
|
61
|
+
f"# Content to exam\n{input_text}\n\n# Rule Must to follow\n{rule.display()}\nDoes `Content to exam` provided above violate the `Rule Must to follow` provided above?",
|
62
|
+
**override_kwargs(kwargs, default=None),
|
63
|
+
):
|
64
|
+
return await self.propose(
|
65
|
+
Improvement,
|
66
|
+
TEMPLATE_MANAGER.render_template(
|
67
|
+
configs.templates.check_string_template,
|
68
|
+
{"to_check": input_text, "rule": rule, "judge": judge.display()},
|
69
|
+
),
|
70
|
+
**kwargs,
|
71
|
+
)
|
72
|
+
return None
|
73
|
+
|
74
|
+
async def check_obj[M: (Display, WithBriefing)](
|
75
|
+
self,
|
76
|
+
obj: M,
|
77
|
+
rule: Rule,
|
78
|
+
**kwargs: Unpack[ValidateKwargs[Improvement]],
|
79
|
+
) -> Optional[Improvement]:
|
80
|
+
"""Validate an object against specified rule.
|
81
|
+
|
82
|
+
Args:
|
83
|
+
obj (M): Object implementing Display or WithBriefing interface
|
84
|
+
rule (Rule): Validation rule to apply
|
85
|
+
**kwargs: Validation configuration parameters
|
86
|
+
|
87
|
+
Returns:
|
88
|
+
Optional[Improvement]: Improvement suggestion if issues detected
|
89
|
+
"""
|
90
|
+
if isinstance(obj, Display):
|
91
|
+
input_text = obj.display()
|
92
|
+
elif isinstance(obj, WithBriefing):
|
93
|
+
input_text = obj.briefing
|
94
|
+
else:
|
95
|
+
raise TypeError("obj must be either Display or WithBriefing")
|
96
|
+
|
97
|
+
return await self.check_string(input_text, rule, **kwargs)
|
@@ -8,8 +8,9 @@ based on predefined criteria and templates.
|
|
8
8
|
from typing import Optional, Unpack, cast
|
9
9
|
|
10
10
|
from fabricatio._rust_instances import TEMPLATE_MANAGER
|
11
|
-
from fabricatio.capabilities.review import Review
|
11
|
+
from fabricatio.capabilities.review import Review
|
12
12
|
from fabricatio.config import configs
|
13
|
+
from fabricatio.models.extra.problem import Improvement
|
13
14
|
from fabricatio.models.generic import CensoredAble, Display, ProposedAble, ProposedUpdateAble, WithBriefing
|
14
15
|
from fabricatio.models.kwargs_types import CensoredCorrectKwargs, CorrectKwargs, ReviewKwargs
|
15
16
|
from fabricatio.models.task import Task
|
@@ -31,7 +32,7 @@ class Correct(Review):
|
|
31
32
|
obj: M,
|
32
33
|
reference: str = "",
|
33
34
|
supervisor_check: bool = True,
|
34
|
-
**kwargs: Unpack[ReviewKwargs[
|
35
|
+
**kwargs: Unpack[ReviewKwargs[Improvement]],
|
35
36
|
) -> Optional[M]:
|
36
37
|
"""Review and correct an object based on defined criteria and templates.
|
37
38
|
|
@@ -71,7 +72,7 @@ class Correct(Review):
|
|
71
72
|
)
|
72
73
|
|
73
74
|
async def correct_string(
|
74
|
-
self, input_text: str, supervisor_check: bool = True, **kwargs: Unpack[ReviewKwargs[
|
75
|
+
self, input_text: str, supervisor_check: bool = True, **kwargs: Unpack[ReviewKwargs[Improvement]]
|
75
76
|
) -> Optional[str]:
|
76
77
|
"""Review and correct a string based on defined criteria and templates.
|
77
78
|
|
@@ -100,7 +101,7 @@ class Correct(Review):
|
|
100
101
|
)
|
101
102
|
|
102
103
|
async def correct_task[T](
|
103
|
-
self, task: Task[T], **kwargs: Unpack[CorrectKwargs[
|
104
|
+
self, task: Task[T], **kwargs: Unpack[CorrectKwargs[Improvement]]
|
104
105
|
) -> Optional[Task[T]]:
|
105
106
|
"""Review and correct a task object based on defined criteria.
|
106
107
|
|
@@ -117,7 +118,7 @@ class Correct(Review):
|
|
117
118
|
return await self.correct_obj(task, **kwargs)
|
118
119
|
|
119
120
|
async def censor_obj[M: CensoredAble](
|
120
|
-
self, obj: M, **kwargs: Unpack[CensoredCorrectKwargs[
|
121
|
+
self, obj: M, **kwargs: Unpack[CensoredCorrectKwargs[Improvement]]
|
121
122
|
) -> M:
|
122
123
|
"""Censor and correct an object based on defined criteria and templates.
|
123
124
|
|
@@ -147,7 +148,7 @@ class Correct(Review):
|
|
147
148
|
return modified_obj or last_modified_obj
|
148
149
|
|
149
150
|
async def correct_obj_inplace[M: ProposedUpdateAble](
|
150
|
-
self, obj: M, **kwargs: Unpack[CorrectKwargs[
|
151
|
+
self, obj: M, **kwargs: Unpack[CorrectKwargs[Improvement]]
|
151
152
|
) -> Optional[M]:
|
152
153
|
"""Correct an object in place based on defined criteria and templates.
|
153
154
|
|
@@ -10,28 +10,43 @@ from fabricatio.models.usages import LLMUsage
|
|
10
10
|
class Propose(LLMUsage):
|
11
11
|
"""A class that proposes an Obj based on a prompt."""
|
12
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
|
+
|
13
21
|
@overload
|
14
22
|
async def propose[M: ProposedAble](
|
15
23
|
self,
|
16
24
|
cls: Type[M],
|
17
25
|
prompt: List[str],
|
18
26
|
**kwargs: Unpack[ValidateKwargs[M]],
|
19
|
-
) ->
|
27
|
+
) -> List[M]: ...
|
20
28
|
|
21
29
|
@overload
|
22
30
|
async def propose[M: ProposedAble](
|
23
31
|
self,
|
24
32
|
cls: Type[M],
|
25
33
|
prompt: str,
|
26
|
-
**kwargs: Unpack[ValidateKwargs[
|
34
|
+
**kwargs: Unpack[ValidateKwargs[None]],
|
27
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: ...
|
28
43
|
|
29
44
|
async def propose[M: ProposedAble](
|
30
45
|
self,
|
31
46
|
cls: Type[M],
|
32
47
|
prompt: List[str] | str,
|
33
|
-
**kwargs: Unpack[ValidateKwargs[M]],
|
34
|
-
) -> Optional[List[M] | M]:
|
48
|
+
**kwargs: Unpack[ValidateKwargs[Optional[M]]],
|
49
|
+
) -> Optional[M] | List[Optional[M]] | M | List[M]:
|
35
50
|
"""Asynchronously proposes a task based on a given prompt and parameters.
|
36
51
|
|
37
52
|
Parameters:
|
@@ -47,3 +62,4 @@ class Propose(LLMUsage):
|
|
47
62
|
validator=cls.instantiate_from_string,
|
48
63
|
**kwargs,
|
49
64
|
)
|
65
|
+
|
fabricatio/capabilities/rag.py
CHANGED
@@ -22,7 +22,8 @@ from fabricatio.models.kwargs_types import (
|
|
22
22
|
RetrievalKwargs,
|
23
23
|
)
|
24
24
|
from fabricatio.models.usages import EmbeddingUsage
|
25
|
-
from fabricatio.models.utils import MilvusData
|
25
|
+
from fabricatio.models.utils import MilvusData
|
26
|
+
from fabricatio.utils import ok
|
26
27
|
from more_itertools.recipes import flatten, unique
|
27
28
|
from pydantic import Field, PrivateAttr
|
28
29
|
|
@@ -376,7 +377,7 @@ class RAG(EmbeddingUsage):
|
|
376
377
|
Returns:
|
377
378
|
List[str]: A list of refined questions.
|
378
379
|
"""
|
379
|
-
return await self.
|
380
|
+
return await self.alist_str(
|
380
381
|
TEMPLATE_MANAGER.render_template(
|
381
382
|
configs.templates.refined_query_template,
|
382
383
|
{"question": [question] if isinstance(question, str) else question},
|
@@ -7,16 +7,15 @@ from typing import Dict, List, Optional, Set, Tuple, Union, Unpack, overload
|
|
7
7
|
from fabricatio._rust_instances import TEMPLATE_MANAGER
|
8
8
|
from fabricatio.config import configs
|
9
9
|
from fabricatio.journal import logger
|
10
|
-
from fabricatio.models.generic import WithBriefing
|
11
10
|
from fabricatio.models.kwargs_types import ValidateKwargs
|
12
11
|
from fabricatio.models.usages import LLMUsage
|
13
|
-
from fabricatio.models.utils import override_kwargs
|
14
12
|
from fabricatio.parser import JsonCapture
|
13
|
+
from fabricatio.utils import override_kwargs
|
15
14
|
from more_itertools import flatten, windowed
|
16
15
|
from pydantic import NonNegativeInt, PositiveInt
|
17
16
|
|
18
17
|
|
19
|
-
class Rating(
|
18
|
+
class Rating(LLMUsage):
|
20
19
|
"""A class that provides functionality to rate tasks based on a rating manual and score range.
|
21
20
|
|
22
21
|
References:
|
@@ -149,9 +148,7 @@ class Rating(WithBriefing, LLMUsage):
|
|
149
148
|
return json_data
|
150
149
|
return None
|
151
150
|
|
152
|
-
criteria = criteria or await self.draft_rating_criteria(
|
153
|
-
topic, **self.prepend_sys_msg(override_kwargs(dict(kwargs), default=None))
|
154
|
-
)
|
151
|
+
criteria = criteria or await self.draft_rating_criteria(topic, **override_kwargs(dict(kwargs), default=None))
|
155
152
|
|
156
153
|
if criteria is None:
|
157
154
|
logger.error(f"Failed to draft rating criteria for topic {topic}")
|
@@ -168,7 +165,7 @@ class Rating(WithBriefing, LLMUsage):
|
|
168
165
|
)
|
169
166
|
),
|
170
167
|
validator=_validator,
|
171
|
-
**
|
168
|
+
**kwargs,
|
172
169
|
)
|
173
170
|
|
174
171
|
async def draft_rating_criteria(
|
@@ -200,7 +197,7 @@ class Rating(WithBriefing, LLMUsage):
|
|
200
197
|
validator=lambda resp: set(out)
|
201
198
|
if (out := JsonCapture.validate_with(resp, list, str, criteria_count)) is not None
|
202
199
|
else out,
|
203
|
-
**
|
200
|
+
**kwargs,
|
204
201
|
)
|
205
202
|
|
206
203
|
async def draft_rating_criteria_from_examples(
|
@@ -253,7 +250,7 @@ class Rating(WithBriefing, LLMUsage):
|
|
253
250
|
validator=lambda resp: JsonCapture.validate_with(
|
254
251
|
resp, target_type=list, elements_type=str, length=reasons_count
|
255
252
|
),
|
256
|
-
**
|
253
|
+
**kwargs,
|
257
254
|
)
|
258
255
|
)
|
259
256
|
# extract certain mount of criteria from reasons according to their importance and frequency
|
@@ -310,7 +307,7 @@ class Rating(WithBriefing, LLMUsage):
|
|
310
307
|
for pair in windows
|
311
308
|
],
|
312
309
|
validator=lambda resp: JsonCapture.validate_with(resp, target_type=float),
|
313
|
-
**
|
310
|
+
**kwargs,
|
314
311
|
)
|
315
312
|
weights = [1]
|
316
313
|
for rw in relative_weights:
|