fabricatio 0.2.0.dev17__cp312-cp312-win_amd64.whl → 0.2.0.dev18__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.
Binary file
@@ -1,14 +1,19 @@
1
1
  """A module for advanced models and functionalities."""
2
2
 
3
- from typing import List
3
+ from types import CodeType
4
+ from typing import List, Optional, Tuple, Unpack
4
5
 
6
+ import orjson
5
7
  from fabricatio._rust_instances import template_manager
8
+ from fabricatio.config import configs
6
9
  from fabricatio.models.generic import WithBriefing
10
+ from fabricatio.models.kwargs_types import LLMKwargs
7
11
  from fabricatio.models.task import Task
12
+ from fabricatio.models.tool import Tool, ToolExecutor
8
13
  from fabricatio.models.usages import LLMUsage, ToolBoxUsage
9
- from fabricatio.parser import JsonCapture
14
+ from fabricatio.parser import JsonCapture, PythonCapture
10
15
  from loguru import logger
11
- from pydantic import NonNegativeFloat, PositiveInt, ValidationError
16
+ from pydantic import PositiveInt, ValidationError
12
17
 
13
18
 
14
19
  class ProposeTask(LLMUsage, WithBriefing):
@@ -18,28 +23,14 @@ class ProposeTask(LLMUsage, WithBriefing):
18
23
  self,
19
24
  prompt: str,
20
25
  max_validations: PositiveInt = 2,
21
- model: str | None = None,
22
- temperature: NonNegativeFloat | None = None,
23
- stop: str | List[str] | None = None,
24
- top_p: NonNegativeFloat | None = None,
25
- max_tokens: PositiveInt | None = None,
26
- stream: bool | None = None,
27
- timeout: PositiveInt | None = None,
28
- max_retries: PositiveInt | None = None,
26
+ **kwargs: Unpack[LLMKwargs],
29
27
  ) -> Task:
30
28
  """Asynchronously proposes a task based on a given prompt and parameters.
31
29
 
32
30
  Parameters:
33
31
  prompt: The prompt text for proposing a task, which is a string that must be provided.
34
32
  max_validations: The maximum number of validations allowed, default is 2.
35
- model: The model to be used, default is None.
36
- temperature: The sampling temperature, default is None.
37
- stop: The stop sequence(s) for generation, default is None.
38
- top_p: The nucleus sampling parameter, default is None.
39
- max_tokens: The maximum number of tokens to be generated, default is None.
40
- stream: Whether to stream the output, default is None.
41
- timeout: The timeout for the operation, default is None.
42
- max_retries: The maximum number of retries for the operation, default is None.
33
+ **kwargs: The keyword arguments for the LLM (Large Language Model) usage.
43
34
 
44
35
  Returns:
45
36
  A Task object based on the proposal result.
@@ -65,32 +56,64 @@ class ProposeTask(LLMUsage, WithBriefing):
65
56
  validator=_validate_json,
66
57
  system_message=f"# your personal briefing: \n{self.briefing}",
67
58
  max_validations=max_validations,
68
- model=model,
69
- temperature=temperature,
70
- stop=stop,
71
- top_p=top_p,
72
- max_tokens=max_tokens,
73
- stream=stream,
74
- timeout=timeout,
75
- max_retries=max_retries,
59
+ **kwargs,
76
60
  )
77
61
 
78
62
 
79
63
  class HandleTask(WithBriefing, ToolBoxUsage):
80
64
  """A class that handles a task based on a task object."""
81
65
 
82
- async def handle[T](
66
+ async def draft_tool_usage_code(
83
67
  self,
84
- task: Task[T],
85
- max_validations: PositiveInt = 2,
86
- model: str | None = None,
87
- temperature: NonNegativeFloat | None = None,
88
- stop: str | List[str] | None = None,
89
- top_p: NonNegativeFloat | None = None,
90
- max_tokens: PositiveInt | None = None,
91
- stream: bool | None = None,
92
- timeout: PositiveInt | None = None,
93
- max_retries: PositiveInt | None = None,
94
- ) -> T:
68
+ task: Task,
69
+ tools: List[Tool],
70
+ **kwargs: Unpack[LLMKwargs],
71
+ ) -> Tuple[CodeType, List[str]]:
72
+ """Asynchronously drafts the tool usage code for a task based on a given task object and tools."""
73
+ logger.info(f"Drafting tool usage code for task: {task.briefing}")
74
+
75
+ if not tools:
76
+ err = f"{self.name}: Tools must be provided to draft the tool usage code."
77
+ logger.error(err)
78
+ raise ValueError(err)
79
+
80
+ def _validator(response: str) -> Tuple[CodeType, List[str]] | None:
81
+ if (source := PythonCapture.convert_with(response, lambda resp: compile(resp, "<string>", "exec"))) and (
82
+ to_extract := JsonCapture.convert_with(response, orjson.loads)
83
+ ):
84
+ return source, to_extract
85
+ return None
86
+
87
+ return await self.aask_validate(
88
+ question=template_manager.render_template(
89
+ "draft_tool_usage_code",
90
+ {
91
+ "tool_module_name": configs.toolbox.tool_module_name,
92
+ "task": task.briefing,
93
+ "tools": [tool.briefing for tool in tools],
94
+ },
95
+ ),
96
+ validator=_validator,
97
+ system_message=f"# your personal briefing: \n{self.briefing}",
98
+ **kwargs,
99
+ )
100
+
101
+ async def handle_fin_grind(
102
+ self,
103
+ task: Task,
104
+ **kwargs: Unpack[LLMKwargs],
105
+ ) -> Optional[Tuple]:
95
106
  """Asynchronously handles a task based on a given task object and parameters."""
96
- # TODO: Implement the handle method
107
+ logger.info(f"Handling task: {task.briefing}")
108
+
109
+ tools = await self.gather_tools(task)
110
+ logger.info(f"{self.name} have gathered {len(tools)} tools gathered")
111
+
112
+ if tools:
113
+ executor = ToolExecutor(execute_sequence=tools)
114
+ code, to_extract = await self.draft_tool_usage_code(task, tools, **kwargs)
115
+ cxt = await executor.execute(code)
116
+ if to_extract:
117
+ return tuple(cxt.get(k) for k in to_extract)
118
+
119
+ return None
@@ -0,0 +1,26 @@
1
+ """This module contains the types for the keyword arguments of the methods in the models module."""
2
+
3
+ from typing import List, NotRequired, TypedDict
4
+
5
+ from pydantic import NonNegativeFloat, NonNegativeInt, PositiveInt
6
+
7
+
8
+ class LLMKwargs(TypedDict):
9
+ """A type representing the keyword arguments for the LLM (Large Language Model) usage."""
10
+
11
+ model: NotRequired[str]
12
+ temperature: NotRequired[NonNegativeFloat]
13
+ stop: NotRequired[str | List[str]]
14
+ top_p: NotRequired[NonNegativeFloat]
15
+ max_tokens: NotRequired[PositiveInt]
16
+ stream: NotRequired[bool]
17
+ timeout: NotRequired[PositiveInt]
18
+ max_retries: NotRequired[PositiveInt]
19
+
20
+
21
+ class ChooseKwargs(LLMKwargs):
22
+ """A type representing the keyword arguments for the choose method."""
23
+
24
+ max_validations: NotRequired[PositiveInt]
25
+ system_message: NotRequired[str]
26
+ k: NotRequired[NonNegativeInt]
fabricatio/models/tool.py CHANGED
@@ -167,6 +167,6 @@ class ToolExecutor(BaseModel):
167
167
  tools = []
168
168
  while tool_name := recipe.pop(0):
169
169
  for toolbox in toolboxes:
170
- tools.append(toolbox.get(tool_name))
170
+ tools.append(toolbox[tool_name])
171
171
 
172
172
  return cls(execute_sequence=tools)
@@ -1,6 +1,6 @@
1
1
  """This module contains classes that manage the usage of language models and tools in tasks."""
2
2
 
3
- from typing import Callable, Dict, Iterable, List, NotRequired, Optional, Self, Set, TypedDict, Union, Unpack
3
+ from typing import Callable, Dict, Iterable, List, Optional, Self, Set, Union, Unpack
4
4
 
5
5
  import litellm
6
6
  import orjson
@@ -8,6 +8,7 @@ from fabricatio._rust_instances import template_manager
8
8
  from fabricatio.config import configs
9
9
  from fabricatio.journal import logger
10
10
  from fabricatio.models.generic import Base, WithBriefing
11
+ from fabricatio.models.kwargs_types import ChooseKwargs, LLMKwargs
11
12
  from fabricatio.models.task import Task
12
13
  from fabricatio.models.tool import Tool, ToolBox
13
14
  from fabricatio.models.utils import Messages
@@ -16,19 +17,6 @@ from litellm.types.utils import Choices, ModelResponse, StreamingChoices
16
17
  from pydantic import Field, HttpUrl, NonNegativeFloat, NonNegativeInt, PositiveInt, SecretStr
17
18
 
18
19
 
19
- class LLMKwargs(TypedDict):
20
- """A type representing the keyword arguments for the LLM (Large Language Model) usage."""
21
-
22
- model: NotRequired[str]
23
- temperature: NotRequired[NonNegativeFloat]
24
- stop: NotRequired[str | List[str]]
25
- top_p: NotRequired[NonNegativeFloat]
26
- max_tokens: NotRequired[PositiveInt]
27
- stream: NotRequired[bool]
28
- timeout: NotRequired[PositiveInt]
29
- max_retries: NotRequired[PositiveInt]
30
-
31
-
32
20
  class LLMUsage(Base):
33
21
  """Class that manages LLM (Large Language Model) usage parameters and methods."""
34
22
 
@@ -319,14 +307,6 @@ class LLMUsage(Base):
319
307
  setattr(other, attr_name, attr)
320
308
 
321
309
 
322
- class ChooseKwargs(LLMKwargs):
323
- """A type representing the keyword arguments for the choose method."""
324
-
325
- max_validations: NotRequired[PositiveInt]
326
- system_message: NotRequired[str]
327
- k: NotRequired[NonNegativeInt]
328
-
329
-
330
310
  class ToolBoxUsage(LLMUsage):
331
311
  """A class representing the usage of tools in a task."""
332
312
 
@@ -362,7 +342,7 @@ class ToolBoxUsage(LLMUsage):
362
342
  logger.warning("No toolboxes available.")
363
343
  return []
364
344
  return await self.achoose(
365
- instruction=task.briefing,
345
+ instruction=task.briefing, # TODO write a template to build a more robust instruction
366
346
  choices=list(self.toolboxes),
367
347
  k=k,
368
348
  max_validations=max_validations,
@@ -396,7 +376,7 @@ class ToolBoxUsage(LLMUsage):
396
376
  logger.warning(f"No tools available in toolbox {toolbox.name}.")
397
377
  return []
398
378
  return await self.achoose(
399
- instruction=task.briefing,
379
+ instruction=task.briefing, # TODO write a template to build a more robust instruction
400
380
  choices=toolbox.tools,
401
381
  k=k,
402
382
  max_validations=max_validations,
@@ -404,7 +384,7 @@ class ToolBoxUsage(LLMUsage):
404
384
  **kwargs,
405
385
  )
406
386
 
407
- async def gather_tools(
387
+ async def gather_tools_fine_grind(
408
388
  self,
409
389
  task: Task,
410
390
  box_choose_kwargs: Optional[ChooseKwargs] = None,
@@ -431,6 +411,18 @@ class ToolBoxUsage(LLMUsage):
431
411
  chosen_tools.extend(await self.choose_tools(task, toolbox, **tool_choose_kwargs))
432
412
  return chosen_tools
433
413
 
414
+ async def gather_tools(self, task: Task, **kwargs: Unpack[ChooseKwargs]) -> List[Tool]:
415
+ """Asynchronously gathers tools based on the provided task.
416
+
417
+ Args:
418
+ task (Task): The task for which to gather tools.
419
+ **kwargs (Unpack[ChooseKwargs]): Keyword arguments for choosing tools, such as `system_message`, `k`, `max_validations`, `model`, `temperature`, `stop`, `top_p`, `max_tokens`, `stream`, `timeout`, and `max_retries`.
420
+
421
+ Returns:
422
+ List[Tool]: A list of tools gathered based on the provided task.
423
+ """
424
+ return await self.gather_tools_fine_grind(task, kwargs, kwargs)
425
+
434
426
  def supply_tools_from[S: "ToolBoxUsage"](self, others: Union[S, Iterable[S]]) -> Self:
435
427
  """Supplies tools from other ToolUsage instances to this instance.
