fabricatio 0.2.6.dev8__cp312-cp312-manylinux_2_34_x86_64.whl → 0.2.7.dev1__cp312-cp312-manylinux_2_34_x86_64.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.pyi CHANGED
@@ -11,7 +11,7 @@ class TemplateManager:
11
11
  """
12
12
 
13
13
  def __init__(
14
- self, template_dirs: List[Path], suffix: Optional[str] = None, active_loading: Optional[bool] = None
14
+ self, template_dirs: List[Path], suffix: Optional[str] = None, active_loading: Optional[bool] = None
15
15
  ) -> None:
16
16
  """Initialize the template manager.
17
17
 
@@ -55,6 +55,16 @@ class TemplateManager:
55
55
  RuntimeError: If template rendering fails
56
56
  """
57
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
+ """
58
68
 
59
69
  def blake3_hash(content: bytes) -> str:
60
70
  """Calculate the BLAKE3 cryptographic hash of data.
@@ -66,7 +76,6 @@ def blake3_hash(content: bytes) -> str:
66
76
  Hex-encoded BLAKE3 hash string
67
77
  """
68
78
 
69
-
70
79
  class BibManager:
71
80
  """BibTeX bibliography manager for parsing and querying citation data."""
72
81
 
@@ -1,16 +1,14 @@
1
1
  """Actions for transmitting tasks to targets."""
2
2
 
3
- from os import PathLike
4
3
  from pathlib import Path
5
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
12
- from questionary import confirm, text
13
- from rich import print as rprint
11
+ from fabricatio.models.utils import ok
14
12
 
15
13
 
16
14
  class ExtractArticleEssence(Action):
@@ -24,10 +22,10 @@ class ExtractArticleEssence(Action):
24
22
  output_key: str = "article_essence"
25
23
  """The key of the output data."""
26
24
 
27
- async def _execute[P: PathLike | str](
25
+ async def _execute(
28
26
  self,
29
27
  task_input: Task,
30
- 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"),
31
29
  **_,
32
30
  ) -> Optional[List[ArticleEssence]]:
33
31
  if not task_input.dependencies:
@@ -51,18 +49,29 @@ class GenerateArticleProposal(Action):
51
49
 
52
50
  async def _execute(
53
51
  self,
54
- task_input: Task,
52
+ task_input: Optional[Task] = None,
53
+ article_briefing: Optional[str] = None,
54
+ article_briefing_path: Optional[str] = None,
55
55
  **_,
56
56
  ) -> Optional[ArticleProposal]:
57
- input_path = await self.awhich_pathstr(
58
- f"{task_input.briefing}\nExtract the path of file, which contains the article briefing that I need to read."
59
- )
57
+ if article_briefing is None and article_briefing_path is None and task_input is None:
58
+ logger.info("Task not approved, since ")
59
+ return None
60
+ if article_briefing_path is None and task_input:
61
+ article_briefing_path = await self.awhich_pathstr(
62
+ f"{task_input.briefing}\nExtract the path of file which contains the article briefing."
63
+ )
60
64
 
61
- return await self.propose(
62
- ArticleProposal,
63
- safe_text_read(input_path),
64
- system_message=f"# your personal briefing: \n{self.briefing}",
65
- )
65
+ return (
66
+ await self.propose(
67
+ ArticleProposal,
68
+ briefing := (
69
+ article_briefing
70
+ or safe_text_read(ok(article_briefing_path, "Could not find the path of file to read."))
71
+ ),
72
+ **self.prepend_sys_msg(),
73
+ )
74
+ ).update_ref(briefing)
66
75
 
67
76
 
68
77
  class GenerateOutline(Action):
@@ -76,11 +85,13 @@ class GenerateOutline(Action):
76
85
  article_proposal: ArticleProposal,
77
86
  **_,
78
87
  ) -> Optional[ArticleOutline]:
79
- return await self.propose(
80
- ArticleOutline,
81
- article_proposal.display(),
82
- system_message=f"# your personal briefing: \n{self.briefing}",
83
- )
88
+ return (
89
+ await self.propose(
90
+ ArticleOutline,
91
+ article_proposal.as_prompt(),
92
+ **self.prepend_sys_msg(),
93
+ )
94
+ ).update_ref(article_proposal)
84
95
 
85
96
 
86
97
  class CorrectProposal(Action):
@@ -88,23 +99,11 @@ class CorrectProposal(Action):
88
99
 
89
100
  output_key: str = "corrected_proposal"
90
101
 
