fabricatio 0.2.6__cp39-cp39-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. fabricatio/__init__.py +43 -0
  2. fabricatio/_rust.cp39-win_amd64.pyd +0 -0
  3. fabricatio/_rust.pyi +115 -0
  4. fabricatio/_rust_instances.py +10 -0
  5. fabricatio/actions/article.py +128 -0
  6. fabricatio/actions/output.py +19 -0
  7. fabricatio/actions/rag.py +71 -0
  8. fabricatio/capabilities/correct.py +115 -0
  9. fabricatio/capabilities/propose.py +49 -0
  10. fabricatio/capabilities/rag.py +384 -0
  11. fabricatio/capabilities/rating.py +339 -0
  12. fabricatio/capabilities/review.py +278 -0
  13. fabricatio/capabilities/task.py +113 -0
  14. fabricatio/config.py +405 -0
  15. fabricatio/core.py +181 -0
  16. fabricatio/decorators.py +179 -0
  17. fabricatio/fs/__init__.py +29 -0
  18. fabricatio/fs/curd.py +149 -0
  19. fabricatio/fs/readers.py +46 -0
  20. fabricatio/journal.py +21 -0
  21. fabricatio/models/action.py +230 -0
  22. fabricatio/models/events.py +120 -0
  23. fabricatio/models/extra.py +655 -0
  24. fabricatio/models/generic.py +406 -0
  25. fabricatio/models/kwargs_types.py +169 -0
  26. fabricatio/models/role.py +72 -0
  27. fabricatio/models/task.py +299 -0
  28. fabricatio/models/tool.py +189 -0
  29. fabricatio/models/usages.py +718 -0
  30. fabricatio/models/utils.py +192 -0
  31. fabricatio/parser.py +151 -0
  32. fabricatio/py.typed +0 -0
  33. fabricatio/toolboxes/__init__.py +15 -0
  34. fabricatio/toolboxes/arithmetic.py +62 -0
  35. fabricatio/toolboxes/fs.py +31 -0
  36. fabricatio/workflows/articles.py +26 -0
  37. fabricatio/workflows/rag.py +11 -0
  38. fabricatio-0.2.6.data/scripts/tdown.exe +0 -0
  39. fabricatio-0.2.6.dist-info/METADATA +432 -0
  40. fabricatio-0.2.6.dist-info/RECORD +42 -0
  41. fabricatio-0.2.6.dist-info/WHEEL +4 -0
  42. fabricatio-0.2.6.dist-info/licenses/LICENSE +21 -0