436
428
 
fabricatio/parser.py CHANGED
@@ -66,7 +66,7 @@ class Capture(BaseModel):
66
66
  return None
67
67
  try:
68
68
  return convertor(cap)
69
- except ValueError as e:
69
+ except (ValueError, SyntaxError) as e:
70
70
  logger.error(f"Failed to convert text using convertor: {convertor.__name__}, error: \n{e}")
71
71
  return None
72
72
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fabricatio
3
- Version: 0.2.0.dev17
3
+ Version: 0.2.0.dev18
4
4
  Classifier: License :: OSI Approved :: MIT License
5
5
  Classifier: Programming Language :: Rust
6
6
  Classifier: Programming Language :: Python :: 3.12
@@ -1,6 +1,6 @@
1
- fabricatio-0.2.0.dev17.dist-info/METADATA,sha256=1I6ycXWgI6ZRXlRrLYSubYm8tSkbfG8dqHYcHgCYIoc,6386
2
- fabricatio-0.2.0.dev17.dist-info/WHEEL,sha256=tpW5AN9B-9qsM9WW2FXG2r193YXiqexDadpKp0A2daI,96
3
- fabricatio-0.2.0.dev17.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
1
+ fabricatio-0.2.0.dev18.dist-info/METADATA,sha256=iasqYxUndNOxKQXzDKo53YvvgDA9l9QujIHcGx_8h30,6386
2
+ fabricatio-0.2.0.dev18.dist-info/WHEEL,sha256=tpW5AN9B-9qsM9WW2FXG2r193YXiqexDadpKp0A2daI,96
3
+ fabricatio-0.2.0.dev18.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
4
4
  fabricatio/actions/communication.py,sha256=wyc1DfhVwrwadhYG_auI9ykGXM0fwVYNwxpp91sSfiU,484
