fabricatio 0.2.8.dev3__cp312-cp312-win_amd64.whl → 0.2.9__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.
Files changed (48) hide show
  1. fabricatio/__init__.py +4 -11
  2. fabricatio/actions/__init__.py +1 -0
  3. fabricatio/actions/article.py +128 -165
  4. fabricatio/actions/article_rag.py +62 -46
  5. fabricatio/actions/output.py +60 -4
  6. fabricatio/actions/rag.py +2 -1
  7. fabricatio/actions/rules.py +72 -0
  8. fabricatio/capabilities/__init__.py +1 -0
  9. fabricatio/capabilities/censor.py +104 -0
  10. fabricatio/capabilities/check.py +148 -32
  11. fabricatio/capabilities/correct.py +162 -100
  12. fabricatio/capabilities/rag.py +5 -4
  13. fabricatio/capabilities/rating.py +109 -54
  14. fabricatio/capabilities/review.py +1 -1
  15. fabricatio/capabilities/task.py +2 -1
  16. fabricatio/config.py +14 -6
  17. fabricatio/fs/readers.py +20 -1
  18. fabricatio/models/action.py +63 -41
  19. fabricatio/models/adv_kwargs_types.py +25 -0
  20. fabricatio/models/extra/__init__.py +1 -0
  21. fabricatio/models/extra/advanced_judge.py +7 -4
  22. fabricatio/models/extra/article_base.py +125 -79
  23. fabricatio/models/extra/article_main.py +101 -19
  24. fabricatio/models/extra/article_outline.py +2 -3
  25. fabricatio/models/extra/article_proposal.py +15 -14
  26. fabricatio/models/extra/patches.py +20 -0
  27. fabricatio/models/extra/problem.py +64 -23
  28. fabricatio/models/extra/rule.py +39 -10
  29. fabricatio/models/generic.py +405 -75
  30. fabricatio/models/kwargs_types.py +23 -17
  31. fabricatio/models/task.py +1 -1
  32. fabricatio/models/tool.py +149 -14
  33. fabricatio/models/usages.py +55 -56
  34. fabricatio/parser.py +12 -13
  35. fabricatio/rust.cp312-win_amd64.pyd +0 -0
  36. fabricatio/{_rust.pyi → rust.pyi} +42 -4
  37. fabricatio/{_rust_instances.py → rust_instances.py} +1 -1
  38. fabricatio/utils.py +5 -5
  39. fabricatio/workflows/__init__.py +1 -0
  40. fabricatio/workflows/articles.py +3 -5
  41. fabricatio-0.2.9.data/scripts/tdown.exe +0 -0
  42. {fabricatio-0.2.8.dev3.dist-info → fabricatio-0.2.9.dist-info}/METADATA +1 -1
  43. fabricatio-0.2.9.dist-info/RECORD +61 -0
  44. fabricatio/_rust.cp312-win_amd64.pyd +0 -0
  45. fabricatio-0.2.8.dev3.data/scripts/tdown.exe +0 -0
  46. fabricatio-0.2.8.dev3.dist-info/RECORD +0 -53
  47. {fabricatio-0.2.8.dev3.dist-info → fabricatio-0.2.9.dist-info}/WHEEL +0 -0
  48. {fabricatio-0.2.8.dev3.dist-info → fabricatio-0.2.9.dist-info}/licenses/LICENSE +0 -0
@@ -1,7 +1,7 @@
1
1
  """This module contains the types for the keyword arguments of the methods in the models module."""
2
2
 
3
3
  from importlib.util import find_spec
4
- from typing import Any, Dict, Required, TypedDict
4
+ from typing import Any, Dict, List, Optional, Required, TypedDict
5
5
 
6
6
  from litellm.caching.caching import CacheMode
7
7
  from litellm.types.caching import CachingSupportedCallTypes
@@ -95,11 +95,30 @@ class ValidateKwargs[T](GenerateKwargs, total=False):
95
95
  such as limiting the number of validation attempts.