fabricatio/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """Fabricatio is a Python library for building llm app using event-based agent structure."""
2
+
3
+ from importlib.util import find_spec
4
+
5
+ from fabricatio import actions, toolboxes, workflows
6
+ from fabricatio._rust import BibManager
7
+ from fabricatio._rust_instances import TEMPLATE_MANAGER
8
+ from fabricatio.core import env
9
+ from fabricatio.journal import logger
10
+ from fabricatio.models import extra
11
+ from fabricatio.models.action import Action, WorkFlow
12
+ from fabricatio.models.events import Event
13
+ from fabricatio.models.role import Role
14
+ from fabricatio.models.task import Task
15
+ from fabricatio.models.tool import ToolBox
16
+ from fabricatio.parser import Capture, GenericCapture, JsonCapture, PythonCapture
17
+
18
+ __all__ = [
19
+ "TEMPLATE_MANAGER",
20
+ "Action",
21
+ "BibManager",
22
+ "Capture",
23
+ "Event",
24
+ "GenericCapture",
25
+ "JsonCapture",
26
+ "PythonCapture",
27
+ "Role",
28
+ "Task",
29
+ "ToolBox",
30
+ "WorkFlow",
31
+ "actions",
32
+ "env",
33
+ "extra",
34
+ "logger",
35
+ "toolboxes",
36
+ "workflows",
37
+ ]
38
+
39
+
40
+ if find_spec("pymilvus"):
41
+ from fabricatio.capabilities.rag import RAG
42
+
43
+ __all__ += ["RAG"]
Binary file
fabricatio/_rust.pyi ADDED
@@ -0,0 +1,115 @@
1
+ from pathlib import Path
2
+ from typing import Any, Dict, List, Optional
3
+
4
+ class TemplateManager:
5
+ """Template rendering engine using Handlebars templates.
6
+
7
+ This manager handles template discovery, loading, and rendering
8
+ through a wrapper around the handlebars-rust engine.
9
+
10
+ See: https://crates.io/crates/handlebars
11
+ """
12
+
13
+ def __init__(
14
+ self, template_dirs: List[Path], suffix: Optional[str] = None, active_loading: Optional[bool] = None
15
+ ) -> None:
16
+ """Initialize the template manager.
17
+
18
+ Args:
19
+ template_dirs: List of directories containing template files
20
+ suffix: File extension for templates (defaults to 'hbs')
21
+ active_loading: Whether to enable dev mode for reloading templates on change
22
+ """
23
+
24
+ @property
25
+ def template_count(self) -> int:
26
+ """Returns the number of currently loaded templates."""
27
+
28
+ def get_template_source(self, name: str) -> Optional[str]:
29
+ """Get the filesystem path for a template.
30
+
31
+ Args:
32
+ name: Template name (without extension)
33
+
34
+ Returns:
35
+ Path to the template file if found, None otherwise
36
+ """
37
+
38
+ def discover_templates(self) -> None:
39
+ """Scan template directories and load available templates.
40
+
41
+ This refreshes the template cache, finding any new or modified templates.
42
+ """
43
+
44
+ def render_template(self, name: str, data: Dict[str, Any]) -> str:
45
+ """Render a template with context data.
46
+
47
+ Args:
48
+ name: Template name (without extension)
49
+ data: Context dictionary to provide variables to the template
50
+
51
+ Returns:
52
+ Rendered template content as string
53
+
54
+ Raises:
55
+ RuntimeError: If template rendering fails
56
+ """
57
+
58
+
59
+ def blake3_hash(content: bytes) -> str:
60
+ """Calculate the BLAKE3 cryptographic hash of data.
61
+
62
+ Args:
63
+ content: Bytes to be hashed
64
+
65
+ Returns:
66
+ Hex-encoded BLAKE3 hash string
67
+ """
68
+
69
+
70
+ class BibManager:
71
+ """BibTeX bibliography manager for parsing and querying citation data."""
72
+
73
+ def __init__(self, path: str) -> None:
74
+ """Initialize the bibliography manager.
75
+
76
+ Args:
77
+ path: Path to BibTeX (.bib) file to load
78
+
79
+ Raises:
80
+ RuntimeError: If file cannot be read or parsed
81
+ """
82
+
83
+ def get_cite_key(self, title: str) -> Optional[str]:
84
+ """Find citation key by exact title match.
85
+
86
+ Args:
87
+ title: Full title to search for (case-insensitive)
88
+
89
+ Returns:
90
+ Citation key if exact match found, None otherwise
91
+ """
92
+
93
+ def get_cite_key_fuzzy(self, query: str) -> Optional[str]:
94
+ """Find best matching citation using fuzzy text search.
95
+
96
+ Args:
97
+ query: Search term to find in bibliography entries
98
+
99
+ Returns:
100
+ Citation key of best matching entry, or None if no good match
101
+
102
+ Notes:
103
+ Uses nucleo_matcher for high-quality fuzzy text searching
104
+ See: https://crates.io/crates/nucleo-matcher
105
+ """
106
+
107
+ def list_titles(self, is_verbatim: Optional[bool] = False) -> List[str]:
108
+ """List all titles in the bibliography.
109
+
110
+ Args:
111
+ is_verbatim: Whether to return verbatim titles (without formatting)
112
+
113
+ Returns:
114
+ List of all titles in the bibliography
115
+ """
@@ -0,0 +1,10 @@
1
+ """Some necessary instances."""
2
+
3
+ from fabricatio._rust import TemplateManager
4
+ from fabricatio.config import configs
5
+
6
+ TEMPLATE_MANAGER = TemplateManager(
7
+ template_dirs=configs.templates.template_dir,
8
+ suffix=configs.templates.template_suffix,
9
+ active_loading=configs.templates.active_loading,
10
+ )
@@ -0,0 +1,128 @@
1
+ """Actions for transmitting tasks to targets."""
2
+
3
+ from os import PathLike
4
+ from pathlib import Path
5
+ from typing import Any, Callable, List, Optional
6
+
7
+ from fabricatio.fs import safe_text_read
8
+ from fabricatio.journal import logger
9
+ from fabricatio.models.action import Action
10
+ from fabricatio.models.extra import ArticleEssence, ArticleOutline, ArticleProposal
11
+ from fabricatio.models.task import Task
12
+ from questionary import confirm, text
13
+ from rich import print as rprint
14
+
15
+
16
+ class ExtractArticleEssence(Action):
17
+ """Extract the essence of article(s) in text format from the paths specified in the task dependencies.
18
+
19
+ Notes:
20
+ This action is designed to extract vital information from articles with Markdown format, which is pure text, and
21
+ which is converted from pdf files using `magic-pdf` from the `MinerU` project, see https://github.com/opendatalab/MinerU
22
+ """
23
+
24
+ output_key: str = "article_essence"
25
+ """The key of the output data."""
26
+
27
+ async def _execute[P: PathLike | str](
28
+ self,
29
+ task_input: Task,
30
+ reader: Callable[[P], str] = lambda p: Path(p).read_text(encoding="utf-8"),
31
+ **_,
32
+ ) -> Optional[List[ArticleEssence]]:
33
+ if not task_input.dependencies:
34
+ logger.info(err := "Task not approved, since no dependencies are provided.")
35
+ raise RuntimeError(err)
36
+
37
+ # trim the references
38
+ contents = ["References".join(c.split("References")[:-1]) for c in map(reader, task_input.dependencies)]
39
+ return await self.propose(
40
+ ArticleEssence,
41
+ contents,
42
+ system_message=f"# your personal briefing: \n{self.briefing}",
43
+ )
44
+
45
+
46
+ class GenerateArticleProposal(Action):
47
+ """Generate an outline for the article based on the extracted essence."""
48
+
49
+ output_key: str = "article_proposal"
50
+ """The key of the output data."""
51
+
52
+ async def _execute(
53
+ self,
54
+ task_input: Task,
55
+ **_,
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
+ )
60
+
61
+ return await self.propose(
62
+ ArticleProposal,
63
+ safe_text_read(input_path),
64
+ system_message=f"# your personal briefing: \n{self.briefing}",
65
+ )
66
+
67
+
68
+ class GenerateOutline(Action):
69
+ """Generate the article based on the outline."""
70
+
71
+ output_key: str = "article_outline"
72
+ """The key of the output data."""
73
+
74
+ async def _execute(
75
+ self,
76
+ article_proposal: ArticleProposal,
77
+ **_,
78
+ ) -> Optional[ArticleOutline]:
79
+ return await self.propose(
80
+ ArticleOutline,
81
+ article_proposal.display(),
82
+ system_message=f"# your personal briefing: \n{self.briefing}",
83
+ )
84
+
85
+
86
+ class CorrectProposal(Action):
87
+ """Correct the proposal of the article."""
88
+
89
+ output_key: str = "corrected_proposal"
90
+
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."
94
+ )
95
+
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
+
109
+ class CorrectOutline(Action):
110
+ """Correct the outline of the article."""
111
+
112
+ output_key: str = "corrected_outline"
113
+ """The key of the output data."""
114
+
115
+ async def _execute(
116
+ self,
117
+ article_outline: ArticleOutline,
118
+ article_proposal: ArticleProposal,
119
+
120
+ **_,
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
@@ -0,0 +1,19 @@
1
+ """Dump the finalized output to a file."""
2
+
3
+ from fabricatio.models.action import Action
4
+ from fabricatio.models.generic import FinalizedDumpAble
5
+ from fabricatio.models.task import Task
6
+
7
+
8
+ class DumpFinalizedOutput(Action):
9
+ """Dump the finalized output to a file."""
10
+
11
+ output_key: str = "dump_path"
12
+
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."
16
+ )
17
+
18
+ to_dump.finalized_dump_to(dump_path)
19
+ return dump_path
@@ -0,0 +1,71 @@
1
+ """Inject data into the database."""
2
+
3
+ from typing import List, Optional
4
+
5
+ from fabricatio.capabilities.rag import RAG
6
+ from fabricatio.journal import logger
7
+ from fabricatio.models.action import Action
8
+ from fabricatio.models.generic import PrepareVectorization
9
+ from fabricatio.models.task import Task
10
+ from questionary import text
11
+
12
+
13
+ class InjectToDB(Action, RAG):
14
+ """Inject data into the database."""
15
+
16
+ output_key: str = "collection_name"
17
+
18
+ async def _execute[T: PrepareVectorization](
19
+ self, to_inject: Optional[T] | List[Optional[T]], collection_name: Optional[str] = "my_collection", **_
20
+ ) -> Optional[str]:
21
+ if not isinstance(to_inject, list):
22
+ to_inject = [to_inject]
23
+ logger.info(f"Injecting {len(to_inject)} items into the collection '{collection_name}'")
24
+ await self.view(collection_name, create=True).consume_string(
25
+ [
26
+ t.prepare_vectorization(self.embedding_max_sequence_length)
27
+ for t in to_inject
28
+ if isinstance(t, PrepareVectorization)
29
+ ],
30
+ )
31
+
32
+ return collection_name
33
+
34
+
35
+ class RAGTalk(Action, RAG):
36
+ """RAG-enabled conversational action that processes user questions based on a given task.
37
+
38
+ This action establishes an interactive conversation loop where it retrieves context-relevant
39
+ information to answer user queries according to the assigned task briefing.
40
+
41
+ Notes:
42
+ task_input: Task briefing that guides how to respond to user questions
43
+ collection_name: Name of the vector collection to use for retrieval (default: "my_collection")
44
+
45
+ Returns:
46
+ Number of conversation turns completed before termination
47
+ """
48
+
49
+ output_key: str = "task_output"
50
+
51
+ async def _execute(self, task_input: Task[str], **kwargs) -> int:
52
+ collection_name = kwargs.get("collection_name", "my_collection")
53
+ counter = 0
54
+
55
+ self.view(collection_name, create=True)
56
+
57
+ try:
58
+ while True:
59
+ user_say = await text("User: ").ask_async()
60
+ if user_say is None:
61
+ break
62
+ gpt_say = await self.aask_retrieved(
63
+ user_say,
64
+ user_say,
65
+ extra_system_message=f"You have to answer to user obeying task assigned to you:\n{task_input.briefing}",
66
+ )
67
+ print(f"GPT: {gpt_say}") # noqa: T201
68
+ counter += 1
69
+ except KeyboardInterrupt:
70
+ logger.info(f"executed talk action {counter} times")
71
+ return counter
@@ -0,0 +1,115 @@
1
+ """Correct capability module providing advanced review and validation functionality.
2
+
3
+ This module implements the Correct capability, which extends the Review functionality
4
+ to provide mechanisms for reviewing, validating, and correcting various objects and tasks
5
+ based on predefined criteria and templates.
6
+ """
7
+
8
+ from typing import Optional, Unpack, cast
9
+
10
+ from fabricatio._rust_instances import TEMPLATE_MANAGER
11
+ from fabricatio.capabilities.review import Review, ReviewResult
12
+ from fabricatio.config import configs
13
+ from fabricatio.models.generic import Display, ProposedAble, WithBriefing
14
+ from fabricatio.models.kwargs_types import CorrectKwargs, ReviewKwargs
15
+ from fabricatio.models.task import Task
16
+
17
+
18
+ class Correct(Review):
19
+ """Correct capability for reviewing, validating, and improving objects.
20
+
21
+ This class enhances the Review capability with specialized functionality for
22
+ correcting and improving objects based on review feedback. It can process
23
+ various inputs including tasks, strings, and generic objects that implement
24
+ the required interfaces, applying corrections based on templated review processes.
25
+ """
26
+
27
+ async def correct_obj[M: ProposedAble](
28
+ self,
29
+ obj: M,
30
+ reference: str = "",
31
+ supervisor_check: bool = True,
32
+ **kwargs: Unpack[ReviewKwargs[ReviewResult[str]]],
33
+ ) -> Optional[M]:
34
+ """Review and correct an object based on defined criteria and templates.
35
+
36
+ This method first conducts a review of the given object, then uses the review results
37
+ to generate a corrected version of the object using appropriate templates.
38
+
39
+ Args:
40
+ obj (M): The object to be reviewed and corrected. Must implement ProposedAble.
41
+ reference (str): A reference or contextual information for the object.
42
+ supervisor_check (bool, optional): Whether to perform a supervisor check on the review results. Defaults to True.
43
+ **kwargs: Review configuration parameters including criteria and review options.
44
+
45
+ Returns:
46
+ Optional[M]: A corrected version of the input object, or None if correction fails.
47
+
48
+ Raises:
49
+ TypeError: If the provided object doesn't implement Display or WithBriefing interfaces.
50
+ """
51
+ if not isinstance(obj, (Display, WithBriefing)):
52
+ raise TypeError(f"Expected Display or WithBriefing, got {type(obj)}")
53
+
54
+ review_res = await self.review_obj(obj, **kwargs)
55
+ if supervisor_check:
56
+ await review_res.supervisor_check()
57
+ if "default" in kwargs:
58
+ cast(ReviewKwargs[None], kwargs)["default"] = None
59
+ return await self.propose(
60
+ obj.__class__,
61
+ TEMPLATE_MANAGER.render_template(
62
+ configs.templates.correct_template,
63
+ {
64
+ "content": f"{(reference + '\n\nAbove is referencing material') if reference else ''}{obj.display() if isinstance(obj, Display) else obj.briefing}",
65
+ "review": review_res.display(),
66
+ },
67
+ ),
68
+ **kwargs,
69
+ )
70
+
71
+ async def correct_string(
72
+ self, input_text: str, supervisor_check: bool = True, **kwargs: Unpack[ReviewKwargs[ReviewResult[str]]]
73
+ ) -> Optional[str]:
74
+ """Review and correct a string based on defined criteria and templates.
75
+
76
+ This method applies the review process to the input text and generates
77
+ a corrected version based on the review results.
78
+
79
+ Args:
80
+ input_text (str): The text content to be reviewed and corrected.
81
+ supervisor_check (bool, optional): Whether to perform a supervisor check on the review results. Defaults to True.
82
+ **kwargs: Review configuration parameters including criteria and review options.
83
+
84
+ Returns:
85
+ Optional[str]: The corrected text content, or None if correction fails.
86
+ """
87
+ review_res = await self.review_string(input_text, **kwargs)
88
+ if supervisor_check:
89
+ await review_res.supervisor_check()
90
+
91
+ if "default" in kwargs:
92
+ cast(ReviewKwargs[None], kwargs)["default"] = None
93
+ return await self.ageneric_string(
94
+ TEMPLATE_MANAGER.render_template(
95
+ configs.templates.correct_template, {"content": input_text, "review": review_res.display()}
96
+ ),
97
+ **kwargs,
98
+ )
99
+
100
+ async def correct_task[T](
101
+ self, task: Task[T], **kwargs: Unpack[CorrectKwargs[ReviewResult[str]]]
102
+ ) -> Optional[Task[T]]:
103
+ """Review and correct a task object based on defined criteria.
104
+
105
+ This is a specialized version of correct_obj specifically for Task objects,
106
+ applying the same review and correction process to task definitions.
107
+
108
+ Args:
109
+ task (Task[T]): The task to be reviewed and corrected.
110
+ **kwargs: Review configuration parameters including criteria and review options.
111
+
112
+ Returns:
113
+ Optional[Task[T]]: The corrected task, or None if correction fails.
114
+ """
115
+ return await self.correct_obj(task, **kwargs)
@@ -0,0 +1,49 @@
1
+ """A module for the task capabilities of the Fabricatio library."""
2
+
3
+ from typing import List, Optional, Type, Unpack, overload
4
+
5
+ from fabricatio.models.generic import ProposedAble
6
+ from fabricatio.models.kwargs_types import ValidateKwargs
7
+ from fabricatio.models.usages import LLMUsage
8
+
9
+
10
+ class Propose(LLMUsage):
11
+ """A class that proposes an Obj based on a prompt."""
12
+
13
+ @overload
14
+ async def propose[M: ProposedAble](
15
+ self,
16
+ cls: Type[M],
17
+ prompt: List[str],
18
+ **kwargs: Unpack[ValidateKwargs[M]],
19
+ ) -> Optional[List[M]]: ...
20
+
21
+ @overload
22
+ async def propose[M: ProposedAble](
23
+ self,
24
+ cls: Type[M],
25
+ prompt: str,
26
+ **kwargs: Unpack[ValidateKwargs[M]],
27
+ ) -> Optional[M]: ...
28
+
29
+ async def propose[M: ProposedAble](
30
+ self,
31
+ cls: Type[M],
32
+ prompt: List[str] | str,
33
+ **kwargs: Unpack[ValidateKwargs[M]],
34
+ ) -> Optional[List[M] | M]:
35
+ """Asynchronously proposes a task based on a given prompt and parameters.
36
+
37
+ Parameters:
38
+ cls: The class type of the task to be proposed.
39
+ prompt: The prompt text for proposing a task, which is a string that must be provided.
40
+ **kwargs: The keyword arguments for the LLM (Large Language Model) usage.
41
+
42
+ Returns:
43
+ A Task object based on the proposal result.
44
+ """
45
+ return await self.aask_validate(
46
+ question=cls.create_json_prompt(prompt),
47
+ validator=cls.instantiate_from_string,
48
+ **kwargs,
49
+ )