fabricatio 0.2.1.dev0__cp313-cp313-win_amd64.whl → 0.3.14.dev5__cp313-cp313-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 +12 -20
- fabricatio/actions/__init__.py +1 -5
- fabricatio/actions/article.py +319 -0
- fabricatio/actions/article_rag.py +416 -0
- fabricatio/actions/fs.py +25 -0
- fabricatio/actions/output.py +248 -0
- fabricatio/actions/rag.py +96 -0
- fabricatio/actions/rules.py +83 -0
- fabricatio/capabilities/__init__.py +1 -0
- fabricatio/capabilities/advanced_judge.py +20 -0
- fabricatio/capabilities/advanced_rag.py +61 -0
- fabricatio/capabilities/censor.py +105 -0
- fabricatio/capabilities/check.py +212 -0
- fabricatio/capabilities/correct.py +228 -0
- fabricatio/capabilities/extract.py +74 -0
- fabricatio/capabilities/persist.py +103 -0
- fabricatio/capabilities/propose.py +65 -0
- fabricatio/capabilities/rag.py +263 -0
- fabricatio/capabilities/rating.py +404 -0
- fabricatio/capabilities/review.py +114 -0
- fabricatio/capabilities/task.py +113 -0
- fabricatio/decorators.py +251 -179
- fabricatio/{core.py → emitter.py} +31 -21
- fabricatio/fs/__init__.py +32 -2
- fabricatio/fs/curd.py +32 -9
- fabricatio/fs/readers.py +44 -7
- fabricatio/journal.py +3 -19
- fabricatio/models/action.py +185 -61
- fabricatio/models/adv_kwargs_types.py +63 -0
- fabricatio/models/extra/__init__.py +1 -0
- fabricatio/models/extra/advanced_judge.py +32 -0
- fabricatio/models/extra/aricle_rag.py +284 -0
- fabricatio/models/extra/article_base.py +422 -0
- fabricatio/models/extra/article_essence.py +101 -0
- fabricatio/models/extra/article_main.py +284 -0
- fabricatio/models/extra/article_outline.py +46 -0
- fabricatio/models/extra/article_proposal.py +52 -0
- fabricatio/models/extra/patches.py +20 -0
- fabricatio/models/extra/problem.py +165 -0
- fabricatio/models/extra/rag.py +98 -0
- fabricatio/models/extra/rule.py +52 -0
- fabricatio/models/generic.py +704 -36
- fabricatio/models/kwargs_types.py +112 -17
- fabricatio/models/role.py +74 -27
- fabricatio/models/task.py +94 -60
- fabricatio/models/tool.py +328 -188
- fabricatio/models/usages.py +791 -515
- fabricatio/parser.py +81 -60
- fabricatio/rust.cp313-win_amd64.pyd +0 -0
- fabricatio/rust.pyi +886 -0
- fabricatio/toolboxes/__init__.py +1 -3
- fabricatio/toolboxes/fs.py +17 -1
- fabricatio/utils.py +156 -0
- fabricatio/workflows/__init__.py +1 -0
- fabricatio/workflows/articles.py +24 -0
- fabricatio/workflows/rag.py +11 -0
- fabricatio-0.3.14.dev5.data/scripts/tdown.exe +0 -0
- fabricatio-0.3.14.dev5.data/scripts/ttm.exe +0 -0
- fabricatio-0.3.14.dev5.dist-info/METADATA +188 -0
- fabricatio-0.3.14.dev5.dist-info/RECORD +64 -0
- {fabricatio-0.2.1.dev0.dist-info → fabricatio-0.3.14.dev5.dist-info}/WHEEL +1 -1
- fabricatio/_rust.cp313-win_amd64.pyd +0 -0
- fabricatio/_rust.pyi +0 -53
- fabricatio/_rust_instances.py +0 -8
- fabricatio/actions/communication.py +0 -15
- fabricatio/actions/transmission.py +0 -23
- fabricatio/config.py +0 -263
- fabricatio/models/advanced.py +0 -128
- fabricatio/models/events.py +0 -82
- fabricatio/models/utils.py +0 -78
- fabricatio/toolboxes/task.py +0 -6
- fabricatio-0.2.1.dev0.data/scripts/tdown.exe +0 -0
- fabricatio-0.2.1.dev0.dist-info/METADATA +0 -420
- fabricatio-0.2.1.dev0.dist-info/RECORD +0 -35
- {fabricatio-0.2.1.dev0.dist-info → fabricatio-0.3.14.dev5.dist-info}/licenses/LICENSE +0 -0
fabricatio/config.py
DELETED
@@ -1,263 +0,0 @@
|
|
1
|
-
"""Configuration module for the Fabricatio application."""
|
2
|
-
|
3
|
-
from typing import List, Literal, Optional
|
4
|
-
|
5
|
-
from appdirs import user_config_dir
|
6
|
-
from pydantic import (
|
7
|
-
BaseModel,
|
8
|
-
ConfigDict,
|
9
|
-
DirectoryPath,
|
10
|
-
Field,
|
11
|
-
FilePath,
|
12
|
-
HttpUrl,
|
13
|
-
NonNegativeFloat,
|
14
|
-
PositiveInt,
|
15
|
-
SecretStr,
|
16
|
-
)
|
17
|
-
from pydantic_settings import (
|
18
|
-
BaseSettings,
|
19
|
-
DotEnvSettingsSource,
|
20
|
-
EnvSettingsSource,
|
21
|
-
PydanticBaseSettingsSource,
|
22
|
-
PyprojectTomlConfigSettingsSource,
|
23
|
-
SettingsConfigDict,
|
24
|
-
TomlConfigSettingsSource,
|
25
|
-
)
|
26
|
-
|
27
|
-
ROAMING_DIR = user_config_dir("fabricatio", "", roaming=True)
|
28
|
-
|
29
|
-
|
30
|
-
class LLMConfig(BaseModel):
|
31
|
-
"""LLM configuration class.
|
32
|
-
|
33
|
-
Attributes:
|
34
|
-
api_endpoint (HttpUrl): OpenAI API Endpoint.
|
35
|
-
api_key (SecretStr): OpenAI API key. Empty by default for security reasons, should be set before use.
|
36
|
-
timeout (PositiveInt): The timeout of the LLM model in seconds. Default is 300 seconds as per request.
|
37
|
-
max_retries (PositiveInt): The maximum number of retries. Default is 3 retries.
|
38
|
-
model (str): The LLM model name. Set to 'gpt-3.5-turbo' as per request.
|
39
|
-
temperature (NonNegativeFloat): The temperature of the LLM model. Controls randomness in generation. Set to 1.0 as per request.
|
40
|
-
stop_sign (str): The stop sign of the LLM model. No default stop sign specified.
|
41
|
-
top_p (NonNegativeFloat): The top p of the LLM model. Controls diversity via nucleus sampling. Set to 0.35 as per request.
|
42
|
-
generation_count (PositiveInt): The number of generations to generate. Default is 1.
|
43
|
-
stream (bool): Whether to stream the LLM model's response. Default is False.
|
44
|
-
max_tokens (PositiveInt): The maximum number of tokens to generate. Set to 8192 as per request.
|
45
|
-
"""
|
46
|
-
|
47
|
-
model_config = ConfigDict(use_attribute_docstrings=True)
|
48
|
-
api_endpoint: HttpUrl = Field(default=HttpUrl("https://api.openai.com"))
|
49
|
-
"""OpenAI API Endpoint."""
|
50
|
-
|
51
|
-
api_key: SecretStr = Field(default=SecretStr(""))
|
52
|
-
"""OpenAI API key. Empty by default for security reasons, should be set before use."""
|
53
|
-
|
54
|
-
timeout: PositiveInt = Field(default=300)
|
55
|
-
"""The timeout of the LLM model in seconds. Default is 300 seconds as per request."""
|
56
|
-
|
57
|
-
max_retries: PositiveInt = Field(default=3)
|
58
|
-
"""The maximum number of retries. Default is 3 retries."""
|
59
|
-
|
60
|
-
model: str = Field(default="gpt-3.5-turbo")
|
61
|
-
"""The LLM model name. Set to 'gpt-3.5-turbo' as per request."""
|
62
|
-
|
63
|
-
temperature: NonNegativeFloat = Field(default=1.0)
|
64
|
-
"""The temperature of the LLM model. Controls randomness in generation. Set to 1.0 as per request."""
|
65
|
-
|
66
|
-
stop_sign: str | List[str] = Field(default=("\n\n\n", "User:"))
|
67
|
-
"""The stop sign of the LLM model. No default stop sign specified."""
|
68
|
-
|
69
|
-
top_p: NonNegativeFloat = Field(default=0.35)
|
70
|
-
"""The top p of the LLM model. Controls diversity via nucleus sampling. Set to 0.35 as per request."""
|
71
|
-
|
72
|
-
generation_count: PositiveInt = Field(default=1)
|
73
|
-
"""The number of generations to generate. Default is 1."""
|
74
|
-
|
75
|
-
stream: bool = Field(default=False)
|
76
|
-
"""Whether to stream the LLM model's response. Default is False."""
|
77
|
-
|
78
|
-
max_tokens: PositiveInt = Field(default=8192)
|
79
|
-
"""The maximum number of tokens to generate. Set to 8192 as per request."""
|
80
|
-
|
81
|
-
|
82
|
-
class PymitterConfig(BaseModel):
|
83
|
-
"""Pymitter configuration class.
|
84
|
-
|
85
|
-
Attributes:
|
86
|
-
delimiter (str): The delimiter used to separate the event name into segments.
|
87
|
-
new_listener_event (bool): If set, a newListener event is emitted when a new listener is added.
|
88
|
-
max_listeners (int): The maximum number of listeners per event.
|
89
|
-
"""
|
90
|
-
|
91
|
-
model_config = ConfigDict(use_attribute_docstrings=True)
|
92
|
-
delimiter: str = Field(default="::", frozen=True)
|
93
|
-
"""The delimiter used to separate the event name into segments."""
|
94
|
-
|
95
|
-
new_listener_event: bool = Field(default=False, frozen=True)
|
96
|
-
"""If set, a newListener event is emitted when a new listener is added."""
|
97
|
-
|
98
|
-
max_listeners: int = Field(default=-1, frozen=True)
|
99
|
-
"""The maximum number of listeners per event."""
|
100
|
-
|
101
|
-
|
102
|
-
class DebugConfig(BaseModel):
|
103
|
-
"""Debug configuration class.
|
104
|
-
|
105
|
-
Attributes:
|
106
|
-
log_level (Literal["DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL"]): The log level of the application.
|
107
|
-
log_file (FilePath): The log file of the application.
|
108
|
-
"""
|
109
|
-
|
110
|
-
model_config = ConfigDict(use_attribute_docstrings=True)
|
111
|
-
|
112
|
-
log_level: Literal["DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL"] = Field(default="INFO")
|
113
|
-
"""The log level of the application."""
|
114
|
-
|
115
|
-
log_file: FilePath = Field(default=rf"{ROAMING_DIR}\fabricatio.log")
|
116
|
-
"""The log file of the application."""
|
117
|
-
|
118
|
-
rotation: int = Field(default=1)
|
119
|
-
"""The rotation of the log file. in weeks."""
|
120
|
-
|
121
|
-
retention: int = Field(default=2)
|
122
|
-
"""The retention of the log file. in weeks."""
|
123
|
-
|
124
|
-
streaming_visible: bool = Field(default=False)
|
125
|
-
"""Whether to print the llm output when streaming."""
|
126
|
-
|
127
|
-
|
128
|
-
class TemplateConfig(BaseModel):
|
129
|
-
"""Template configuration class."""
|
130
|
-
|
131
|
-
model_config = ConfigDict(use_attribute_docstrings=True)
|
132
|
-
template_dir: List[DirectoryPath] = Field(
|
133
|
-
default_factory=lambda: [DirectoryPath(r".\templates"), DirectoryPath(rf"{ROAMING_DIR}\templates")]
|
134
|
-
)
|
135
|
-
"""The directory containing the templates."""
|
136
|
-
active_loading: bool = Field(default=False)
|
137
|
-
"""Whether to enable active loading of templates."""
|
138
|
-
|
139
|
-
template_suffix: str = Field(default="hbs", frozen=True)
|
140
|
-
"""The suffix of the templates."""
|
141
|
-
|
142
|
-
propose_task_template: str = Field(default="propose_task")
|
143
|
-
"""The name of the propose task template which will be used to propose a task."""
|
144
|
-
|
145
|
-
draft_tool_usage_code_template: str = Field(default="draft_tool_usage_code")
|
146
|
-
"""The name of the draft tool usage code template which will be used to draft tool usage code."""
|
147
|
-
|
148
|
-
make_choice_template: str = Field(default="make_choice")
|
149
|
-
"""The name of the make choice template which will be used to make a choice."""
|
150
|
-
|
151
|
-
make_judgment_template: str = Field(default="make_judgment")
|
152
|
-
"""The name of the make judgment template which will be used to make a judgment."""
|
153
|
-
|
154
|
-
dependencies_template: str = Field(default="dependencies")
|
155
|
-
"""The name of the dependencies template which will be used to manage dependencies."""
|
156
|
-
|
157
|
-
task_briefing_template: str = Field(default="task_briefing")
|
158
|
-
"""The name of the task briefing template which will be used to brief a task."""
|
159
|
-
|
160
|
-
|
161
|
-
class MagikaConfig(BaseModel):
|
162
|
-
"""Magika configuration class."""
|
163
|
-
|
164
|
-
model_config = ConfigDict(use_attribute_docstrings=True)
|
165
|
-
model_dir: Optional[DirectoryPath] = Field(default=None)
|
166
|
-
"""The directory containing the models for magika."""
|
167
|
-
|
168
|
-
|
169
|
-
class GeneralConfig(BaseModel):
|
170
|
-
"""Global configuration class."""
|
171
|
-
|
172
|
-
model_config = ConfigDict(use_attribute_docstrings=True)
|
173
|
-
workspace: DirectoryPath = Field(default=DirectoryPath(r"."))
|
174
|
-
"""The workspace directory for the application."""
|
175
|
-
|
176
|
-
confirm_on_ops: bool = Field(default=True)
|
177
|
-
"""Whether to confirm on operations."""
|
178
|
-
|
179
|
-
|
180
|
-
class ToolBoxConfig(BaseModel):
|
181
|
-
"""Toolbox configuration class."""
|
182
|
-
|
183
|
-
model_config = ConfigDict(use_attribute_docstrings=True)
|
184
|
-
|
185
|
-
tool_module_name: str = Field(default="Toolbox")
|
186
|
-
"""The name of the module containing the toolbox."""
|
187
|
-
|
188
|
-
data_module_name: str = Field(default="Data")
|
189
|
-
"""The name of the module containing the data."""
|
190
|
-
|
191
|
-
|
192
|
-
class Settings(BaseSettings):
|
193
|
-
"""Application settings class.
|
194
|
-
|
195
|
-
Attributes:
|
196
|
-
llm (LLMConfig): LLM Configuration
|
197
|
-
debug (DebugConfig): Debug Configuration
|
198
|
-
pymitter (PymitterConfig): Pymitter Configuration
|
199
|
-
templates (TemplateConfig): Template Configuration
|
200
|
-
magika (MagikaConfig): Magika Configuration
|
201
|
-
"""
|
202
|
-
|
203
|
-
model_config = SettingsConfigDict(
|
204
|
-
env_prefix="FABRIK_",
|
205
|
-
env_nested_delimiter="__",
|
206
|
-
pyproject_toml_depth=1,
|
207
|
-
pyproject_toml_table_header=("tool", "fabricatio"),
|
208
|
-
toml_file=["fabricatio.toml", rf"{ROAMING_DIR}\fabricatio.toml"],
|
209
|
-
env_file=[".env", ".envrc"],
|
210
|
-
use_attribute_docstrings=True,
|
211
|
-
)
|
212
|
-
|
213
|
-
llm: LLMConfig = Field(default_factory=LLMConfig)
|
214
|
-
"""LLM Configuration"""
|
215
|
-
|
216
|
-
debug: DebugConfig = Field(default_factory=DebugConfig)
|
217
|
-
"""Debug Configuration"""
|
218
|
-
|
219
|
-
pymitter: PymitterConfig = Field(default_factory=PymitterConfig)
|
220
|
-
"""Pymitter Configuration"""
|
221
|
-
|
222
|
-
templates: TemplateConfig = Field(default_factory=TemplateConfig)
|
223
|
-
"""Template Configuration"""
|
224
|
-
|
225
|
-
magika: MagikaConfig = Field(default_factory=MagikaConfig)
|
226
|
-
"""Magika Configuration"""
|
227
|
-
|
228
|
-
general: GeneralConfig = Field(default_factory=GeneralConfig)
|
229
|
-
"""General Configuration"""
|
230
|
-
|
231
|
-
toolbox: ToolBoxConfig = Field(default_factory=ToolBoxConfig)
|
232
|
-
"""Toolbox Configuration"""
|
233
|
-
|
234
|
-
@classmethod
|
235
|
-
def settings_customise_sources(
|
236
|
-
cls,
|
237
|
-
settings_cls: type[BaseSettings],
|
238
|
-
init_settings: PydanticBaseSettingsSource,
|
239
|
-
env_settings: PydanticBaseSettingsSource,
|
240
|
-
dotenv_settings: PydanticBaseSettingsSource,
|
241
|
-
file_secret_settings: PydanticBaseSettingsSource,
|
242
|
-
) -> tuple[PydanticBaseSettingsSource, ...]:
|
243
|
-
"""Customize settings sources.
|
244
|
-
|
245
|
-
Args:
|
246
|
-
settings_cls (type[BaseSettings]): The settings class.
|
247
|
-
init_settings (PydanticBaseSettingsSource): Initial settings source.
|
248
|
-
env_settings (PydanticBaseSettingsSource): Environment settings source.
|
249
|
-
dotenv_settings (PydanticBaseSettingsSource): Dotenv settings source.
|
250
|
-
file_secret_settings (PydanticBaseSettingsSource): File secret settings source.
|
251
|
-
|
252
|
-
Returns:
|
253
|
-
tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources.
|
254
|
-
"""
|
255
|
-
return (
|
256
|
-
DotEnvSettingsSource(settings_cls),
|
257
|
-
EnvSettingsSource(settings_cls),
|
258
|
-
TomlConfigSettingsSource(settings_cls),
|
259
|
-
PyprojectTomlConfigSettingsSource(settings_cls),
|
260
|
-
)
|
261
|
-
|
262
|
-
|
263
|
-
configs: Settings = Settings()
|
fabricatio/models/advanced.py
DELETED
@@ -1,128 +0,0 @@
|
|
1
|
-
"""A module for advanced models and functionalities."""
|
2
|
-
|
3
|
-
from types import CodeType
|
4
|
-
from typing import Any, Dict, List, Optional, Tuple, Unpack
|
5
|
-
|
6
|
-
import orjson
|
7
|
-
from fabricatio._rust_instances import template_manager
|
8
|
-
from fabricatio.config import configs
|
9
|
-
from fabricatio.models.generic import WithBriefing
|
10
|
-
from fabricatio.models.kwargs_types import LLMKwargs
|
11
|
-
from fabricatio.models.task import Task
|
12
|
-
from fabricatio.models.tool import Tool, ToolExecutor
|
13
|
-
from fabricatio.models.usages import LLMUsage, ToolBoxUsage
|
14
|
-
from fabricatio.parser import JsonCapture, PythonCapture
|
15
|
-
from loguru import logger
|
16
|
-
from pydantic import PositiveInt, ValidationError
|
17
|
-
|
18
|
-
|
19
|
-
class ProposeTask(WithBriefing, LLMUsage):
|
20
|
-
"""A class that proposes a task based on a prompt."""
|
21
|
-
|
22
|
-
async def propose[T](
|
23
|
-
self,
|
24
|
-
prompt: str,
|
25
|
-
max_validations: PositiveInt = 2,
|
26
|
-
**kwargs: Unpack[LLMKwargs],
|
27
|
-
) -> Task[T]:
|
28
|
-
"""Asynchronously proposes a task based on a given prompt and parameters.
|
29
|
-
|
30
|
-
Parameters:
|
31
|
-
prompt: The prompt text for proposing a task, which is a string that must be provided.
|
32
|
-
max_validations: The maximum number of validations allowed, default is 2.
|
33
|
-
**kwargs: The keyword arguments for the LLM (Large Language Model) usage.
|
34
|
-
|
35
|
-
Returns:
|
36
|
-
A Task object based on the proposal result.
|
37
|
-
"""
|
38
|
-
if not prompt:
|
39
|
-
err = f"{self.name}: Prompt must be provided."
|
40
|
-
logger.error(err)
|
41
|
-
raise ValueError(err)
|
42
|
-
|
43
|
-
def _validate_json(response: str) -> None | Task:
|
44
|
-
try:
|
45
|
-
cap = JsonCapture.capture(response)
|
46
|
-
logger.debug(f"Response: \n{response}")
|
47
|
-
logger.info(f"Captured JSON: \n{cap}")
|
48
|
-
return Task.model_validate_json(cap)
|
49
|
-
except ValidationError as e:
|
50
|
-
logger.error(f"Failed to parse task from JSON: {e}")
|
51
|
-
return None
|
52
|
-
|
53
|
-
template_data = {"prompt": prompt, "json_example": Task.json_example()}
|
54
|
-
return await self.aask_validate(
|
55
|
-
question=template_manager.render_template(configs.templates.propose_task_template, template_data),
|
56
|
-
validator=_validate_json,
|
57
|
-
system_message=f"# your personal briefing: \n{self.briefing}",
|
58
|
-
max_validations=max_validations,
|
59
|
-
**kwargs,
|
60
|
-
)
|
61
|
-
|
62
|
-
|
63
|
-
class HandleTask(WithBriefing, ToolBoxUsage):
|
64
|
-
"""A class that handles a task based on a task object."""
|
65
|
-
|
66
|
-
async def draft_tool_usage_code(
|
67
|
-
self,
|
68
|
-
task: Task,
|
69
|
-
tools: List[Tool],
|
70
|
-
data: Dict[str, Any],
|
71
|
-
**kwargs: Unpack[LLMKwargs],
|
72
|
-
) -> Tuple[CodeType, List[str]]:
|
73
|
-
"""Asynchronously drafts the tool usage code for a task based on a given task object and tools."""
|
74
|
-
logger.info(f"Drafting tool usage code for task: {task.briefing}")
|
75
|
-
|
76
|
-
if not tools:
|
77
|
-
err = f"{self.name}: Tools must be provided to draft the tool usage code."
|
78
|
-
logger.error(err)
|
79
|
-
raise ValueError(err)
|
80
|
-
|
81
|
-
def _validator(response: str) -> Tuple[CodeType, List[str]] | None:
|
82
|
-
if (source := PythonCapture.convert_with(response, lambda resp: compile(resp, "<string>", "exec"))) and (
|
83
|
-
to_extract := JsonCapture.convert_with(response, orjson.loads)
|
84
|
-
):
|
85
|
-
return source, to_extract
|
86
|
-
|
87
|
-
return None
|
88
|
-
|
89
|
-
q = template_manager.render_template(
|
90
|
-
configs.templates.draft_tool_usage_code_template,
|
91
|
-
{
|
92
|
-
"data_module_name": configs.toolbox.data_module_name,
|
93
|
-
"tool_module_name": configs.toolbox.tool_module_name,
|
94
|
-
"task": task.briefing,
|
95
|
-
"deps": task.dependencies_prompt,
|
96
|
-
"tools": [{"name": t.name, "briefing": t.briefing} for t in tools],
|
97
|
-
"data": data,
|
98
|
-
},
|
99
|
-
)
|
100
|
-
logger.debug(f"Code Drafting Question: \n{q}")
|
101
|
-
return await self.aask_validate(
|
102
|
-
question=q,
|
103
|
-
validator=_validator,
|
104
|
-
system_message=f"# your personal briefing: \n{self.briefing}",
|
105
|
-
**kwargs,
|
106
|
-
)
|
107
|
-
|
108
|
-
async def handle_fin_grind(
|
109
|
-
self,
|
110
|
-
task: Task,
|
111
|
-
data: Dict[str, Any],
|
112
|
-
**kwargs: Unpack[LLMKwargs],
|
113
|
-
) -> Optional[Tuple]:
|
114
|
-
"""Asynchronously handles a task based on a given task object and parameters."""
|
115
|
-
logger.info(f"Handling task: \n{task.briefing}")
|
116
|
-
|
117
|
-
tools = await self.gather_tools(task)
|
118
|
-
logger.info(f"{self.name} have gathered {[t.name for t in tools]}")
|
119
|
-
|
120
|
-
if tools:
|
121
|
-
executor = ToolExecutor(candidates=tools, data=data)
|
122
|
-
code, to_extract = await self.draft_tool_usage_code(task, tools, data, **kwargs)
|
123
|
-
|
124
|
-
cxt = executor.execute(code)
|
125
|
-
if to_extract:
|
126
|
-
return tuple(cxt.get(k) for k in to_extract)
|
127
|
-
|
128
|
-
return None
|
fabricatio/models/events.py
DELETED
@@ -1,82 +0,0 @@
|
|
1
|
-
"""The module containing the Event class."""
|
2
|
-
|
3
|
-
from typing import List, Self, Union
|
4
|
-
|
5
|
-
from fabricatio.config import configs
|
6
|
-
from pydantic import BaseModel, ConfigDict, Field
|
7
|
-
|
8
|
-
type EventLike = Union[str, List[str], "Event"]
|
9
|
-
|
10
|
-
|
11
|
-
class Event(BaseModel):
|
12
|
-
"""A class representing an event."""
|
13
|
-
|
14
|
-
model_config = ConfigDict(use_attribute_docstrings=True)
|
15
|
-
|
16
|
-
segments: List[str] = Field(default_factory=list, frozen=True)
|
17
|
-
""" The segments of the namespaces."""
|
18
|
-
|
19
|
-
@classmethod
|
20
|
-
def instantiate_from(cls, event: EventLike) -> Self:
|
21
|
-
"""Create an Event instance from a string or list of strings or an Event instance.
|
22
|
-
|
23
|
-
Args:
|
24
|
-
event (EventLike): The event to instantiate from.
|
25
|
-
|
26
|
-
Returns:
|
27
|
-
Event: The Event instance.
|
28
|
-
"""
|
29
|
-
if isinstance(event, Event):
|
30
|
-
return event.clone()
|
31
|
-
if isinstance(event, str):
|
32
|
-
event = event.split(configs.pymitter.delimiter)
|
33
|
-
|
34
|
-
return cls(segments=event)
|
35
|
-
|
36
|
-
def derive(self, event: EventLike) -> Self:
|
37
|
-
"""Derive a new event from this event and another event or a string."""
|
38
|
-
return self.clone().concat(event)
|
39
|
-
|
40
|
-
def collapse(self) -> str:
|
41
|
-
"""Collapse the event into a string."""
|
42
|
-
return configs.pymitter.delimiter.join(self.segments)
|
43
|
-
|
44
|
-
def clone(self) -> Self:
|
45
|
-
"""Clone the event."""
|
46
|
-
return Event(segments=list(self.segments))
|
47
|
-
|
48
|
-
def push(self, segment: str) -> Self:
|
49
|
-
"""Push a segment to the event."""
|
50
|
-
if not segment:
|
51
|
-
raise ValueError("The segment must not be empty.")
|
52
|
-
if configs.pymitter.delimiter in segment:
|
53
|
-
raise ValueError("The segment must not contain the delimiter.")
|
54
|
-
|
55
|
-
self.segments.append(segment)
|
56
|
-
return self
|
57
|
-
|
58
|
-
def push_wildcard(self) -> Self:
|
59
|
-
"""Push a wildcard segment to the event."""
|
60
|
-
return self.push("*")
|
61
|
-
|
62
|
-
def pop(self) -> str:
|
63
|
-
"""Pop a segment from the event."""
|
64
|
-
return self.segments.pop()
|
65
|
-
|
66
|
-
def clear(self) -> Self:
|
67
|
-
"""Clear the event."""
|
68
|
-
self.segments.clear()
|
69
|
-
return self
|
70
|
-
|
71
|
-
def concat(self, event: EventLike) -> Self:
|
72
|
-
"""Concatenate another event to this event."""
|
73
|
-
self.segments.extend(Event.instantiate_from(event).segments)
|
74
|
-
return self
|
75
|
-
|
76
|
-
def __hash__(self) -> int:
|
77
|
-
"""Return the hash of the event, using the collapsed string."""
|
78
|
-
return hash(self.collapse())
|
79
|
-
|
80
|
-
def __eq__(self, other: str | List[str] | Self) -> bool:
|
81
|
-
"""Check if the event is equal to another event or a string."""
|
82
|
-
return self.collapse() == Event.instantiate_from(other).collapse()
|
fabricatio/models/utils.py
DELETED
@@ -1,78 +0,0 @@
|
|
1
|
-
"""A module containing utility classes for the models."""
|
2
|
-
|
3
|
-
from typing import Dict, List, Literal, Self
|
4
|
-
|
5
|
-
from pydantic import BaseModel, ConfigDict, Field
|
6
|
-
|
7
|
-
|
8
|
-
class Message(BaseModel):
|
9
|
-
"""A class representing a message."""
|
10
|
-
|
11
|
-
model_config = ConfigDict(use_attribute_docstrings=True)
|
12
|
-
role: Literal["user", "system", "assistant"] = Field(default="user")
|
13
|
-
"""
|
14
|
-
Who is sending the message.
|
15
|
-
"""
|
16
|
-
content: str = Field(default="")
|
17
|
-
"""
|
18
|
-
The content of the message.
|
19
|
-
"""
|
20
|
-
|
21
|
-
|
22
|
-
class Messages(list):
|
23
|
-
"""A list of messages."""
|
24
|
-
|
25
|
-
def add_message(self, role: Literal["user", "system", "assistant"], content: str) -> Self:
|
26
|
-
"""Adds a message to the list with the specified role and content.
|
27
|
-
|
28
|
-
Args:
|
29
|
-
role (Literal["user", "system", "assistant"]): The role of the message sender.
|
30
|
-
content (str): The content of the message.
|
31
|
-
|
32
|
-
Returns:
|
33
|
-
Self: The current instance of Messages to allow method chaining.
|
34
|
-
"""
|
35
|
-
if content:
|
36
|
-
self.append(Message(role=role, content=content))
|
37
|
-
return self
|
38
|
-
|
39
|
-
def add_user_message(self, content: str) -> Self:
|
40
|
-
"""Adds a user message to the list with the specified content.
|
41
|
-
|
42
|
-
Args:
|
43
|
-
content (str): The content of the user message.
|
44
|
-
|
45
|
-
Returns:
|
46
|
-
Self: The current instance of Messages to allow method chaining.
|
47
|
-
"""
|
48
|
-
return self.add_message("user", content)
|
49
|
-
|
50
|
-
def add_system_message(self, content: str) -> Self:
|
51
|
-
"""Adds a system message to the list with the specified content.
|
52
|
-
|
53
|
-
Args:
|
54
|
-
content (str): The content of the system message.
|
55
|
-
|
56
|
-
Returns:
|
57
|
-
Self: The current instance of Messages to allow method chaining.
|
58
|
-
"""
|
59
|
-
return self.add_message("system", content)
|
60
|
-
|
61
|
-
def add_assistant_message(self, content: str) -> Self:
|
62
|
-
"""Adds an assistant message to the list with the specified content.
|
63
|
-
|
64
|
-
Args:
|
65
|
-
content (str): The content of the assistant message.
|
66
|
-
|
67
|
-
Returns:
|
68
|
-
Self: The current instance of Messages to allow method chaining.
|
69
|
-
"""
|
70
|
-
return self.add_message("assistant", content)
|
71
|
-
|
72
|
-
def as_list(self) -> List[Dict[str, str]]:
|
73
|
-
"""Converts the messages to a list of dictionaries.
|
74
|
-
|
75
|
-
Returns:
|
76
|
-
list[dict]: A list of dictionaries representing the messages.
|
77
|
-
"""
|
78
|
-
return [message.model_dump() for message in self]
|
fabricatio/toolboxes/task.py
DELETED
@@ -1,6 +0,0 @@
|
|
1
|
-
"""This module contains the toolbox for tasks management."""
|
2
|
-
|
3
|
-
from fabricatio.models.task import Task
|
4
|
-
from fabricatio.models.tool import ToolBox
|
5
|
-
|
6
|
-
task_toolbox = ToolBox(name="TaskToolBox", description="A toolbox for tasks management.").add_tool(Task.simple_task)
|
Binary file
|