96
96
  """
97
97
 
98
- default: T
98
+ default: Optional[T]
99
99
  max_validations: int
100
100
  co_extractor: GenerateKwargs
101
101
 
102
102
 
103
+ class CompositeScoreKwargs(ValidateKwargs[List[Dict[str, float]]], total=False):
104
+ """Arguments for composite score generation operations.
105
+
106
+ Extends GenerateKwargs with parameters for generating composite scores
107
+ based on specific criteria and weights.
108
+ """
109
+
110
+ topic: str
111
+ criteria: set[str]
112
+ weights: Dict[str, float]
113
+ manual: Dict[str, str]
114
+
115
+
116
+ class BestKwargs(CompositeScoreKwargs, total=False):
117
+ """Arguments for choose top-k operations."""
118
+
119
+ k: int
120
+
121
+
103
122
  class ReviewInnerKwargs[T](ValidateKwargs[T], total=False):
104
123
  """Arguments for content review operations."""
105
124
 
@@ -118,22 +137,9 @@ class ReviewKwargs[T](ReviewInnerKwargs[T], total=False):
118
137
  topic: Required[str]
119
138
 
120
139
 
121
- class CorrectKwargs[T](ReviewKwargs[T], total=False):
122
- """Arguments for content correction operations.
123
-
124
- Extends GenerateKwargs with parameters for correcting content based on
125
- specific criteria and templates.
126
- """
127
-
128
- reference: str
129
- supervisor_check: bool
130
-
131
-
132
- class CensoredCorrectKwargs[T](ReviewInnerKwargs[T], total=False):
133
- """Arguments for content censorship operations."""
134
-
140
+ class ReferencedKwargs[T](ValidateKwargs[T], total=False):
141
+ """Arguments for content review operations."""
135
142
  reference: str
136
- supervisor_check: bool
137
143
 
138
144
 
139
145
  # noinspection PyTypedDict
fabricatio/models/task.py CHANGED
@@ -6,13 +6,13 @@ It includes methods to manage the task's lifecycle, such as starting, finishing,
6
6
  from asyncio import Queue
7
7
  from typing import Any, List, Optional, Self
8
8
 
9
- from fabricatio._rust_instances import TEMPLATE_MANAGER
10
9
  from fabricatio.config import configs
11
10
  from fabricatio.core import env
12
11
  from fabricatio.journal import logger
13
12
  from fabricatio.models.events import Event, EventLike
14
13
  from fabricatio.models.generic import ProposedAble, WithBriefing, WithDependency
15
14
  from fabricatio.models.utils import TaskStatus
15
+ from fabricatio.rust_instances import TEMPLATE_MANAGER
16
16
  from pydantic import Field, PrivateAttr
17
17
 
18
18
 
fabricatio/models/tool.py CHANGED
@@ -1,4 +1,8 @@
1
- """A module for defining tools and toolboxes."""
1
+ """A module for defining tools and toolboxes.
2
+
3
+ This module provides classes for defining tools and toolboxes, which can be used to manage and execute callable functions
4
+ with additional functionalities such as logging, execution info, and briefing.
5
+ """
2
6
 
3
7
  from importlib.machinery import ModuleSpec
4
8
  from importlib.util import module_from_spec
@@ -14,7 +18,16 @@ from pydantic import BaseModel, ConfigDict, Field
14
18
 
15
19
 
16
20
  class Tool[**P, R](WithBriefing):
17
- """A class representing a tool with a callable source function."""
21
+ """A class representing a tool with a callable source function.
22
+
23
+ This class encapsulates a callable function (source) and provides methods to invoke it, log its execution, and generate
24
+ a brief description (briefing) of the tool.
25
+
26
+ Attributes:
27
+ name (str): The name of the tool.
28
+ description (str): The description of the tool.
29
+ source (Callable[P, R]): The source function of the tool.
30
+ """
18
31
 
19
32
  name: str = Field(default="")
20
33
  """The name of the tool."""
@@ -26,7 +39,16 @@ class Tool[**P, R](WithBriefing):
26
39
  """The source function of the tool."""
27
40
 
28
41
  def model_post_init(self, __context: Any) -> None:
29
- """Initialize the tool with a name and a source function."""
42
+ """Initialize the tool with a name and a source function.
43
+
44
+ This method sets the tool's name and description based on the source function's name and docstring.
45
+
46
+ Args:
47
+ __context (Any): Context passed during model initialization.
48
+
49
+ Raises:
50
+ RuntimeError: If the tool does not have a source function.
51
+ """
30
52
  self.name = self.name or self.source.__name__
31
53
 
32
54
  if not self.name:
@@ -36,7 +58,17 @@ class Tool[**P, R](WithBriefing):
36
58
  self.description = self.description.strip()
37
59
 
38
60
  def invoke(self, *args: P.args, **kwargs: P.kwargs) -> R:
39
- """Invoke the tool's source function with the provided arguments."""
61
+ """Invoke the tool's source function with the provided arguments.
62
+
63
+ This method logs the invocation of the tool and then calls the source function with the given arguments.
64
+
65
+ Args:
66
+ *args (P.args): Positional arguments to be passed to the source function.
67
+ **kwargs (P.kwargs): Keyword arguments to be passed to the source function.
68
+
69
+ Returns:
70
+ R: The result of the source function.
71
+ """
40
72
  logger.info(f"Invoking tool: {self.name}")