5
5
  fabricatio/actions/transmission.py,sha256=fU-xL8fDG3oRDD9x7Q94OU2Sb9G6xQfrj5IMlMYsgiM,1240
6
6
  fabricatio/actions/__init__.py,sha256=eFmFVPQvtNgFynIXBVr3eP-vWQDWCPng60YY5LXvZgg,115
@@ -12,15 +12,16 @@ fabricatio/fs/readers.py,sha256=lwAoOGafusBWyTZeN11oXJc224nPZrfafVHMmGSajkY,167
12
12
  fabricatio/fs/__init__.py,sha256=lWcKYg0v3mv2LnnSegOQaTtlVDODU0vtw_s6iKU5IqQ,122
13
13
  fabricatio/journal.py,sha256=z5K5waad9xmGr1hGrqSgFDRH3wiDQ5Oqfe0o98DaM-k,707
14
14
  fabricatio/models/action.py,sha256=YbfCZc5pWzfSsOATMaoPNwQH8uR7AOdjzqo289XVnrE,5301
15
- fabricatio/models/advanced.py,sha256=tJ93mrQiuIAD5lJMwEcQP1IXY2L2ihUTacyVmVaq9lA,3952
15
+ fabricatio/models/advanced.py,sha256=DTezOSrd9lni2Xjccu3BOhEdxGW3N0lsHnJIbtqLr34,4669
16
16
  fabricatio/models/events.py,sha256=p9uXXQNWmDcDvGuiCzeVudMC1cdwB0zSdf5FX8mEBnY,2704