91
- async def _execute(self, task_input: Task, article_proposal: ArticleProposal, **_) -> Any:
92
- input_path = await self.awhich_pathstr(
93
- f"{task_input.briefing}\nExtract the path of file, which contains the article briefing that I need to read."
102
+ async def _execute(self, article_proposal: ArticleProposal, **_) -> Any:
103
+ return (await self.censor_obj(article_proposal, reference=article_proposal.referenced)).update_ref(
104
+ article_proposal
94
105
  )
95
106
 
96
- ret = None
97
- while await confirm("Do you want to correct the Proposal?").ask_async():
98
- rprint(article_proposal.display())
99
- while not (topic := await text("What is the topic of the proposal reviewing?").ask_async()):
100
- ...
101
- ret = await self.correct_obj(
102
- article_proposal,
103
- safe_text_read(input_path),
104
- topic=topic,
105
- )
106
- return ret or article_proposal
107
-
108
107
 
109
108
  class CorrectOutline(Action):
110
109
  """Correct the outline of the article."""
@@ -115,14 +114,45 @@ class CorrectOutline(Action):
115
114
  async def _execute(
116
115
  self,
117
116
  article_outline: ArticleOutline,
118
- article_proposal: ArticleProposal,
117
+ **_,
118
+ ) -> ArticleOutline:
119
+ return (await self.censor_obj(article_outline, reference=article_outline.referenced.as_prompt())).update_ref(
120
+ article_outline
121
+ )
119
122
 
123
+
124
+ class GenerateArticle(Action):
125
+ """Generate the article based on the outline."""
126
+
127
+ output_key: str = "article"
128
+ """The key of the output data."""
129
+
130
+ async def _execute(
131
+ self,
132
+ article_outline: ArticleOutline,
133
+ **_,
134
+ ) -> Optional[Article]:
135
+ article: Article = Article.from_outline(article_outline).update_ref(article_outline)
136
+
137
+ for c, deps in article.iter_dfs_with_deps():
138
+ out = await self.correct_obj(
139
+ c, reference=f"{article_outline.referenced.as_prompt()}\n" + "\n".join(d.display() for d in deps)
140
+ )
141
+
142
+ c.update_from(out)
143
+ return article
144
+
145
+
146
+ class CorrectArticle(Action):
147
+ """Correct the article based on the outline."""
148
+
149
+ output_key: str = "corrected_article"
150
+ """The key of the output data."""
151
+
152
+ async def _execute(
153
+ self,
154
+ article: Article,
155
+ article_outline: ArticleOutline,
120
156
  **_,
121
- ) -> Optional[str]:
122
- ret = None
123
- while await confirm("Do you want to correct the outline?").ask_async():
124
- rprint(article_outline.finalized_dump())
125
- while not (topic := await text("What is the topic of the outline reviewing?").ask_async()):
126
- ...
127
- ret = await self.correct_obj(article_outline, article_proposal.display(), topic=topic)
128
- return ret or article_outline
157
+ ) -> Article:
158
+ 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
@@ -6,6 +6,8 @@ from fabricatio.capabilities.rag import RAG
6
6
  from fabricatio.journal import logger
7
7
  from fabricatio.models.action import Action
8
8
  from fabricatio.models.generic import PrepareVectorization
9
+ from fabricatio.models.task import Task
10
+ from questionary import text
9
11
 
10
12
 
11
13
  class InjectToDB(Action, RAG):
@@ -14,13 +16,58 @@ class InjectToDB(Action, RAG):
14
16
  output_key: str = "collection_name"
15
17
 
16
18
  async def _execute[T: PrepareVectorization](
17
- self, to_inject: Optional[T] | List[Optional[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, **_
18
20
  ) -> Optional[str]:
19
21
  if not isinstance(to_inject, list):
20
22
  to_inject = [to_inject]
21
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)
22
26
  await self.view(collection_name, create=True).consume_string(
23
- [t.prepare_vectorization(self.embedding_max_sequence_length) for t in to_inject if isinstance(t,PrepareVectorization)],
27
+ [
28
+ t.prepare_vectorization(self.embedding_max_sequence_length)
29
+ for t in to_inject
30
+ if isinstance(t, PrepareVectorization)
31
+ ],
24
32
  )
25
33
 
26
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
@@ -10,9 +10,11 @@ from typing import Optional, Unpack, cast
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 CorrectKwargs, 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):
@@ -55,7 +57,7 @@ class Correct(Review):
55
57
  if supervisor_check:
56
58
  await review_res.supervisor_check()
57
59
  if "default" in kwargs:
58
- cast(ReviewKwargs[None], kwargs)["default"] = None
60
+ cast("ReviewKwargs[None]", kwargs)["default"] = None
59
61
  return await self.propose(
60
62
  obj.__class__,
61
63
  TEMPLATE_MANAGER.render_template(
@@ -89,7 +91,7 @@ class Correct(Review):
89
91
  await review_res.supervisor_check()
90
92
 
91
93
  if "default" in kwargs:
92
- cast(ReviewKwargs[None], kwargs)["default"] = None
94
+ cast("ReviewKwargs[None]", kwargs)["default"] = None
93
95
  return await self.ageneric_string(
94
96
  TEMPLATE_MANAGER.render_template(
95
97
  configs.templates.correct_template, {"content": input_text, "review": review_res.display()}
@@ -113,3 +115,31 @@ class Correct(Review):
113
115
  Optional[Task[T]]: The corrected task, or None if correction fails.
114
116
  """
115
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
@@ -19,6 +19,7 @@ from fabricatio.models.kwargs_types import (
19
19
  EmbeddingKwargs,
20
20
  FetchKwargs,
21
21
  LLMKwargs,
22
+ RetrievalKwargs,
22
23
  )
23
24
  from fabricatio.models.usages import EmbeddingUsage
24
25
  from fabricatio.models.utils import MilvusData, ok
@@ -213,6 +214,25 @@ class RAG(EmbeddingUsage):
213
214
  self.add_document(await self.pack(text), collection_name or self.safe_target_collection, flush=True)
214
215
  return self
215
216
 
217
+ @overload
218
+ async def afetch_document[V: (int, str, float, bytes)](
219
+ self,
220
+ vecs: List[List[float]],
221
+ desired_fields: List[str],
222
+ collection_name: Optional[str] = None,
223
+ similarity_threshold: float = 0.37,
224
+ result_per_query: int = 10,
225
+ ) -> List[Dict[str, V]]: ...
226
+
227
+ @overload
228
+ async def afetch_document[V: (int, str, float, bytes)](
229
+ self,
230
+ vecs: List[List[float]],
231
+ desired_fields: str,
232
+ collection_name: Optional[str] = None,
233
+ similarity_threshold: float = 0.37,
234
+ result_per_query: int = 10,
235
+ ) -> List[V]: ...
216
236
  async def afetch_document[V: (int, str, float, bytes)](
217
237
  self,
218
238
  vecs: List[List[float]],
@@ -275,7 +295,7 @@ class RAG(EmbeddingUsage):
275
295
  if isinstance(query, str):
276
296
  query = [query]
277
297
  return cast(
278
- List[str],
298
+ "List[str]",
279
299
  await self.afetch_document(
280
300
  vecs=(await self.vectorize(query)),
281
301
  desired_fields="text",
@@ -283,6 +303,24 @@ class RAG(EmbeddingUsage):
283
303
  ),
284
304
  )[:final_limit]
285
305
 
306
+ async def aretrieve_compact(
307
+ self,
308
+ query: List[str] | str,
309
+ **kwargs: Unpack[RetrievalKwargs],
310
+ ) -> str:
311
+ """Retrieve data from the collection and format it for display.
312
+
313
+ Args:
314
+ query (List[str] | str): The query to be used for retrieval.
315
+ **kwargs (Unpack[RetrievalKwargs]): Additional keyword arguments for retrieval.
316
+
317
+ Returns:
318
+ str: A formatted string containing the retrieved data.
319
+ """
320
+ return TEMPLATE_MANAGER.render_template(
321
+ configs.templates.retrieved_display_template, {"docs": (await self.aretrieve(query, **kwargs))}
322
+ )
323
+
286
324
  async def aask_retrieved(
287
325
  self,
288
326
  question: str,
@@ -313,16 +351,14 @@ class RAG(EmbeddingUsage):
313
351
  Returns:
314
352
  str: A string response generated after asking with the context of retrieved documents.
315
353
  """
316
- docs = await self.aretrieve(
354
+ rendered = await self.aretrieve_compact(
317
355
  query or question,
318
- final_limit,
356
+ final_limit=final_limit,
319
357
  collection_name=collection_name,
320
358
  result_per_query=result_per_query,
321
359
  similarity_threshold=similarity_threshold,
322
360
  )
323
361
 
324
- rendered = TEMPLATE_MANAGER.render_template(configs.templates.retrieved_display_template, {"docs": docs[::-1]})
325
-
326
362
  logger.debug(f"Retrieved Documents: \n{rendered}")
327
363
  return await self.aask(
328
364
  question,
@@ -159,7 +159,7 @@ class GiveRating(WithBriefing, LLMUsage):
159
159
  )
160
160
  ),
161
161
  validator=_validator,
162
- **self.prepend(kwargs),
162
+ **self.prepend_sys_msg(kwargs),
163
163
  )
164
164
 
165
165
  async def draft_rating_criteria(
@@ -191,7 +191,7 @@ class GiveRating(WithBriefing, LLMUsage):
191
191
  validator=lambda resp: set(out)
192
192
  if (out := JsonCapture.validate_with(resp, list, str, criteria_count)) is not None
193
193
  else out,
194
- **self.prepend(kwargs),
194
+ **self.prepend_sys_msg(kwargs),
195
195
  )
196
196
 
197
197
  async def draft_rating_criteria_from_examples(
@@ -244,7 +244,7 @@ class GiveRating(WithBriefing, LLMUsage):
244
244
  validator=lambda resp: JsonCapture.validate_with(
245
245
  resp, target_type=list, elements_type=str, length=reasons_count
246
246
  ),
247
- **self.prepend(kwargs),
247
+ **self.prepend_sys_msg(kwargs),
248
248
  )
249
249
  )
250
250
  # extract certain mount of criteria from reasons according to their importance and frequency
@@ -301,7 +301,7 @@ class GiveRating(WithBriefing, LLMUsage):
301
301
  for pair in windows
302
302
  ],
303
303
  validator=lambda resp: JsonCapture.validate_with(resp, target_type=float),
304
- **self.prepend(kwargs),
304
+ **self.prepend_sys_msg(kwargs),
305
305
  )