41
73
  return self.source(*args, **kwargs)
42
74
 
@@ -44,6 +76,8 @@ class Tool[**P, R](WithBriefing):
44
76
  def briefing(self) -> str:
45
77
  """Return a brief description of the tool.
46
78
 
79
+ This method generates a brief description of the tool, including its name, signature, and description.
80
+
47
81
  Returns:
48
82
  str: A brief description of the tool.
49
83
  """
@@ -59,7 +93,18 @@ def _desc_wrapper(desc: str) -> str:
59
93
 
60
94
 
61
95
  class ToolBox(WithBriefing):
62
- """A class representing a collection of tools."""
96
+ """A class representing a collection of tools.
97
+
98
+ This class manages a list of tools and provides methods to add tools, retrieve tools by name, and generate a brief
99
+ description (briefing) of the toolbox.
100
+
101
+ Attributes:
102
+ description (str): The description of the toolbox.
103
+ tools (List[Tool]): A list of tools in the toolbox.
104
+ """
105
+
106
+ description: str = ""
107
+ """The description of the toolbox."""
63
108
 
64
109
  tools: List[Tool] = Field(default_factory=list, frozen=True)
65
110
  """A list of tools in the toolbox."""
@@ -67,6 +112,8 @@ class ToolBox(WithBriefing):
67
112
  def collect_tool[**P, R](self, func: Callable[P, R]) -> Callable[P, R]:
68
113
  """Add a callable function to the toolbox as a tool.
69
114
 
115
+ This method wraps the function with logging execution info and adds it to the toolbox.
116
+
70
117
  Args:
71
118
  func (Callable[P, R]): The function to be added as a tool.
72
119
 
@@ -79,6 +126,8 @@ class ToolBox(WithBriefing):
79
126
  def add_tool[**P, R](self, func: Callable[P, R]) -> Self:
80
127
  """Add a callable function to the toolbox as a tool.
81
128
 
129
+ This method wraps the function with logging execution info and adds it to the toolbox.
130
+
82
131
  Args:
83
132
  func (Callable): The function to be added as a tool.
84
133
 
@@ -92,6 +141,8 @@ class ToolBox(WithBriefing):
92
141
  def briefing(self) -> str:
93
142
  """Return a brief description of the toolbox.
94
143
 
144
+ This method generates a brief description of the toolbox, including its name, description, and a list of tools.
145
+
95
146
  Returns:
96
147
  str: A brief description of the toolbox.
97
148
  """
@@ -102,6 +153,8 @@ class ToolBox(WithBriefing):
102
153
  def get[**P, R](self, name: str) -> Tool[P, R]:
103
154
  """Invoke a tool by name with the provided arguments.
104
155
 
156
+ This method retrieves a tool by its name from the toolbox.
157
+
105
158
  Args:
106
159
  name (str): The name of the tool to invoke.
107
160
 
@@ -120,13 +173,24 @@ class ToolBox(WithBriefing):
120
173
  return tool
121
174
 
122
175
  def __hash__(self) -> int:
123
- """Return a hash of the toolbox based on its briefing."""
176
+ """Return a hash of the toolbox based on its briefing.
177
+
178
+ Returns:
179
+ int: A hash value based on the toolbox's briefing.
180
+ """
124
181
  return hash(self.briefing)
125
182
 
126
183
 
127
184
  class ToolExecutor(BaseModel):
128
- """A class representing a tool executor with a sequence of tools to execute."""
185
+ """A class representing a tool executor with a sequence of tools to execute.
186
+
187
+ This class manages a sequence of tools and provides methods to inject tools and data into a module, execute the tools,
188
+ and retrieve specific outputs.
129
189
 