17
17
  fabricatio/models/generic.py,sha256=bxH0TidKhDN8n8LOCHjPx3ViIclztHGao1N6YM1IGuQ,3425
18
+ fabricatio/models/kwargs_types.py,sha256=lSZAxOnhFdQwRkm-NrbJVMSyBbfdeuVNx807LvJpEOo,901
18
19
  fabricatio/models/role.py,sha256=O0hMOGpSXFLPx2A5XhRis7BtPebG-EgT9tY9P5-8p4Y,1417
19
20
  fabricatio/models/task.py,sha256=vVOGwnT-oaIIgjemEa0riMMz_CpWdCasie2NSIRvTKM,8188
20
- fabricatio/models/tool.py,sha256=pOBjvOsMF6bX9cPy1mnaljzWnWE31rV1gPtTQ0ZPwxc,6389
21
- fabricatio/models/usages.py,sha256=PHoXqRzu7ItF0Wts4xzgN8Ek_BVTqAHOcQZXxVmU_3s,20567
21
+ fabricatio/models/tool.py,sha256=mD0rlG7hpMxTd_pI6JfRxAVsqPaXGdw1VLThAlbrqFE,6385
22
+ fabricatio/models/usages.py,sha256=SHY8DHNO8poTFGRmKc4AWXvKzLXS540qw8SBWDCjSbg,20719
22
23
  fabricatio/models/utils.py,sha256=i_kpcQpct04mQFk1nbcVGV-pl1YThWu4Qk3wbewzKkc,2535
23
- fabricatio/parser.py,sha256=foEhrO_e-hhRhmABcttwdMyciyJx422MpNqCZOUx8bg,3278
24
+ fabricatio/parser.py,sha256=cpJtH711Lzl1JmwwJ1Jj3ZCzZxIblwrkl18QXLay2fE,3293
24
25
  fabricatio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
26
  fabricatio/toolboxes/arithmetic.py,sha256=WLqhY-Pikv11Y_0SGajwZx3WhsLNpHKf9drzAqOf_nY,1369
26
27
  fabricatio/toolboxes/fs.py,sha256=q5weqzAPv4RddC73blEeYYMTeXoIZjHuK55Us1yVlj0,455
@@ -29,6 +30,6 @@ fabricatio/toolboxes/__init__.py,sha256=xWObAUPasJjBw0pY9V_XTA9fTavdQkCZSYi7-CTf
29
30
  fabricatio/_rust.pyi,sha256=rZd_143JcGrLtRF-r5H1rErp8jQxH74n8ItA5FrohT0,1639
30
31
  fabricatio/_rust_instances.py,sha256=P5yKVZ9M9CC4ryI1G2rq4mHL96iu6DW_85RMTX8onpA,211
31
32
  fabricatio/__init__.py,sha256=C9r6OVyMBb8IqwERNUq8lKDLe4BqN7fiu-O4TsXZ5xU,913
32
- fabricatio/_rust.cp312-win_amd64.pyd,sha256=BaHm-8-2oT5dASWOXTsJxN17dnc3A2rRTh7RKILO8Cs,1132032
33
- fabricatio-0.2.0.dev17.data/scripts/tdown.exe,sha256=HsrHzB4dL8S5qCvg98dfRruvwEtwnUkPcmZcdX-efFw,3383808
34
- fabricatio-0.2.0.dev17.dist-info/RECORD,,
33
+ fabricatio/_rust.cp312-win_amd64.pyd,sha256=zcOGopnAj1DXcPzdR7LV8NYWoumcl5jBeIZ3zC9EwXg,1132032
34
+ fabricatio-0.2.0.dev18.data/scripts/tdown.exe,sha256=-wy8nh24fWDJ_M6NpAPqzQPJ2rIoStthYT1uFy4vCfU,3383808
35
+ fabricatio-0.2.0.dev18.dist-info/RECORD,,