fabricatio 0.2.6.dev1__cp312-cp312-win_amd64.whl → 0.2.7.dev2__cp312-cp312-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fabricatio/__init__.py CHANGED
@@ -2,59 +2,42 @@
2
2
 
3
3
  from importlib.util import find_spec
4
4
 
5
+ from fabricatio import actions, toolboxes, workflows
5
6
  from fabricatio._rust import BibManager
6
7
  from fabricatio._rust_instances import TEMPLATE_MANAGER
7
- from fabricatio.actions.article import ExtractArticleEssence, GenerateArticleProposal, GenerateOutline
8
- from fabricatio.actions.output import DumpFinalizedOutput
9
8
  from fabricatio.core import env
10
- from fabricatio.fs import MAGIKA, safe_json_read, safe_text_read
11
9
  from fabricatio.journal import logger
10
+ from fabricatio.models import extra
12
11
  from fabricatio.models.action import Action, WorkFlow
13
12
  from fabricatio.models.events import Event
14
- from fabricatio.models.extra import ArticleEssence
15
13
  from fabricatio.models.role import Role
16
14
  from fabricatio.models.task import Task
17
15
  from fabricatio.models.tool import ToolBox
18
- from fabricatio.models.utils import Message, Messages
19
16
  from fabricatio.parser import Capture, GenericCapture, JsonCapture, PythonCapture
20
- from fabricatio.toolboxes import arithmetic_toolbox, basic_toolboxes, fs_toolbox
21
- from fabricatio.workflows.articles import WriteOutlineWorkFlow
22
17
 
23
18
  __all__ = [
24
- "MAGIKA",
25
19
  "TEMPLATE_MANAGER",
26
20
  "Action",
27
- "ArticleEssence",
28
21
  "BibManager",
29
22
  "Capture",
30
- "DumpFinalizedOutput",
31
23
  "Event",
32
- "ExtractArticleEssence",
33
- "GenerateArticleProposal",
34
- "GenerateOutline",
35
24
  "GenericCapture",
36
25
  "JsonCapture",
37
- "Message",
38
- "Messages",
39
26
  "PythonCapture",
40
27
  "Role",
41
28
  "Task",
42
29
  "ToolBox",
43
30
  "WorkFlow",
44
- "WriteOutlineWorkFlow",
45
- "arithmetic_toolbox",
46
- "basic_toolboxes",
31
+ "actions",
47
32
  "env",
48
- "fs_toolbox",
33
+ "extra",
49
34
  "logger",
50
- "safe_json_read",
51
- "safe_text_read",
35
+ "toolboxes",
36
+ "workflows",
52
37
  ]
53
38
 
54
39
 
55
40
  if find_spec("pymilvus"):
56
- from fabricatio.actions.rag import InjectToDB
57
41
  from fabricatio.capabilities.rag import RAG
58
- from fabricatio.workflows.rag import StoreArticle
59
42
 
60
- __all__ += ["RAG", "InjectToDB", "StoreArticle"]
43
+ __all__ += ["RAG"]
Binary file
fabricatio/_rust.pyi CHANGED
@@ -9,6 +9,7 @@ class TemplateManager:
9
9
 
10
10
  See: https://crates.io/crates/handlebars
11
11
  """
12
+
12
13
  def __init__(
13
14
  self, template_dirs: List[Path], suffix: Optional[str] = None, active_loading: Optional[bool] = None
14
15
  ) -> None:
@@ -54,6 +55,17 @@ class TemplateManager:
54
55
  RuntimeError: If template rendering fails
55
56
  """
56
57
 
58
+ def render_template_raw(self, template: str, data: Dict[str, Any]) -> str:
59
+ """Render a template with context data.
60
+
61
+ Args:
62
+ template: The template string
63
+ data: Context dictionary to provide variables to the template
64
+
65
+ Returns:
66
+ Rendered template content as string
67
+ """
68
+
57
69
  def blake3_hash(content: bytes) -> str:
58
70
  """Calculate the BLAKE3 cryptographic hash of data.
59
71
 
@@ -100,3 +112,13 @@ class BibManager:
100
112
  Uses nucleo_matcher for high-quality fuzzy text searching
101
113
  See: https://crates.io/crates/nucleo-matcher
102
114
  """
115
+
116
+ def list_titles(self, is_verbatim: Optional[bool] = False) -> List[str]:
117
+ """List all titles in the bibliography.
118
+
119
+ Args:
120
+ is_verbatim: Whether to return verbatim titles (without formatting)
121
+
122
+ Returns:
123
+ List of all titles in the bibliography
124
+ """
@@ -1,14 +1,14 @@
1
1
  """Actions for transmitting tasks to targets."""
2
2
 
3
- from os import PathLike
4
3
  from pathlib import Path
5
- from typing import Callable, List, Optional
4
+ from typing import Any, Callable, List, Optional
6
5
 
7
6
  from fabricatio.fs import safe_text_read
8
7
  from fabricatio.journal import logger
9
8
  from fabricatio.models.action import Action
10
- from fabricatio.models.extra import ArticleEssence, ArticleOutline, ArticleProposal
9
+ from fabricatio.models.extra import Article, ArticleEssence, ArticleOutline, ArticleProposal
11
10
  from fabricatio.models.task import Task
11
+ from fabricatio.models.utils import ok
12
12
 
13
13
 
14
14
  class ExtractArticleEssence(Action):
@@ -22,10 +22,10 @@ class ExtractArticleEssence(Action):
22
22
  output_key: str = "article_essence"
23
23
  """The key of the output data."""
24
24
 
