fabricatio 0.2.7.dev3__cp312-cp312-win_amd64.whl → 0.2.7.dev4__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.
@@ -23,6 +23,7 @@ from pydantic import (
23
23
  PrivateAttr,
24
24
  SecretStr,
25
25
  )
26
+ from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
26
27
 
27
28
 
28
29
  class Base(BaseModel):
@@ -172,6 +173,23 @@ class WithBriefing(Named, Described):
172
173
  raise TypeError(f"{system_msg_like} is not a dict or str")
173
174
 
174
175
 
176
+ class ReverseGenerate(GenerateJsonSchema):
177
+ """Class that provides a reverse JSON schema of the model."""
178
+
179
+ def _sort_recursive(self, value: Any, parent_key: str | None = None) -> Any:
180
+ if isinstance(value, dict):
181
+ sorted_dict: dict[str, JsonSchemaValue] = {}
182
+ # Reverse all keys regardless of parent_key
183
+ keys = reversed(value.keys())
184
+ for key in keys:
185
+ sorted_dict[key] = self._sort_recursive(value[key], parent_key=key)
186
+ return sorted_dict
187
+ if isinstance(value, list):
188
+ # Reverse list order and process each item
189
+ return [self._sort_recursive(item, parent_key) for item in reversed(value)]
190
+ return value
191
+
192
+
175
193
  class WithFormatedJsonSchema(Base):
176
194
  """Class that provides a formatted JSON schema of the model."""
177
195
 
@@ -183,8 +201,8 @@ class WithFormatedJsonSchema(Base):
183
201
  str: The JSON schema of the model in a formatted string.