190
+ Attributes:
191
+ candidates (List[Tool]): The sequence of tools to execute.
192
+ data (Dict[str, Any]): The data that could be used when invoking the tools.
193
+ """
130
194
  model_config = ConfigDict(use_attribute_docstrings=True)
131
195
  candidates: List[Tool] = Field(default_factory=list, frozen=True)
132
196
  """The sequence of tools to execute."""
@@ -135,7 +199,16 @@ class ToolExecutor(BaseModel):
135
199
  """The data that could be used when invoking the tools."""
136
200
 
137
201
  def inject_tools[M: ModuleType](self, module: Optional[M] = None) -> M:
138
- """Inject the tools into the provided module or default."""
202
+ """Inject the tools into the provided module or default.
203
+
204
+ This method injects the tools into the provided module or creates a new module if none is provided.
205
+
206
+ Args:
207
+ module (Optional[M]): The module to inject tools into. If None, a new module is created.
208
+
209
+ Returns:
210
+ M: The module with injected tools.
211
+ """
139
212
  module = module or cast(
140
213
  "M", module_from_spec(spec=ModuleSpec(name=configs.toolbox.tool_module_name, loader=None))
141
214
  )
@@ -145,7 +218,16 @@ class ToolExecutor(BaseModel):
145
218
  return module
146
219
 
147
220
  def inject_data[M: ModuleType](self, module: Optional[M] = None) -> M:
148
- """Inject the data into the provided module or default."""
221
+ """Inject the data into the provided module or default.
222
+
223
+ This method injects the data into the provided module or creates a new module if none is provided.
224
+
225
+ Args:
226
+ module (Optional[M]): The module to inject data into. If None, a new module is created.
227
+
228
+ Returns:
229
+ M: The module with injected data.
230
+ """
149
231
  module = module or cast(
150
232
  'M', module_from_spec(spec=ModuleSpec(name=configs.toolbox.data_module_name, loader=None))
151
233
  )
@@ -155,7 +237,17 @@ class ToolExecutor(BaseModel):
155
237
  return module
156
238
 
157
239
  def execute[C: Dict[str, Any]](self, source: CodeType, cxt: Optional[C] = None) -> C:
158
- """Execute the sequence of tools with the provided context."""
240
+ """Execute the sequence of tools with the provided context.
241
+
242
+ This method executes the tools in the sequence with the provided context.
243
+
244
+ Args:
245
+ source (CodeType): The source code to execute.
246
+ cxt (Optional[C]): The context to execute the tools with. If None, an empty dictionary is used.
247
+
248
+ Returns:
249
+ C: The context after executing the tools.
250
+ """
159
251
  cxt = cxt or {}
160
252
 
161
253
  @use_temp_module([self.inject_data(), self.inject_tools()])
@@ -167,16 +259,49 @@ class ToolExecutor(BaseModel):
167
259
 
168
260
  @overload
169
261
  def take[C: Dict[str, Any]](self, keys: List[str], source: CodeType, cxt: Optional[C] = None) -> C:
170
- """Check the output of the tools with the provided context."""
262
+ """Check the output of the tools with the provided context.
263
+
264
+ This method executes the tools and retrieves specific keys from the context.
265
+
266
+ Args:
267
+ keys (List[str]): The keys to retrieve from the context.
268
+ source (CodeType): The source code to execute.
269
+ cxt (Optional[C]): The context to execute the tools with. If None, an empty dictionary is used.
270
+
271
+ Returns:
272
+ C: A dictionary containing the retrieved keys and their values.
273
+ """
171
274
  ...
172
275
 
173
276
  @overload
174
277
  def take[C: Dict[str, Any]](self, keys: str, source: CodeType, cxt: Optional[C] = None) -> Any:
175
- """Check the output of the tools with the provided context."""
278
+ """Check the output of the tools with the provided context.
279
+
280
+ This method executes the tools and retrieves a specific key from the context.
281
+
282
+ Args:
283
+ keys (str): The key to retrieve from the context.
284
+ source (CodeType): The source code to execute.
285
+ cxt (Optional[C]): The context to execute the tools with. If None, an empty dictionary is used.
286
+
287
+ Returns:
288
+ Any: The value of the retrieved key.
289
+ """
176
290
  ...
177
291
 
178
292
  def take[C: Dict[str, Any]](self, keys: List[str] | str, source: CodeType, cxt: Optional[C] = None) -> C | Any:
179
- """Check the output of the tools with the provided context."""
293
+ """Check the output of the tools with the provided context.
294
+
295
+ This method executes the tools and retrieves specific keys or a specific key from the context.
296
+
297
+ Args:
298
+ keys (List[str] | str): The keys to retrieve from the context. Can be a single key or a list of keys.
299
+ source (CodeType): The source code to execute.
300
+ cxt (Optional[C]): The context to execute the tools with. If None, an empty dictionary is used.
301
+
302
+ Returns:
303
+ C | Any: A dictionary containing the retrieved keys and their values, or the value of the retrieved key.
304
+ """
180
305
  cxt = self.execute(source, cxt)
181
306
  if isinstance(keys, str):
182
307
  return cxt[keys]
@@ -184,7 +309,17 @@ class ToolExecutor(BaseModel):
184
309
 
185
310
  @classmethod
186
311
  def from_recipe(cls, recipe: List[str], toolboxes: List[ToolBox]) -> Self:
187
- """Create a tool executor from a recipe and a list of toolboxes."""
312
+ """Create a tool executor from a recipe and a list of toolboxes.
313
+
314
+ This method creates a tool executor by retrieving tools from the provided toolboxes based on the recipe.
315
+
316
+ Args:
317
+ recipe (List[str]): The recipe specifying the names of the tools to be added.
318
+ toolboxes (List[ToolBox]): The list of toolboxes to retrieve tools from.
319
+
320
+ Returns:
321
+ Self: A new instance of the tool executor with the specified tools.
322
+ """
188
323
  tools = []
189
324
  while tool_name := recipe.pop(0):
190
325
  for toolbox in toolboxes:
@@ -2,11 +2,10 @@
2
2
 
3
3
  import traceback
4
4
  from asyncio import gather
5
- from typing import Callable, Dict, Iterable, List, Optional, Self, Sequence, Set, Type, Union, Unpack, overload
5
+ from typing import Callable, Dict, Iterable, List, Optional, Self, Sequence, Set, Union, Unpack, overload
6
6
 
7
7
  import asyncstdlib
8
8
  import litellm
9
- from fabricatio._rust_instances import TEMPLATE_MANAGER
10
9
  from fabricatio.config import configs
11
10
  from fabricatio.decorators import logging_exec_time
12
11
  from fabricatio.journal import logger
@@ -16,6 +15,7 @@ from fabricatio.models.task import Task
16
15
  from fabricatio.models.tool import Tool, ToolBox
17
16
  from fabricatio.models.utils import Messages
18
17
  from fabricatio.parser import GenericCapture, JsonCapture
18
+ from fabricatio.rust_instances import TEMPLATE_MANAGER
19
19
  from fabricatio.utils import ok
20
20
  from litellm import RateLimitError, Router, stream_chunk_builder # pyright: ignore [reportPrivateImportUsage]
21
21
  from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo
@@ -46,17 +46,24 @@ ROUTER = Router(
46
46
 
47
47
 
48
48
  class LLMUsage(ScopedConfig):
49
- """Class that manages LLM (Large Language Model) usage parameters and methods."""
49
+ """Class that manages LLM (Large Language Model) usage parameters and methods.
50
+
51
+ This class provides methods to deploy LLMs, query them for responses, and handle various configurations
52
+ related to LLM usage such as API keys, endpoints, and rate limits.
53
+ """
50
54
 
51
55
  def _deploy(self, deployment: Deployment) -> Router:
52
- """Add a deployment to the router."""
56
+ """Add a deployment to the router.
57
+
58
+ Args:
59
+ deployment (Deployment): The deployment to be added to the router.
60
+
61
+ Returns:
62
+ Router: The updated router with the added deployment.
63
+ """
53
64
  self._added_deployment = ROUTER.upsert_deployment(deployment)
54
65
  return ROUTER
55
66
 
56
- @classmethod
57
- def _scoped_model(cls) -> Type["LLMUsage"]:
58
- return LLMUsage
59
-
60
67
  # noinspection PyTypeChecker,PydanticTypeChecker
61
68
  async def aquery(
62
69
  self,
@@ -123,7 +130,6 @@ class LLMUsage(ScopedConfig):
123
130
  question: str,
124
131
  system_message: str = "",
125
132
  n: PositiveInt | None = None,
126
- stream_buffer_size: int = 50,
127
133
  **kwargs: Unpack[LLMKwargs],
128
134
  ) -> Sequence[TextChoices | Choices | StreamingChoices]:
129
135
  """Asynchronously invokes the language model with a question and optional system message.