306
306
  weights = [1]
307
307
  for rw in relative_weights:
@@ -121,7 +121,7 @@ class ReviewResult[T](ProposedAble, Display):
121
121
  ReviewResult[K]: The current instance with updated reference type.
122
122
  """
123
123
  self._ref = ref # pyright: ignore [reportAttributeAccessIssue]
124
- return cast(ReviewResult[K], self)
124
+ return cast("ReviewResult[K]", self)
125
125
 
126
126
  def deref(self) -> T:
127
127
  """Retrieve the referenced object that was reviewed.
@@ -200,7 +200,7 @@ class Review(GiveRating, Propose):
200
200
  ReviewResult[Task[T]]: A review result containing identified problems and proposed solutions,
201
201
  with a reference to the original task.
202
202
  """
203
- return cast(ReviewResult[Task[T]], await self.review_obj(task, **kwargs))
203
+ return cast('ReviewResult[Task[T]]', await self.review_obj(task, **kwargs))
204
204
 
205
205
  async def review_string(
206
206
  self,
@@ -23,7 +23,7 @@ class ProposeTask(WithBriefing, Propose):
23
23
  self,
24
24
  prompt: str,
25
25
  **kwargs: Unpack[ValidateKwargs[Task[T]]],
26
- ) -> Task[T]:
26
+ ) -> Optional[Task[T]]:
27
27
  """Asynchronously proposes a task based on a given prompt and parameters.
28
28
 
29
29
  Parameters:
@@ -37,7 +37,7 @@ class ProposeTask(WithBriefing, Propose):
37
37
  logger.error(err := f"{self.name}: Prompt must be provided.")
38
38
  raise ValueError(err)
39
39
 
40
- return await self.propose(Task, prompt, **self.prepend(cast(Dict[str, Any], kwargs)))
40
+ return await self.propose(Task, prompt, **self.prepend_sys_msg(cast("Dict[str, Any]", kwargs)))
41
41
 
42
42
 
43
43
  class HandleTask(WithBriefing, ToolBoxUsage):
@@ -81,7 +81,7 @@ class HandleTask(WithBriefing, ToolBoxUsage):
81
81
  return await self.aask_validate(
82
82
  question=q,
83
83
  validator=_validator,
84
- **self.prepend(cast(Dict[str, Any], kwargs)),
84
+ **self.prepend_sys_msg(cast("Dict[str, Any]", kwargs)),
85
85
  )
86
86
 
87
87
  async def handle_fine_grind(
fabricatio/config.py CHANGED
@@ -235,6 +235,9 @@ class TemplateConfig(BaseModel):
235
235
  co_validation_template: str = Field(default="co_validation")
236
236
  """The name of the co-validation template which will be used to co-validate a string."""
237
237
 
238
+ as_prompt_template: str = Field(default="as_prompt")
239
+ """The name of the as prompt template which will be used to convert a string to a prompt."""
240
+
238
241
 
239
242
  class MagikaConfig(BaseModel):
240
243
  """Magika configuration class."""
@@ -48,7 +48,7 @@ class Action(HandleTask, ProposeTask, Correct):
48
48
  self.description = self.description or self.__class__.__doc__ or ""
49
49
 
50
50
  @abstractmethod
51
- async def _execute(self, **cxt) -> Any:
51
+ async def _execute(self,*_, **cxt) -> Any: # noqa: ANN002
52
52
  """Execute the action logic with the provided context arguments.
53
53
 
54
54
  This method must be implemented by subclasses to define the actual behavior.