184
202
  """
185
203
  return orjson.dumps(
186
- cls.model_json_schema(),
187
- option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS,
204
+ cls.model_json_schema(schema_generator=ReverseGenerate),
205
+ option=orjson.OPT_INDENT_2,
188
206
  ).decode()
189
207
 
190
208
 
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.4
2
+ Name: fabricatio
3
+ Version: 0.2.7.dev4
4
+ Classifier: License :: OSI Approved :: MIT License
5
+ Classifier: Programming Language :: Rust
6
+ Classifier: Programming Language :: Python :: 3.12
7
+ Classifier: Programming Language :: Python :: Implementation :: CPython
8
+ Classifier: Framework :: AsyncIO
9
+ Classifier: Framework :: Pydantic :: 2
10
+ Classifier: Typing :: Typed
11
+ Requires-Dist: appdirs>=1.4.4
12
+ Requires-Dist: asyncio>=3.4.3
13
+ Requires-Dist: asyncstdlib>=3.13.0
14
+ Requires-Dist: json-repair>=0.39.1
15
+ Requires-Dist: litellm>=1.60.0
16
+ Requires-Dist: loguru>=0.7.3
17
+ Requires-Dist: magika>=0.5.1
18
+ Requires-Dist: more-itertools>=10.6.0
19
+ Requires-Dist: orjson>=3.10.15
20
+ Requires-Dist: pydantic>=2.10.6
21
+ Requires-Dist: pydantic-settings>=2.7.1
22
+ Requires-Dist: pymitter>=1.0.0
23
+ Requires-Dist: questionary>=2.1.0
24
+ Requires-Dist: regex>=2024.11.6
25
+ Requires-Dist: rich>=13.9.4
26
+ Requires-Dist: pymilvus>=2.5.4 ; extra == 'rag'
27
+ Requires-Dist: fabricatio[calc,plot,rag] ; extra == 'full'
28
+ Requires-Dist: sympy>=1.13.3 ; extra == 'calc'
29
+ Requires-Dist: matplotlib>=3.10.1 ; extra == 'plot'
30
+ Provides-Extra: rag
31
+ Provides-Extra: full
32
+ Provides-Extra: calc
33
+ Provides-Extra: plot
34
+ License-File: LICENSE
35
+ Summary: A LLM multi-agent framework.
36
+ Keywords: ai,agents,multi-agent,llm,pyo3
37
+ Author-email: Whth <zettainspector@foxmail.com>
38
+ Requires-Python: >=3.12, <3.13
39
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
40
+ Project-URL: Homepage, https://github.com/Whth/fabricatio
41
+ Project-URL: Repository, https://github.com/Whth/fabricatio
42
+ Project-URL: Issues, https://github.com/Whth/fabricatio/issues
43
+
44
+ # Fabricatio
45
+
46
+ ![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)
47
+ ![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)
48
+ ![Build Status](https://img.shields.io/badge/build-passing-brightgreen)
49
+
50
+ ## Overview
51
+
52
+ Fabricatio is a streamlined Python library for building LLM applications using an event-based agent structure. It leverages Rust for performance-critical tasks, Handlebars for templating, and PyO3 for Python bindings.
53
+
54
+ ## Features
55
+
56
+ - **Event-Driven Architecture**: Robust task management through an EventEmitter pattern.
57
+ - **LLM Integration & Templating**: Seamlessly interact with large language models and dynamic content generation.
58
+ - **Async & Extensible**: Fully asynchronous execution with easy extension via custom actions and workflows.
59
+
60
+ ## Installation
61
+
62
+ ### Using UV (Recommended)
63
+
64
+ ```bash
65
+ # Install uv if not already installed
66
+ pip install uv
67
+
68
+ # Clone the repository
69
+ git clone https://github.com/Whth/fabricatio.git
70
+ cd fabricatio
71
+
72
+ # Install the package in development mode with uv
73
+ uv --with-editable . maturin develop --uv -r
74
+ ```
75
+
76
+ ### Building Distribution
77
+
78
+ ```bash
79
+ # Build distribution packages
80
+ make bdist
81
+ ```
82
+
83
+ ## Usage
84
+
85
+ ### Basic Example
86
+
87
+ ```python
88
+ import asyncio
89
+ from fabricatio import Action, Role, Task, logger, WorkFlow
90
+ from typing import Any
91
+
92
+ class Hello(Action):
93
+ name: str = "hello"
94
+ output_key: str = "task_output"
95
+
96
+ async def _execute(self, task_input: Task[str], **_) -> Any:
97
+ ret = "Hello fabricatio!"
98
+ logger.info("executing talk action")
99
+ return ret
100
+
101
+ async def main() -> None:
102
+ role = Role(
103
+ name="talker",
104
+ description="talker role",
105
+ registry={Task.pending_label: WorkFlow(name="talk", steps=(Hello,))}
106
+ )
107
+
108
+ task = Task(name="say hello", goals="say hello", description="say hello to the world")
109
+ result = await task.delegate()
110
+ logger.success(f"Result: {result}")
111
+
112
+ if __name__ == "__main__":
113
+ asyncio.run(main())
114
+ ```
115
+
116
+ ### Examples
117
+
118
+ For various usage scenarios, refer to the following examples:
119
+ - Simple Chat
120
+ - Retrieval-Augmented Generation (RAG)
121
+ - Article Extraction
122
+ - Propose Task
123
+ - Code Review
124
+ - Write Outline
125
+
126
+ _(For full example details, please check our detailed documentation, see [Examples](./examples))_
127
+
128
+ ## Configuration
129
+
130
+ The configuration for Fabricatio is managed via environment variables or TOML files. For example:
131
+
132
+ ```toml
133
+ [llm]
134
+ api_endpoint = "https://api.openai.com"
135
+ api_key = "your_openai_api_key"
136
+ timeout = 300
137
+ max_retries = 3
138
+ model = "gpt-3.5-turbo"
139
+ temperature = 1.0
140
+ stop_sign = ["\n\n\n", "User:"]
141
+ top_p = 0.35
142
+ generation_count = 1
143
+ stream = false
144
+ max_tokens = 8192
145
+ ```
146
+
147
+ ## Development Setup
148
+
149
+ 1. **Clone the Repository**:
150
+ ```bash
151
+ git clone https://github.com/Whth/fabricatio.git
152
+ cd fabricatio
153
+ ```
154
+ 2. **Install Dependencies**:
155
+ ```bash
156
+ uv --with-editable . maturin develop --uv -r
157
+ ```
158
+ 3. **Run Tests**:
159
+ ```bash
160
+ make test
161
+ ```
162
+
163
+ ## Contributing
164
+
165
+ Contributions are welcome! Follow these steps:
166
+ 1. Fork the repository.
167
+ 2. Create your feature branch (`git checkout -b feature/new-feature`).
168
+ 3. Commit your changes (`git commit -am 'Add new feature'`).
169
+ 4. Push to the branch (`git push origin feature/new-feature`).
170
+ 5. Create a new Pull Request.
171
+
172
+ ## License
173
+
174
+ Fabricatio is licensed under the MIT License. See [LICENSE](LICENSE) for details.
175
+
176
+ ## Acknowledgments
177
+
178
+ Special thanks to the contributors and maintainers of:
179
+ - [PyO3](https://github.com/PyO3/pyo3)
180
+ - [Maturin](https://github.com/PyO3/maturin)
181
+ - [Handlebars.rs](https://github.com/sunng87/handlebars-rust)
@@ -1,6 +1,6 @@
1
- fabricatio-0.2.7.dev3.dist-info/METADATA,sha256=6O8sm_fbzBC9kYdt9UKzf8ZoXEfFcLGWKHOgJMvC52Q,14236
2
- fabricatio-0.2.7.dev3.dist-info/WHEEL,sha256=jABKVkLC9kJr8mi_er5jOqpiQUjARSLXDUIIxDqsS50,96
3
- fabricatio-0.2.7.dev3.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
1
+ fabricatio-0.2.7.dev4.dist-info/METADATA,sha256=DshHoi8eegFUNjltQNJgm0SkKSGCLPYJj-oaBBlth9o,5259
2
+ fabricatio-0.2.7.dev4.dist-info/WHEEL,sha256=jABKVkLC9kJr8mi_er5jOqpiQUjARSLXDUIIxDqsS50,96
3
+ fabricatio-0.2.7.dev4.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
4
4
  fabricatio/actions/article.py,sha256=AgxNKIRLXF9T-TdrhLPE8NWmT8QZXz1QvFnouvuoRBc,7684
5
5
  fabricatio/actions/article_rag.py,sha256=PiOFxI6VTmLXm3BK-01g_KH1mTE9uOtnA-CwUjt16AU,1456
6
6
  fabricatio/actions/output.py,sha256=K7xsBH8MjXRH6JOy3ZO94KCQzX2jNrwPPK_rRXVkS0E,1161
@@ -20,11 +20,12 @@ fabricatio/fs/__init__.py,sha256=PCf0s_9KDjVfNw7AfPoJzGt3jMq4gJOfbcT4pb0D0ZY,588
20
20
  fabricatio/journal.py,sha256=stnEP88aUBA_GmU9gfTF2EZI8FS2OyMLGaMSTgK4QgA,476
21
21
  fabricatio/models/action.py,sha256=UlflniS__MMrUXglu_U3PDFAtKEjVsKEix17AT9oP3M,8769
22
22
  fabricatio/models/events.py,sha256=QvlnS8FEELg6KNabcJMeh2GV_y0ZBzKOPphcteKYWYU,4183
23
+ fabricatio/models/extra/article_base.py,sha256=9zkS89G3L9moc0iYNq9D7DCcv0K52jRQWjM1MUK__dg,8449
23
24
  fabricatio/models/extra/article_essence.py,sha256=DUESuK4CGgkRvIMoJCv4l8MNp5MawRYoNOtLCrFRPXY,9229
24
- fabricatio/models/extra/article_main.py,sha256=F6rhHMICErzvtRIEWdxS5AoY9thLhUUeDofoJbNF9ZI,13984
25
- fabricatio/models/extra/article_outline.py,sha256=0t-aI3OtY1O1_dhwDDm1y4kUdqoh4bmQ8voNe6MDU4w,12452
26
- fabricatio/models/extra/article_proposal.py,sha256=eXtomW88urP9M4aKbVNN9dct0GH-fBwYOM_Rcq3d7j4,1771
27
- fabricatio/models/generic.py,sha256=TXNPGeVOWJnCKJ6KZU8T-SWQ913woX4Xt1BLJ0x4V9M,16820
25
+ fabricatio/models/extra/article_main.py,sha256=yhgZvHWAgL-BJ-eolaXTqBzyWq340GfJucoTY_2CPzs,11342
26
+ fabricatio/models/extra/article_outline.py,sha256=83hFbCaUDuXn9K_0qcCXQOQ1NBmK-7305ChfKvhNXns,7404
27
+ fabricatio/models/extra/article_proposal.py,sha256=p0NPzqg9x6t65DZqdF52Z1P0JwP6kwo2_eP-NsXgifU,1720
28
+ fabricatio/models/generic.py,sha256=GVjcDnzwjKElCZoEVciS7X8SSPjqEp_6M2fLiyAkwNo,17644
28
29
  fabricatio/models/kwargs_types.py,sha256=chJ-rHaeBVRUPuORHuGR3DdNxxTUrotz0eflPEh4l4w,5474
29
30
  fabricatio/models/role.py,sha256=mmQbJ6GKr2Gx3wtjEz8d-vYoXs09ffcEkT_eCXaDd3E,2782
30
31
  fabricatio/models/task.py,sha256=8NaR7ojQWyM740EDTqt9stwHKdrD6axCRpLKo0QzS-I,10492
@@ -41,6 +42,6 @@ fabricatio/workflows/rag.py,sha256=-YYp2tlE9Vtfgpg6ROpu6QVO8j8yVSPa6yDzlN3qVxs,5
41
42
  fabricatio/_rust.pyi,sha256=dGTGV7viu3YAGl1cRKIWrdHPc1hlwk3_hbaDaswxdVo,3831
42
43
  fabricatio/_rust_instances.py,sha256=2GwF8aVfYNemRI2feBzH1CZfBGno-XJJE5imJokGEYw,314
43
44
  fabricatio/__init__.py,sha256=SzBYsRhZeL77jLtfJEjmoHOSwHwUGyvMATX6xfndLDM,1135
44
- fabricatio/_rust.cp312-win_amd64.pyd,sha256=JqLbZHAa0qBcJyWzAWC4Px5MTCxV9VN_BMsfm4saGus,1840128
45
- fabricatio-0.2.7.dev3.data/scripts/tdown.exe,sha256=2sqdWL-XEloL8IsQRQ9wZ_4O0aaLO02jgeb8KWCLgdM,3402752
46
- fabricatio-0.2.7.dev3.dist-info/RECORD,,
45
+ fabricatio/_rust.cp312-win_amd64.pyd,sha256=opsv_4PpUw06LsJqoKuuTr8aQ3NdAMxB1Ep2RrQqaLc,1835520
46
+ fabricatio-0.2.7.dev4.data/scripts/tdown.exe,sha256=eEr8wBSNDWdntRBBly7YQr1DnA0ru8NAgAmfMPw7SdU,3402240
47
+ fabricatio-0.2.7.dev4.dist-info/RECORD,,
@@ -1,436 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: fabricatio
3
- Version: 0.2.7.dev3
4
- Classifier: License :: OSI Approved :: MIT License
5
- Classifier: Programming Language :: Rust
6
- Classifier: Programming Language :: Python :: 3.12
7
- Classifier: Programming Language :: Python :: Implementation :: CPython
8
- Classifier: Framework :: AsyncIO
9
- Classifier: Framework :: Pydantic :: 2
10
- Classifier: Typing :: Typed
11
- Requires-Dist: appdirs>=1.4.4
12
- Requires-Dist: asyncio>=3.4.3
13
- Requires-Dist: asyncstdlib>=3.13.0
14
- Requires-Dist: json-repair>=0.39.1
15
- Requires-Dist: litellm>=1.60.0
16
- Requires-Dist: loguru>=0.7.3
17
- Requires-Dist: magika>=0.5.1
18
- Requires-Dist: more-itertools>=10.6.0
19
- Requires-Dist: orjson>=3.10.15
20
- Requires-Dist: pydantic>=2.10.6
21
- Requires-Dist: pydantic-settings>=2.7.1
22
- Requires-Dist: pymitter>=1.0.0
23
- Requires-Dist: questionary>=2.1.0
24
- Requires-Dist: regex>=2024.11.6
25
- Requires-Dist: rich>=13.9.4
26
- Requires-Dist: pymilvus>=2.5.4 ; extra == 'rag'
27
- Requires-Dist: fabricatio[calc,plot,rag] ; extra == 'full'
28
- Requires-Dist: sympy>=1.13.3 ; extra == 'calc'
29
- Requires-Dist: matplotlib>=3.10.1 ; extra == 'plot'
30
- Provides-Extra: rag
31
- Provides-Extra: full
32
- Provides-Extra: calc
33
- Provides-Extra: plot
34
- License-File: LICENSE
35
- Summary: A LLM multi-agent framework.
36
- Keywords: ai,agents,multi-agent,llm,pyo3
37
- Author-email: Whth <zettainspector@foxmail.com>
38
- Requires-Python: >=3.12, <3.13
39
- Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
40
- Project-URL: Homepage, https://github.com/Whth/fabricatio
41
- Project-URL: Repository, https://github.com/Whth/fabricatio
42
- Project-URL: Issues, https://github.com/Whth/fabricatio/issues
43
-
44
- # Fabricatio
45
-
46
- ![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)
47
- ![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)
48
- ![Build Status](https://img.shields.io/badge/build-passing-brightgreen)
49
-
50
- ## Overview
51
-
52
- Fabricatio is a Python library designed for building LLM (Large Language Model) applications using an event-based agent structure. It integrates Rust for performance-critical tasks, utilizes Handlebars for templating, and employs PyO3 for Python bindings.
53
-
54
- ## Features
55
-
56
- - **Event-Based Architecture**: Utilizes an EventEmitter pattern for robust task management.
57
- - **LLM Integration**: Supports interactions with large language models for intelligent task processing.
58
- - **Templating Engine**: Uses Handlebars for dynamic content generation.
59
- - **Toolboxes**: Provides predefined toolboxes for common operations like file manipulation and arithmetic.
60
- - **Async Support**: Fully asynchronous for efficient execution.
61
- - **Extensible**: Easy to extend with custom actions, workflows, and tools.
62
-
63
- ## Installation
64
-
65
- ### Using UV (Recommended)
66
-
67
- To install Fabricatio using `uv` (a package manager for Python):
68
-
69
- ```bash
70
- # Install uv if not already installed
71
- pip install uv
72
-
73
- # Clone the repository
74
- git clone https://github.com/Whth/fabricatio.git
75
- cd fabricatio
76
-
77
- # Install the package in development mode with uv
78
- uv --with-editable . maturin develop --uv -r
79
- ```
80
-
81
- ### Building Distribution
82
-
83
- For production builds:
84
-
85
- ```bash
86
- # Build distribution packages
87
- make bdist
88
- ```
89
-
90
- This will generate distribution files in the `dist` directory.
91
-
92
- ## Usage
93
-
94
- ### Basic Example
95
-
96
- #### Simple Hello World Program
97
-
98
- ```python
99
- import asyncio
100
- from fabricatio import Action, Role, Task, logger, WorkFlow
101
- from typing import Any
102
-
103
- class Hello(Action):
104
- name: str = "hello"
105
- output_key: str = "task_output"
106
-
107
- async def _execute(self, task_input: Task[str], **_) -> Any:
108
- ret = "Hello fabricatio!"
109
- logger.info("executing talk action")
110
- return ret
111
-
112
- async def main() -> None:
113
- role = Role(
114
- name="talker",
115
- description="talker role",
116
- registry={Task.pending_label: WorkFlow(name="talk", steps=(Hello,))}
117
- )
118
-
119
- task = Task(name="say hello", goals="say hello", description="say hello to the world")
120
- result = await task.delegate()
121
- logger.success(f"Result: {result}")
122
-
123
- if __name__ == "__main__":
124
- asyncio.run(main())
125
- ```
126
-
127
- ### Advanced Examples
128
-
129
- #### Simple Chat
130
-
131
- Demonstrates a basic chat application.
132
-
133
- ```python
134
- """Simple chat example."""
135
- import asyncio
136
- from fabricatio import Action, Role, Task, WorkFlow, logger
137
- from fabricatio.models.events import Event
138
- from questionary import text
139
-
140
- class Talk(Action):
141
- """Action that says hello to the world."""
142
-
143
- output_key: str = "task_output"
144
-
145
- async def _execute(self, task_input: Task[str], **_) -> int:
146
- counter = 0
147
- try:
148
- while True:
149
- user_say = await text("User: ").ask_async()
150
- gpt_say = await self.aask(
151
- user_say,
152
- system_message=f"You have to answer to user obeying task assigned to you:\n{task_input.briefing}",
153
- )
154
- print(f"GPT: {gpt_say}") # noqa: T201
155
- counter += 1
156
- except KeyboardInterrupt:
157
- logger.info(f"executed talk action {counter} times")
158
- return counter
159
-
160
- async def main() -> None:
161
- """Main function."""
162
- role = Role(
163
- name="talker",
164
- description="talker role",
165
- registry={Event.instantiate_from("talk").push_wildcard().push("pending"): WorkFlow(name="talk", steps=(Talk,))},
166
- )
167
-
168
- task = await role.propose_task(
169
- "you have to act as a helpful assistant, answer to all user questions properly and patiently"
170
- )
171
- _ = await task.delegate("talk")
172
-
173
- if __name__ == "__main__":
174
- asyncio.run(main())
175
- ```
176
-
177
- #### Simple RAG
178
-
179
- Demonstrates Retrieval-Augmented Generation (RAG).
180
-
181
- ```python
182
- """Simple chat example."""
183
- import asyncio
184
- from fabricatio import RAG, Action, Role, Task, WorkFlow, logger
185
- from fabricatio.models.events import Event
186
- from questionary import text
187
-
188
- class Talk(Action, RAG):
189
- """Action that says hello to the world."""
190
-
191
- output_key: str = "task_output"
192
-
193
- async def _execute(self, task_input: Task[str], **_) -> int:
194
- counter = 0
195
-
196
- self.init_client().view("test_collection", create=True)
197
- await self.consume_string(
198
- [
199
- "Company policy clearly stipulates that all employees must arrive at the headquarters building located at 88 Jianguo Road, Chaoyang District, Beijing before 9 AM daily.",
200
- "According to the latest revised health and safety guidelines, employees must wear company-provided athletic gear when using the company gym facilities.",
201
- "Section 3.2.1 of the employee handbook states that pets are not allowed in the office area under any circumstances.",
202
- "To promote work efficiency, the company has quiet workspaces at 100 Century Avenue, Pudong New District, Shanghai, for employees who need high concentration for their work.",
203
- "According to the company's remote work policy, employees can apply for a maximum of 5 days of working from home per month, but must submit the application one week in advance.",
204
- "The company has strict regulations on overtime. Unless approved by direct supervisors, no form of work is allowed after 9 PM.",
205
- "Regarding the new regulations for business travel reimbursement, all traveling personnel must submit detailed expense reports within five working days after returning.",
206
- "Company address: 123 East Sports Road, Tianhe District, Guangzhou, Postal Code: 510620.",
207
- "Annual team building activities will be held in the second quarter of each year, usually at a resort within a two-hour drive from the Guangzhou headquarters.",
208
- "Employees who are late more than three times will receive a formal warning, which may affect their year-end performance evaluation.",
209
- ]
210
- )
211
- try:
212
- while True:
213
- user_say = await text("User: ").ask_async()
214
- if user_say is None:
215
- break
216
- gpt_say = await self.aask_retrieved(
217
- user_say,
218
- user_say,
219
- extra_system_message=f"You have to answer to user obeying task assigned to you:\n{task_input.briefing}",
220
- )
221
- print(f"GPT: {gpt_say}") # noqa: T201
222
- counter += 1
223
- except KeyboardInterrupt:
224
- logger.info(f"executed talk action {counter} times")
225
- return counter
226
-
227
- async def main() -> None:
228
- """Main function."""
229
- role = Role(
230
- name="talker",
231
- description="talker role but with rag",
232
- registry={Event.instantiate_from("talk").push_wildcard().push("pending"): WorkFlow(name="talk", steps=(Talk,))},
233
- )
234
-
235
- task = await role.propose_task(
236
- "you have to act as a helpful assistant, answer to all user questions properly and patiently"
237
- )
238
- _ = await task.delegate("talk")
239
-
240
- if __name__ == "__main__":
241
- asyncio.run(main())
242
- ```
243
-
244
- #### Extract Article
245
-
246
- Demonstrates extracting the essence of an article from a file.
247
-
248
- ```python
249
- """Example of proposing a task to a role."""
250
- import asyncio
251
- from typing import List
252
-
253
- from fabricatio import ArticleEssence, Event, ExtractArticleEssence, Role, Task, WorkFlow, logger
254
-
255
- async def main() -> None:
256
- """Main function."""
257
- role = Role(
258
- name="Researcher",
259
- description="Extract article essence",
260
- registry={
261
- Event.quick_instantiate("article"): WorkFlow(
262
- name="extract",
263
- steps=(ExtractArticleEssence(output_key="task_output"),),
264
- )
265
- },
266
- )
267
- task: Task[List[ArticleEssence]] = await role.propose_task(
268
- "Extract the essence of the article from the file at './7.md'"
269
- )
270
- ess = (await task.delegate("article")).pop()
271
- logger.success(f"Essence:\n{ess.display()}")
272
-
273
- if __name__ == "__main__":
274
- asyncio.run(main())
275
- ```
276
-
277
- #### Propose Task
278
-
279
- Demonstrates proposing a task to a role.
280
-
281
- ```python
282
- """Example of proposing a task to a role."""
283
- import asyncio
284
- from typing import Any
285
-
286
- from fabricatio import Action, Event, Role, Task, WorkFlow, logger
287
-
288
- class Talk(Action):
289
- """Action that says hello to the world."""
290
-
291
- output_key: str = "task_output"
292
-
293
- async def _execute(self, **_) -> Any:
294
- ret = "Hello fabricatio!"
295
- logger.info("executing talk action")
296
- return ret
297
-
298
- async def main() -> None:
299
- """Main function."""
300
- role = Role(
301
- name="talker",
302
- description="talker role",
303
- registry={Event.quick_instantiate("talk"): WorkFlow(name="talk", steps=(Talk,))},
304
- )
305
- logger.info(f"Task example:\n{Task.formated_json_schema()}")
306
- logger.info(f"proposed task: {await role.propose_task('write a rust clap cli that can download a html page')}")
307
-
308
- if __name__ == "__main__":
309
- asyncio.run(main())
310
- ```
311
-
312
- #### Review
313
-
314
- Demonstrates reviewing code.
315
-
316
- ```python
317
- """Example of review usage."""
318
- import asyncio
319
-
320
- from fabricatio import Role, logger
321
-
322
- async def main() -> None:
323
- """Main function."""
324
- role = Role(
325
- name="Reviewer",
326
- description="A role that reviews the code.",
327
- )
328
-
329
- code = await role.aask(
330
- "write a cli app using rust with clap which can generate a basic manifest of a standard rust project, output code only,no extra explanation"
331
- )
332
-
333
- logger.success(f"Code: \n{code}")
334
- res = await role.review_string(code, "If the cli app is of good design")
335
- logger.success(f"Review: \n{res.display()}")
336
- await res.supervisor_check()
337
- logger.success(f"Review: \n{res.display()}")
338
-
339
- if __name__ == "__main__":
340
- asyncio.run(main())
341
- ```
342
-
343
- #### Write Outline
344
-
345
- Demonstrates writing an outline for an article in Typst format.
346
-
347
- ```python
348
- """Example of using the library."""
349
- import asyncio
350
-
351
- from fabricatio import Event, Role, WriteOutlineWorkFlow, logger
352
-
353
- async def main() -> None:
354
- """Main function."""
355
- role = Role(
356
- name="Undergraduate Researcher",
357
- description="Write an outline for an article in typst format.",
358
- registry={Event.quick_instantiate(ns := "article"): WriteOutlineWorkFlow},
359
- )
360
-
361
- proposed_task = await role.propose_task(
362
- "You need to read the `./article_briefing.txt` file and write an outline for the article in typst format. The outline should be saved in the `./out.typ` file.",
363
- )
364
- path = await proposed_task.delegate(ns)
365
- logger.success(f"The outline is saved in:\n{path}")
366
-
367
- if __name__ == "__main__":
368
- asyncio.run(main())
369
- ```
370
-
371
- ## Configuration
372
-
373
- The configuration for Fabricatio is managed via environment variables or TOML files. The default configuration file (`config.toml`) can be overridden by specifying a custom path.
374
-
375
- Example `config.toml`:
376
-
377
- ```toml
378
- [llm]
379
- api_endpoint = "https://api.openai.com"
380
- api_key = "your_openai_api_key"
381
- timeout = 300
382
- max_retries = 3
383
- model = "gpt-3.5-turbo"
384
- temperature = 1.0
385
- stop_sign = ["\n\n\n", "User:"]
386
- top_p = 0.35
387
- generation_count = 1
388
- stream = false
389
- max_tokens = 8192
390
- ```
391
-
392
- ## Development Setup
393
-
394
- To set up a development environment for Fabricatio:
395
-
396
- 1. **Clone the Repository**:
397
- ```bash
398
- git clone https://github.com/Whth/fabricatio.git
399
- cd fabricatio
400
- ```
401
-
402
- 2. **Install Dependencies**:
403
- ```bash
404
- uv --with-editable . maturin develop --uv -r
405
- ```
406
-
407
- 3. **Run Tests**:
408
- ```bash
409
- make test
410
- ```
411
-
412
- 4. **Build Documentation**:
413
- ```bash
414
- make docs
415
- ```
416
-
417
- ## Contributing
418
-
419
- Contributions are welcome! Please follow these guidelines when contributing:
420
-
421
- 1. Fork the repository.
422
- 2. Create your feature branch (`git checkout -b feature/new-feature`).
423
- 3. Commit your changes (`git commit -am 'Add new feature'`).
424
- 4. Push to the branch (`git push origin feature/new-feature`).
425
- 5. Create a new Pull Request.
426
-
427
- ## License
428
-
429
- Fabricatio is licensed under the MIT License. See [LICENSE](LICENSE) for more details.
430
-
431
- ## Acknowledgments
432
-
433
- Special thanks to the contributors and maintainers of:
434
- - [PyO3](https://github.com/PyO3/pyo3)
435
- - [Maturin](https://github.com/PyO3/maturin)
436
- - [Handlebars.rs](https://github.com/sunng87/handlebars-rust)