@@ -132,11 +138,10 @@ class LLMUsage(ScopedConfig):
132
138
  question (str): The question to ask the model.
133
139
  system_message (str): The system message to provide context to the model. Defaults to an empty string.
134
140
  n (PositiveInt | None): The number of responses to generate. Defaults to the instance's `llm_generation_count` or the global configuration.
135
- stream_buffer_size (int): The buffer size for streaming responses. Defaults to 50.
136
141
  **kwargs (Unpack[LLMKwargs]): Additional keyword arguments for the LLM usage.
137
142
 
138
143
  Returns:
139
- List[Choices | StreamingChoices]: A list of choices or streaming choices from the model response.
144
+ Sequence[TextChoices | Choices | StreamingChoices]: A sequence of choices or streaming choices from the model response.
140
145
  """
141
146
  resp = await self.aquery(
142
147
  messages=Messages().add_system_message(system_message).add_user_message(question).as_list(),
@@ -148,16 +153,7 @@ class LLMUsage(ScopedConfig):
148
153
  if isinstance(resp, CustomStreamWrapper):
149
154
  if not configs.debug.streaming_visible and (pack := stream_chunk_builder(await asyncstdlib.list())):
150
155
  return pack.choices
151
- chunks = []
152
- buffer = ""
153
- async for chunk in resp:
154
- chunks.append(chunk)
155
- buffer += chunk.choices[0].delta.content or ""
156
- if len(buffer) > stream_buffer_size:
157
- print(buffer, end="") # noqa: T201
158
- buffer = ""
159
- print(buffer) # noqa: T201
160
- if pack := stream_chunk_builder(chunks):
156
+ if pack := stream_chunk_builder(await asyncstdlib.list(resp)):
161
157
  return pack.choices
162
158
  logger.critical(err := f"Unexpected response type: {type(resp)}")
163
159
  raise ValueError(err)
@@ -288,27 +284,26 @@ class LLMUsage(ScopedConfig):
288
284
  """Asynchronously asks a question and validates the response using a given validator.