25
- async def _execute[P: PathLike | str](
25
+ async def _execute(
26
26
  self,
27
27
  task_input: Task,
28
- reader: Callable[[P], str] = lambda p: Path(p).read_text(encoding="utf-8"),
28
+ reader: Callable[[str], str] = lambda p: Path(p).read_text(encoding="utf-8"),
29
29
  **_,
30
30
  ) -> Optional[List[ArticleEssence]]:
31
31
  if not task_input.dependencies:
@@ -49,24 +49,39 @@ class GenerateArticleProposal(Action):
49
49
 
50
50
  async def _execute(
51
51
  self,
52
- task_input: Task,
52
+ task_input: Optional[Task] = None,
53
+ article_briefing: Optional[str] = None,
54
+ article_briefing_path: Optional[str] = None,
53
55
  **_,
54
56
  ) -> Optional[ArticleProposal]:
55
- input_path = await self.awhich_pathstr(
56
- f"{task_input.briefing}\nExtract the path of file, which contains the article briefing that I need to read."
57
- )
58
-
59
- return await self.propose(
60
- ArticleProposal,
61
- safe_text_read(input_path),
62
- system_message=f"# your personal briefing: \n{self.briefing}",
63
- )
57
+ if article_briefing is None and article_briefing_path is None and task_input is None:
58
+ logger.error("Task not approved, since all inputs are None.")
59
+ return None
60
+
61
+ return (
62
+ await self.propose(
63
+ ArticleProposal,
64
+ briefing := (
65
+ article_briefing
66
+ or safe_text_read(
67
+ ok(
68
+ article_briefing_path
69
+ or await self.awhich_pathstr(
70
+ f"{task_input.briefing}\nExtract the path of file which contains the article briefing."
71
+ ),
72
+ "Could not find the path of file to read.",
73
+ )
74
+ )
75
+ ),
76
+ **self.prepend_sys_msg(),
77
+ )
78
+ ).update_ref(briefing)
64
79
 
65
80
 
66
81
  class GenerateOutline(Action):
67
82
  """Generate the article based on the outline."""
68
83
 
69
- output_key: str = "article"
84
+ output_key: str = "article_outline"
70
85
  """The key of the output data."""
71
86
 
72
87
  async def _execute(
@@ -74,8 +89,121 @@ class GenerateOutline(Action):
74
89
  article_proposal: ArticleProposal,
75
90
  **_,
76
91
  ) -> Optional[ArticleOutline]:
77
- return await self.propose(
92
+ out = await self.propose(
78
93
  ArticleOutline,
79
- article_proposal.display(),
80
- system_message=f"# your personal briefing: \n{self.briefing}",
94
+ article_proposal.as_prompt(),
95
+ **self.prepend_sys_msg(),
81
96
  )
97
+
98
+ manual = await self.draft_rating_manual(
99
+ topic=(
100
+ topic
101
+ := "Fix the internal referring error, make sure there is no more `ArticleRef` pointing to a non-existing article component."
102
+ ),
103
+ )
104
+ while err := out.resolve_ref_error():
105
+ logger.warning(f"Found error in the outline: \n{err}")
106
+ out = await self.correct_obj(
107
+ out,
108
+ reference=f"# Referring Error\n{err}",
109
+ topic=topic,
110
+ rating_manual=manual,
111
+ supervisor_check=False,
112
+ )
113
+ return out.update_ref(article_proposal)
114
+
115
+
116
+ class CorrectProposal(Action):
117
+ """Correct the proposal of the article."""
118
+
119
+ output_key: str = "corrected_proposal"
120
+
121
+ async def _execute(self, article_proposal: ArticleProposal, **_) -> Any:
122
+ return (await self.censor_obj(article_proposal, reference=article_proposal.referenced)).update_ref(
123
+ article_proposal
124
+ )
125
+
126
+
127
+ class CorrectOutline(Action):
128
+ """Correct the outline of the article."""
129
+
130
+ output_key: str = "corrected_outline"
131
+ """The key of the output data."""
132
+
133
+ async def _execute(
134
+ self,
135
+ article_outline: ArticleOutline,
136
+ **_,
137
+ ) -> ArticleOutline:
138
+ return (await self.censor_obj(article_outline, reference=article_outline.referenced.as_prompt())).update_ref(
139
+ article_outline
140
+ )
141
+
142
+
143
+ class GenerateArticle(Action):
144
+ """Generate the article based on the outline."""
145
+
146
+ output_key: str = "article"
147
+ """The key of the output data."""
148
+
149
+ async def _execute(
150
+ self,
151
+ article_outline: ArticleOutline,
152
+ **_,
153
+ ) -> Optional[Article]:
154
+ article: Article = Article.from_outline(article_outline).update_ref(article_outline)
155
+
156
+ writing_manual = await self.draft_rating_manual(
157
+ topic=(
158
+ topic_1
159
+ := "improve the content of the subsection to fit the outline. SHALL never add or remove any section or subsection, you can only add or delete paragraphs within the subsection."
160
+ ),
161
+ )
162
+ err_resolve_manual = await self.draft_rating_manual(
163
+ topic=(topic_2 := "this article component has violated the constrain, please correct it.")
164
+ )
165
+ for c, deps in article.iter_dfs_with_deps(chapter=False):
166
+ logger.info(f"Updating the article component: \n{c.display()}")
167
+
168
+ out = ok(
169
+ await self.correct_obj(
170
+ c,
171
+ reference=(
172
+ ref := f"{article_outline.referenced.as_prompt()}\n" + "\n".join(d.display() for d in deps)
173
+ ),
174
+ topic=topic_1,
175
+ rating_manual=writing_manual,
176
+ supervisor_check=False,
177
+ ),
178
+ "Could not correct the article component.",
179
+ )
180
+ while err := c.resolve_update_error(out):
181
+ logger.warning(f"Found error in the article component: \n{err}")
182
+ out = ok(
183
+ await self.correct_obj(
184
+ out,
185
+ reference=f"{ref}\n\n# Violated Error\n{err}",
186
+ topic=topic_2,
187
+ rating_manual=err_resolve_manual,
188
+ supervisor_check=False,
189
+ ),
190
+ "Could not correct the article component.",
191
+ )
192
+
193
+ c.update_from(out)
194
+ return article
195
+
196
+
197
+ class CorrectArticle(Action):
198
+ """Correct the article based on the outline."""
199
+
200
+ output_key: str = "corrected_article"
201
+ """The key of the output data."""
202
+
203
+ async def _execute(
204
+ self,
205
+ article: Article,
206
+ article_outline: ArticleOutline,
207
+ **_,
208
+ ) -> Article:
209
+ return await self.censor_obj(article, reference=article_outline.referenced.as_prompt())
@@ -1,8 +1,12 @@
1
1
  """Dump the finalized output to a file."""
2
2
 
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
3
6
  from fabricatio.models.action import Action
4
7
  from fabricatio.models.generic import FinalizedDumpAble
5
8
  from fabricatio.models.task import Task
9
+ from fabricatio.models.utils import ok
6
10
 
7
11
 
8
12
  class DumpFinalizedOutput(Action):
@@ -10,10 +14,21 @@ class DumpFinalizedOutput(Action):
10
14
 
11
15
  output_key: str = "dump_path"
12
16
 
13
- async def _execute(self, task_input: Task, to_dump: FinalizedDumpAble, **_) -> str:
14
- dump_path = await self.awhich_pathstr(
15
- f"{task_input.briefing}\n\nExtract a single path of the file, to which I will dump the data."
17
+ async def _execute(
18
+ self,
19
+ to_dump: FinalizedDumpAble,
20
+ task_input: Optional[Task] = None,
21
+ dump_path: Optional[str | Path] = None,
22
+ **_,
23
+ ) -> str:
24
+ dump_path = Path(
25
+ dump_path
26
+ or ok(
27
+ await self.awhich_pathstr(
28
+ f"{ok(task_input, 'Neither `task_input` and `dump_path` is provided.').briefing}\n\nExtract a single path of the file, to which I will dump the data."
29
+ ),
30
+ "Could not find the path of file to dump the data.",
31
+ )
16
32
  )
17
-
18
- to_dump.finalized_dump_to(dump_path)
19
- return dump_path
33
+ ok(to_dump, "Could not dump the data since the path is not specified.").finalized_dump_to(dump_path)
34
+ return dump_path.as_posix()
fabricatio/actions/rag.py CHANGED
@@ -3,8 +3,11 @@
3
3
  from typing import List, Optional
4
4
 
5
5
  from fabricatio.capabilities.rag import RAG
6
+ from fabricatio.journal import logger
6
7
  from fabricatio.models.action import Action
7
8
  from fabricatio.models.generic import PrepareVectorization
9
+ from fabricatio.models.task import Task
10
+ from questionary import text
8
11
 
9
12
 
10
13
  class InjectToDB(Action, RAG):
@@ -13,13 +16,58 @@ class InjectToDB(Action, RAG):
13
16
  output_key: str = "collection_name"
14
17
 
15
18
  async def _execute[T: PrepareVectorization](
16
- self, to_inject: T | List[T], collection_name: Optional[str] = "my_collection", **_
19
+ self, to_inject: Optional[T] | List[Optional[T]], collection_name: str = "my_collection",override_inject:bool=False, **_
17
20
  ) -> Optional[str]:
18
21
  if not isinstance(to_inject, list):
19
22
  to_inject = [to_inject]
20
-
23
+ logger.info(f"Injecting {len(to_inject)} items into the collection '{collection_name}'")
24
+ if override_inject:
25
+ self.check_client().client.drop_collection(collection_name)
21
26
  await self.view(collection_name, create=True).consume_string(
22
- [t.prepare_vectorization(self.embedding_max_sequence_length) for t in to_inject],
27
+ [
28
+ t.prepare_vectorization(self.embedding_max_sequence_length)
29
+ for t in to_inject
30
+ if isinstance(t, PrepareVectorization)
31
+ ],
23
32
  )
24
33
 
25
34
  return collection_name
35
+
36
+
37
+ class RAGTalk(Action, RAG):
38
+ """RAG-enabled conversational action that processes user questions based on a given task.
39
+
40
+ This action establishes an interactive conversation loop where it retrieves context-relevant
41
+ information to answer user queries according to the assigned task briefing.
42
+
43
+ Notes:
44
+ task_input: Task briefing that guides how to respond to user questions
45
+ collection_name: Name of the vector collection to use for retrieval (default: "my_collection")
46
+
47
+ Returns:
48
+ Number of conversation turns completed before termination
49
+ """
50
+
51
+ output_key: str = "task_output"
52
+
53
+ async def _execute(self, task_input: Task[str], **kwargs) -> int:
54
+ collection_name = kwargs.get("collection_name", "my_collection")
55
+ counter = 0
56
+
57
+ self.view(collection_name, create=True)
58
+
59
+ try:
60
+ while True:
61
+ user_say = await text("User: ").ask_async()
62
+ if user_say is None:
63
+ break
64
+ gpt_say = await self.aask_retrieved(
65
+ user_say,
66
+ user_say,
67
+ extra_system_message=f"You have to answer to user obeying task assigned to you:\n{task_input.briefing}",
68
+ )
69
+ print(f"GPT: {gpt_say}") # noqa: T201
70
+ counter += 1
71
+ except KeyboardInterrupt:
72
+ logger.info(f"executed talk action {counter} times")
73
+ return counter
@@ -5,14 +5,16 @@ to provide mechanisms for reviewing, validating, and correcting various objects
5
5
  based on predefined criteria and templates.
6
6
  """
7
7
 
8
- from typing import Optional, Unpack
8
+ from typing import Optional, Unpack, cast
9
9
 
10
10
  from fabricatio._rust_instances import TEMPLATE_MANAGER
11
11
  from fabricatio.capabilities.review import Review, ReviewResult
12
12
  from fabricatio.config import configs
13
- from fabricatio.models.generic import Display, ProposedAble, WithBriefing
14
- from fabricatio.models.kwargs_types import ReviewKwargs
13
+ from fabricatio.models.generic import CensoredAble, Display, ProposedAble, WithBriefing
14
+ from fabricatio.models.kwargs_types import CensoredCorrectKwargs, CorrectKwargs, ReviewKwargs
15
15
  from fabricatio.models.task import Task
16
+ from questionary import confirm, text
17
+ from rich import print as rprint
16
18
 
17
19
 
18
20
  class Correct(Review):
@@ -25,7 +27,11 @@ class Correct(Review):
25
27
  """
26
28
 
27
29
  async def correct_obj[M: ProposedAble](
28
- self, obj: M, **kwargs: Unpack[ReviewKwargs[ReviewResult[str]]]
30
+ self,
31
+ obj: M,
32
+ reference: str = "",
33
+ supervisor_check: bool = True,
34
+ **kwargs: Unpack[ReviewKwargs[ReviewResult[str]]],
29
35
  ) -> Optional[M]:
30
36
  """Review and correct an object based on defined criteria and templates.
31
37
 
@@ -34,6 +40,8 @@ class Correct(Review):
34
40
 
35
41
  Args:
36
42
  obj (M): The object to be reviewed and corrected. Must implement ProposedAble.
43
+ reference (str): A reference or contextual information for the object.
44
+ supervisor_check (bool, optional): Whether to perform a supervisor check on the review results. Defaults to True.
37
45
  **kwargs: Review configuration parameters including criteria and review options.
38
46
 
39
47
  Returns:
@@ -44,23 +52,27 @@ class Correct(Review):
44
52
  """
45
53
  if not isinstance(obj, (Display, WithBriefing)):
46
54
  raise TypeError(f"Expected Display or WithBriefing, got {type(obj)}")
55
+
47
56
  review_res = await self.review_obj(obj, **kwargs)
48
- await review_res.supervisor_check()
57
+ if supervisor_check:
58
+ await review_res.supervisor_check()
49
59
  if "default" in kwargs:
50
- kwargs["default"] = None
60
+ cast("ReviewKwargs[None]", kwargs)["default"] = None
51
61
  return await self.propose(
52
62
  obj.__class__,
53
63
  TEMPLATE_MANAGER.render_template(
54
64
  configs.templates.correct_template,
55
65
  {
56
- "content": obj.display() if isinstance(obj, Display) else obj.briefing,
66
+ "content": f"{(reference + '\n\nAbove is referencing material') if reference else ''}{obj.display() if isinstance(obj, Display) else obj.briefing}",
57
67
  "review": review_res.display(),
58
68
  },
59
69
  ),
60
70
  **kwargs,
61
71
  )
62
72
 
63
- async def correct_string(self, input_text: str, **kwargs: Unpack[ReviewKwargs[ReviewResult[str]]]) -> Optional[str]:
73
+ async def correct_string(
74
+ self, input_text: str, supervisor_check: bool = True, **kwargs: Unpack[ReviewKwargs[ReviewResult[str]]]
75
+ ) -> Optional[str]:
64
76
  """Review and correct a string based on defined criteria and templates.
65
77
 
66
78
  This method applies the review process to the input text and generates
@@ -68,16 +80,18 @@ class Correct(Review):
68
80
 
69
81
  Args:
70
82
  input_text (str): The text content to be reviewed and corrected.
83
+ supervisor_check (bool, optional): Whether to perform a supervisor check on the review results. Defaults to True.
71
84
  **kwargs: Review configuration parameters including criteria and review options.
72
85
 
73
86
  Returns:
74
87
  Optional[str]: The corrected text content, or None if correction fails.
75
88
  """
76
89
  review_res = await self.review_string(input_text, **kwargs)
77
- await review_res.supervisor_check()
90
+ if supervisor_check:
91
+ await review_res.supervisor_check()
78
92
 
79
93
  if "default" in kwargs:
80
- kwargs["default"] = None
94
+ cast("ReviewKwargs[None]", kwargs)["default"] = None
81
95
  return await self.ageneric_string(
82
96
  TEMPLATE_MANAGER.render_template(
83
97
  configs.templates.correct_template, {"content": input_text, "review": review_res.display()}
@@ -86,7 +100,7 @@ class Correct(Review):
86
100
  )
87
101
 
88
102
  async def correct_task[T](
89
- self, task: Task[T], **kwargs: Unpack[ReviewKwargs[ReviewResult[str]]]
103
+ self, task: Task[T], **kwargs: Unpack[CorrectKwargs[ReviewResult[str]]]
90
104
  ) -> Optional[Task[T]]:
91
105
  """Review and correct a task object based on defined criteria.
92
106
 
@@ -101,3 +115,31 @@ class Correct(Review):
101
115
  Optional[Task[T]]: The corrected task, or None if correction fails.
102
116
  """
103
117
  return await self.correct_obj(task, **kwargs)
118
+
119
+ async def censor_obj[M: CensoredAble](
120
+ self, obj: M, **kwargs: Unpack[CensoredCorrectKwargs[ReviewResult[str]]]
121
+ ) -> M:
122
+ """Censor and correct an object based on defined criteria and templates.
123
+
124
+ Args:
125
+ obj (M): The object to be reviewed and corrected.
126
+ **kwargs (Unpack[CensoredCorrectKwargs]): Additional keyword
127
+
128
+ Returns:
129
+ M: The censored and corrected object.
130
+ """
131
+ last_modified_obj = obj
132
+ modified_obj = None
133
+ rprint(obj.finalized_dump())
134
+ while await confirm("Begin to correct obj above with human censorship?").ask_async():
135
+ while (topic := await text("What is the topic of the obj reviewing?").ask_async()) is not None and topic:
136
+ ...
137
+ if (modified_obj := await self.correct_obj(
138
+ last_modified_obj,
139
+ topic=topic,
140
+ **kwargs,
141
+ )) is None:
142
+ break
143
+ last_modified_obj = modified_obj
144
+ rprint(last_modified_obj.finalized_dump())
145
+ return modified_obj or last_modified_obj