289
285
 
290
286
  Args:
291
- question (str): The question to ask.
287
+ question (str | List[str]): The question to ask.
292
288
  validator (Callable[[str], T | None]): A function to validate the response.
293
289
  default (T | None): Default value to return if validation fails. Defaults to None.
294
- max_validations (PositiveInt): Maximum number of validation attempts. Defaults to 2.
290
+ max_validations (PositiveInt): Maximum number of validation attempts. Defaults to 3.
295
291
  co_extractor (Optional[GenerateKwargs]): Keyword arguments for the co-extractor, if provided will enable co-extraction.
296
- **kwargs (Unpack[LLMKwargs]): Additional keyword arguments for the LLM usage.
292
+ **kwargs (Unpack[GenerateKwargs]): Additional keyword arguments for the LLM usage.
297
293
 
298
294
  Returns:
299
- T: The validated response.
300
-
295
+ Optional[T] | List[Optional[T]] | List[T] | T: The validated response.
301
296
  """
302
297
 
303
298
  async def _inner(q: str) -> Optional[T]:
304
299
  for lap in range(max_validations):
305
300
  try:
306
- if (
307
- (response := await self.aask(question=q, **kwargs))
308
- or (
309
- co_extractor
310
- and (
311
- response := await self.aask(
301
+ if ((validated := validator(response := await self.aask(question=q, **kwargs))) is not None) or (
302
+ co_extractor is not None
303
+ and logger.debug("Co-extraction is enabled.") is None
304
+ and (
305
+ validated := validator(
306
+ response:=await self.aask(
312
307
  question=(
313
308
  TEMPLATE_MANAGER.render_template(
314
309
  configs.templates.co_validation_template,
@@ -319,17 +314,19 @@ class LLMUsage(ScopedConfig):
319
314
  )
320
315
  )
321
316
  )
322
- ) and (validated := validator(response)):
317
+ is not None
318
+ ):
323
319
  logger.debug(f"Successfully validated the response at {lap}th attempt.")
324
320
  return validated
325
321
 
326
322
  except RateLimitError as e:
327
- logger.warning(f"Rate limit error: {e}")
323
+ logger.warning(f"Rate limit error:\n{e}")
328
324
  continue
329
325
  except Exception as e: # noqa: BLE001
330
- logger.error(f"Error during validation: \n{e}")
326
+ logger.error(f"Error during validation:\n{e}")
331
327
  logger.debug(traceback.format_exc())
332
328
  break
329
+ logger.error(f"Failed to validate the response at {lap}th attempt:\n{response}")
333
330
  if not kwargs.get("no_cache"):
334
331
  kwargs["no_cache"] = True
335
332
  logger.debug("Closed the cache for the next attempt")
@@ -350,7 +347,7 @@ class LLMUsage(ScopedConfig):
350
347
  **kwargs (Unpack[ValidateKwargs]): Additional keyword arguments for the LLM usage.
351
348
 
352
349
  Returns:
353
- List[str]: The validated response as a list of strings.
350
+ Optional[List[str]]: The validated response as a list of strings.
354
351
  """
355
352
  return await self.aask_validate(
356
353
  TEMPLATE_MANAGER.render_template(
@@ -361,7 +358,6 @@ class LLMUsage(ScopedConfig):
361
358
  **kwargs,
362
359
  )
363
360
 
364
-
365
361
  async def apathstr(self, requirement: str, **kwargs: Unpack[ChooseKwargs[List[str]]]) -> Optional[List[str]]:
366
362
  """Asynchronously generates a list of strings based on a given requirement.
367
363
 
@@ -370,7 +366,7 @@ class LLMUsage(ScopedConfig):
370
366
  **kwargs (Unpack[ChooseKwargs]): Additional keyword arguments for the LLM usage.
371
367
 
372
368
  Returns:
373
- List[str]: The validated response as a list of strings.
369
+ Optional[List[str]]: The validated response as a list of strings.
374
370
  """
375
371
  return await self.alist_str(
376
372
  TEMPLATE_MANAGER.render_template(
@@ -388,7 +384,7 @@ class LLMUsage(ScopedConfig):
388
384
  **kwargs (Unpack[ValidateKwargs]): Additional keyword arguments for the LLM usage.
389
385
 
390
386
  Returns:
391
- str: The validated response as a single string.
387
+ Optional[str]: The validated response as a single string.
392
388
  """
393
389
  if paths := await self.apathstr(
394
390
  requirement,
@@ -407,7 +403,7 @@ class LLMUsage(ScopedConfig):
407
403
  **kwargs (Unpack[GenerateKwargs]): Additional keyword arguments for the LLM usage.
408
404
 
409
405
  Returns:
410
- str: The generated string.
406
+ Optional[str]: The generated string.
411
407
  """
412
408
  return await self.aask_validate( # pyright: ignore [reportReturnType]
413
409
  TEMPLATE_MANAGER.render_template(
@@ -434,12 +430,7 @@ class LLMUsage(ScopedConfig):
434
430
  **kwargs (Unpack[ValidateKwargs]): Additional keyword arguments for the LLM usage.
435
431
 
436
432
  Returns:
437
- List[T]: The final validated selection result list, with element types matching the input `choices`.
438
-
439
- Important:
440
- - Uses a template engine to generate structured prompts.
441
- - Ensures response compliance through JSON parsing and format validation.
442
- - Relies on `aask_validate` to implement retry mechanisms with validation.
433
+ Optional[List[T]]: The final validated selection result list, with element types matching the input `choices`.
443
434
  """
444
435
  if dup := duplicates_everseen(choices, key=lambda x: x.name):
445
436
  logger.error(err := f"Redundant choices: {dup}")
@@ -527,7 +518,10 @@ class LLMUsage(ScopedConfig):
527
518
 
528
519
 
529
520
  class EmbeddingUsage(LLMUsage):
530
- """A class representing the embedding model."""
521
+ """A class representing the embedding model.
522
+
523
+ This class extends LLMUsage and provides methods to generate embeddings for input text using various models.
524
+ """
531
525
 
532
526
  async def aembedding(
533
527
  self,
@@ -546,13 +540,12 @@ class EmbeddingUsage(LLMUsage):
546
540
  timeout (Optional[PositiveInt]): The timeout for the embedding request. Defaults to the instance's `llm_timeout` or the global configuration.
547
541
  caching (Optional[bool]): Whether to cache the embedding result. Defaults to False.
548
542
 
549
-
550
543
  Returns:
551
544
  EmbeddingResponse: The response containing the embeddings.
552
545
  """
553
546
  # check seq length
554
547
  max_len = self.embedding_max_sequence_length or configs.embedding.max_sequence_length
555
- if max_len and any(length:=(token_counter(text=t)) > max_len for t in input_text):
548
+ if max_len and any(length := (token_counter(text=t)) > max_len for t in input_text):
556
549
  logger.error(err := f"Input text exceeds maximum sequence length {max_len}, got {length}.")
557
550
  raise ValueError(err)
558
551
 
@@ -604,14 +597,21 @@ class EmbeddingUsage(LLMUsage):
604
597
 
605
598
 
606
599
  class ToolBoxUsage(LLMUsage):
607
- """A class representing the usage of tools in a task."""
600
+ """A class representing the usage of tools in a task.
601
+
602
+ This class extends LLMUsage and provides methods to manage and use toolboxes and tools within tasks.
603
+ """
608
604
 
609
605
  toolboxes: Set[ToolBox] = Field(default_factory=set)
610
606
  """A set of toolboxes used by the instance."""
611
607
 
612
608
  @property
613
609
  def available_toolbox_names(self) -> List[str]:
614
- """Return a list of available toolbox names."""
610
+ """Return a list of available toolbox names.
611
+
612
+ Returns:
613
+ List[str]: A list of names of the available toolboxes.
614
+ """
615
615
  return [toolbox.name for toolbox in self.toolboxes]
616
616
 
617
617
  async def choose_toolboxes(
@@ -623,11 +623,10 @@ class ToolBoxUsage(LLMUsage):
623
623
 
624
624
  Args:
625
625
  task (Task): The task for which to choose toolboxes.
626
- system_message (str): Custom system-level prompt, defaults to an empty string.
627
626
  **kwargs (Unpack[LLMKwargs]): Additional keyword arguments for the LLM usage.
628
627
 
629
628
  Returns:
630
- List[ToolBox]: The selected toolboxes.
629
+ Optional[List[ToolBox]]: The selected toolboxes.
631
630
  """
632
631
  if not self.toolboxes:
633
632
  logger.warning("No toolboxes available.")
@@ -652,7 +651,7 @@ class ToolBoxUsage(LLMUsage):
652
651
  **kwargs (Unpack[LLMKwargs]): Additional keyword arguments for the LLM usage.
653
652
 
654
653
  Returns:
655
- List[Tool]: The selected tools.
654
+ Optional[List[Tool]]: The selected tools.
656
655
  """
657
656
  if not toolbox.tools:
658
657
  logger.warning(f"No tools available in toolbox {toolbox.name}.")
@@ -714,7 +713,7 @@ class ToolBoxUsage(LLMUsage):
714
713
  """
715
714
  if isinstance(others, ToolBoxUsage):
716
715
  others = [others]
717
- for other in others:
716
+ for other in (x for x in others if isinstance(x, ToolBoxUsage)):
718
717
  self.toolboxes.update(other.toolboxes)
719
718
  return self
720
719
 
@@ -730,6 +729,6 @@ class ToolBoxUsage(LLMUsage):
730
729
  """
731
730
  if isinstance(others, ToolBoxUsage):
732
731
  others = [others]
733
- for other in others:
732
+ for other in (x for x in others if isinstance(x, ToolBoxUsage)):
734
733
  other.toolboxes.update(self.toolboxes)
735
734
  return self