fabricatio 0.2.6.dev7__cp39-cp39-win_amd64.whl → 0.2.7.dev0__cp39-cp39-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
@@ -24,10 +24,10 @@ class ExtractArticleEssence(Action):
24
24
  output_key: str = "article_essence"
25
25
  """The key of the output data."""
26
26
 
27
- async def _execute[P: PathLike | str](
27
+ async def _execute(
28
28
  self,
29
29
  task_input: Task,
30
- reader: Callable[[P], str] = lambda p: Path(p).read_text(encoding="utf-8"),
30
+ reader: Callable[[str], str] = lambda p: Path(p).read_text(encoding="utf-8"),
31
31
  **_,
32
32
  ) -> Optional[List[ArticleEssence]]:
33
33
  if not task_input.dependencies:
@@ -118,7 +118,7 @@ class CorrectOutline(Action):
118
118
  article_proposal: ArticleProposal,
119
119
 
120
120
  **_,
121
- ) -> Optional[str]:
121
+ ) -> ArticleOutline:
122
122
  ret = None
123
123
  while await confirm("Do you want to correct the outline?").ask_async():
124
124
  rprint(article_outline.finalized_dump())
@@ -126,3 +126,6 @@ class CorrectOutline(Action):
126
126
  ...
127
127
  ret = await self.correct_obj(article_outline, article_proposal.display(), topic=topic)
128
128
  return ret or article_outline
129
+
130
+
131
+
fabricatio/actions/rag.py CHANGED
@@ -3,8 +3,11 @@
3
3
  from typing import List, Optional
4
4
 
5
5
  from fabricatio.capabilities.rag import RAG
6
+ from fabricatio.journal import logger
6
7
  from fabricatio.models.action import Action
7
8
  from fabricatio.models.generic import PrepareVectorization
9
+ from fabricatio.models.task import Task
10
+ from questionary import text
8
11
 
9
12
 
10
13
  class InjectToDB(Action, RAG):
@@ -13,13 +16,58 @@ class InjectToDB(Action, RAG):
13
16
  output_key: str = "collection_name"
14
17
 
15
18
  async def _execute[T: PrepareVectorization](
16
- self, to_inject: T | List[T], collection_name: Optional[str] = "my_collection", **_
19
+ self, to_inject: Optional[T] | List[Optional[T]], collection_name: str = "my_collection",override_inject:bool=False, **_
17
20
  ) -> Optional[str]:
18
21
  if not isinstance(to_inject, list):
19
22
  to_inject = [to_inject]
20
-
23
+ logger.info(f"Injecting {len(to_inject)} items into the collection '{collection_name}'")
24
+ if override_inject:
25
+ self.check_client().client.drop_collection(collection_name)
21
26
  await self.view(collection_name, create=True).consume_string(
22
- [t.prepare_vectorization(self.embedding_max_sequence_length) for t in to_inject],
27
+ [
28
+ t.prepare_vectorization(self.embedding_max_sequence_length)
29
+ for t in to_inject
30
+ if isinstance(t, PrepareVectorization)
31
+ ],
23
32
  )
24
33
 
25
34
  return collection_name
35
+
36
+
37
+ class RAGTalk(Action, RAG):
38
+ """RAG-enabled conversational action that processes user questions based on a given task.
39
+
40
+ This action establishes an interactive conversation loop where it retrieves context-relevant
41
+ information to answer user queries according to the assigned task briefing.
42
+
43
+ Notes:
44
+ task_input: Task briefing that guides how to respond to user questions
45
+ collection_name: Name of the vector collection to use for retrieval (default: "my_collection")
46
+
47
+ Returns:
48
+ Number of conversation turns completed before termination
49
+ """
50
+
51
+ output_key: str = "task_output"
52
+
53
+ async def _execute(self, task_input: Task[str], **kwargs) -> int:
54
+ collection_name = kwargs.get("collection_name", "my_collection")
55
+ counter = 0
56
+
57
+ self.view(collection_name, create=True)
58
+
59
+ try:
60
+ while True:
61
+ user_say = await text("User: ").ask_async()
62
+ if user_say is None:
63
+ break
64
+ gpt_say = await self.aask_retrieved(
65
+ user_say,
66
+ user_say,
67
+ extra_system_message=f"You have to answer to user obeying task assigned to you:\n{task_input.briefing}",
68
+ )
69
+ print(f"GPT: {gpt_say}") # noqa: T201
70
+ counter += 1
71
+ except KeyboardInterrupt:
72
+ logger.info(f"executed talk action {counter} times")
73
+ return counter
@@ -55,7 +55,7 @@ class Correct(Review):
55
55
  if supervisor_check:
56
56
  await review_res.supervisor_check()
57
57
  if "default" in kwargs:
58
- cast(ReviewKwargs[None], kwargs)["default"] = None
58
+ cast('ReviewKwargs[None]', kwargs)["default"] = None
59
59
  return await self.propose(
60
60
  obj.__class__,
61
61
  TEMPLATE_MANAGER.render_template(
@@ -89,7 +89,7 @@ class Correct(Review):
89
89
  await review_res.supervisor_check()
90
90
 
91
91
  if "default" in kwargs:
92
- cast(ReviewKwargs[None], kwargs)["default"] = None
92
+ cast('ReviewKwargs[None]', kwargs)["default"] = None
93
93
  return await self.ageneric_string(
94
94
  TEMPLATE_MANAGER.render_template(
95
95
  configs.templates.correct_template, {"content": input_text, "review": review_res.display()}
@@ -63,10 +63,18 @@ class RAG(EmbeddingUsage):
63
63
  uri=milvus_uri or ok(self.milvus_uri or configs.rag.milvus_uri).unicode_string(),
64
64
  token=milvus_token
65
65
  or (token.get_secret_value() if (token := (self.milvus_token or configs.rag.milvus_token)) else ""),
66
- timeout=milvus_timeout or self.milvus_timeout,
66
+ timeout=milvus_timeout or self.milvus_timeout or configs.rag.milvus_timeout,
67
67
  )
68
68
  return self
69
69
 
70
+ def check_client(self, init: bool = True) -> Self:
71
+ """Check if the client is initialized, and if not, initialize it."""
72
+ if self._client is None and init:
73
+ return self.init_client()
74
+ if self._client is None and not init:
75
+ raise RuntimeError("Client is not initialized. Have you called `self.init_client()`?")
76
+ return self
77
+
70
78
  @overload
71
79
  async def pack(
72
80
  self, input_text: List[str], subject: Optional[str] = None, **kwargs: Unpack[EmbeddingKwargs]
@@ -111,8 +119,15 @@ class RAG(EmbeddingUsage):
111
119
  create (bool): Whether to create the collection if it does not exist.
112
120
  **kwargs (Unpack[CollectionConfigKwargs]): Additional keyword arguments for collection configuration.
113
121
  """
114
- if create and collection_name and self.client.has_collection(collection_name):
115
- kwargs["dimension"] = kwargs.get("dimension") or self.milvus_dimensions or configs.rag.milvus_dimensions
122
+ if create and collection_name and not self.check_client().client.has_collection(collection_name):
123
+ kwargs["dimension"] = ok(
124
+ kwargs.get("dimension")
125
+ or self.milvus_dimensions
126
+ or configs.rag.milvus_dimensions
127
+ or self.embedding_dimensions
128
+ or configs.embedding.dimensions,
129
+ "`dimension` is not set at any level.",
130
+ )
116
131
  self.client.create_collection(collection_name, auto_id=True, **kwargs)
117
132
  logger.info(f"Creating collection {collection_name}")
118
133
 
@@ -158,7 +173,7 @@ class RAG(EmbeddingUsage):
158
173
  else:
159
174
  raise TypeError(f"Expected MilvusData or list of MilvusData, got {type(data)}")
160
175
  c_name = collection_name or self.safe_target_collection
161
- self.client.insert(c_name, prepared_data)
176
+ self.check_client().client.insert(c_name, prepared_data)
162
177
 
163
178
  if flush:
164
179
  logger.debug(f"Flushing collection {c_name}")
@@ -219,7 +234,7 @@ class RAG(EmbeddingUsage):
219
234
  List[Dict[str, Any]] | List[Any]: The retrieved data.
220
235
  """
221
236
  # Step 1: Search for vectors
222
- search_results = self.client.search(
237
+ search_results = self.check_client().client.search(
223
238
  collection_name or self.safe_target_collection,
224
239
  vecs,
225
240
  search_params={"radius": similarity_threshold},
@@ -260,7 +275,7 @@ class RAG(EmbeddingUsage):
260
275
  if isinstance(query, str):
261
276
  query = [query]
262
277
  return cast(
263
- List[str],
278
+ 'List[str]',
264
279
  await self.afetch_document(
265
280
  vecs=(await self.vectorize(query)),
266
281
  desired_fields="text",
@@ -121,7 +121,7 @@ class ReviewResult[T](ProposedAble, Display):
121
121
  ReviewResult[K]: The current instance with updated reference type.
122
122
  """
123
123
  self._ref = ref # pyright: ignore [reportAttributeAccessIssue]
124
- return cast(ReviewResult[K], self)
124
+ return cast("ReviewResult[K]", self)
125
125
 
126
126
  def deref(self) -> T:
127
127
  """Retrieve the referenced object that was reviewed.
@@ -200,7 +200,7 @@ class Review(GiveRating, Propose):
200
200
  ReviewResult[Task[T]]: A review result containing identified problems and proposed solutions,
201
201
  with a reference to the original task.
202
202
  """
203
- return cast(ReviewResult[Task[T]], await self.review_obj(task, **kwargs))
203
+ return cast('ReviewResult[Task[T]]', await self.review_obj(task, **kwargs))
204
204
 
205
205
  async def review_string(
206
206
  self,
@@ -23,7 +23,7 @@ class ProposeTask(WithBriefing, Propose):
23
23
  self,
24
24
  prompt: str,
25
25
  **kwargs: Unpack[ValidateKwargs[Task[T]]],
26
- ) -> Task[T]:
26
+ ) -> Optional[Task[T]]:
27
27
  """Asynchronously proposes a task based on a given prompt and parameters.
28
28
 
29
29
  Parameters:
@@ -37,7 +37,7 @@ class ProposeTask(WithBriefing, Propose):
37
37
  logger.error(err := f"{self.name}: Prompt must be provided.")
38
38
  raise ValueError(err)
39
39
 
40
- return await self.propose(Task, prompt, **self.prepend(cast(Dict[str, Any], kwargs)))
40
+ return await self.propose(Task, prompt, **self.prepend(cast('Dict[str, Any]', kwargs)))
41
41
 
42
42
 
43
43
  class HandleTask(WithBriefing, ToolBoxUsage):
@@ -81,7 +81,7 @@ class HandleTask(WithBriefing, ToolBoxUsage):
81
81
  return await self.aask_validate(
82
82
  question=q,
83
83
  validator=_validator,
84
- **self.prepend(cast(Dict[str, Any], kwargs)),
84
+ **self.prepend(cast('Dict[str, Any]', kwargs)),
85
85
  )
86
86
 
87
87
  async def handle_fine_grind(
fabricatio/config.py CHANGED
@@ -277,7 +277,7 @@ class RagConfig(BaseModel):
277
277
 
278
278
  milvus_uri: Optional[HttpUrl] = Field(default=HttpUrl("http://localhost:19530"))
279
279
  """The URI of the Milvus server."""
280
- milvus_timeout: Optional[PositiveFloat] = Field(default=None)
280
+ milvus_timeout: Optional[PositiveFloat] = Field(default=30.0)
281
281
  """The timeout of the Milvus server."""
282
282
  milvus_token: Optional[SecretStr] = Field(default=None)
283
283
  """The token of the Milvus server."""
@@ -303,11 +303,13 @@ class RoutingConfig(BaseModel):
303
303
 
304
304
  model_config = ConfigDict(use_attribute_docstrings=True)
305
305
 
306
- allowed_fails: Optional[int] = 1
306
+ max_parallel_requests: Optional[int] = 60
307
+ """The maximum number of parallel requests. None means not checked."""
308
+ allowed_fails: Optional[int] = 3
307
309
  """The number of allowed fails before the routing is considered failed."""
308
310
  retry_after: int = 15
309
311
  """The time in seconds to wait before retrying the routing after a fail."""
310
- cooldown_time: Optional[int] = 120
312
+ cooldown_time: Optional[int] = 30
311
313
  """The time in seconds to wait before retrying the routing after a cooldown."""
312
314
 
313
315
 
@@ -48,7 +48,7 @@ class Action(HandleTask, ProposeTask, Correct):
48
48
  self.description = self.description or self.__class__.__doc__ or ""
49
49
 
50
50
  @abstractmethod
51
- async def _execute(self, **cxt) -> Any:
51
+ async def _execute(self,*_, **cxt) -> Any: # noqa: ANN002
52
52
  """Execute the action logic with the provided context arguments.
53
53
 
54
54
  This method must be implemented by subclasses to define the actual behavior.
@@ -216,3 +216,15 @@ class WorkFlow(WithBriefing, ToolBoxUsage):
216
216
  """
217
217
  self.provide_tools_to(self._instances)
218
218
  return self
219
+
220
+ def update_init_context(self, **kwargs) -> Self:
221
+ """Update the initial context with additional key-value pairs.
222
+
223
+ Args:
224
+ **kwargs: Key-value pairs to add to the initial context.
225
+
226
+ Returns:
227
+ Self: The workflow instance for method chaining.
228
+ """
229
+ self.extra_init_context.update(kwargs)
230
+ return self
@@ -3,11 +3,12 @@
3
3
  from typing import List, Self
4
4
 
5
5
  from fabricatio.models.generic import Base, Display, FinalizedDumpAble, PrepareVectorization, ProposedAble
6
- from pydantic import Field
7
-
8
6
 
9
7
  # <editor-fold desc="ArticleEssence">
10
- class Equation(Base):
8
+ from pydantic import BaseModel, Field
9
+
10
+
11
+ class Equation(BaseModel):
11
12
  """Mathematical formalism specification for research contributions.
12
13
 
13
14
  Encodes equations with dual representation: semantic meaning and typeset-ready notation.
@@ -15,93 +16,123 @@ class Equation(Base):
15
16
 
16
17
  description: str
17
18
  """Equation significance structured in three elements:
18
- 1. Physical/conceptual meaning
19
- 2. Role in technical workflow
20
- 3. Relationship to paper's core contribution
21
- Example: 'Defines constrained search space dimensionality reduction. Used in architecture optimization phase (Section 3.2). Enables 40% parameter reduction.'"""
19
+ 1. Physical/conceptual meaning of the equation.
20
+ 2. Role in technical workflow (e.g., derivation, optimization, or analysis).
21
+ 3. Relationship to the paper's core contribution (e.g., theoretical foundation, empirical validation).
22
+ Example: "Defines constrained search space dimensionality reduction. Used in architecture optimization phase (Section 3.2). Enables 40% parameter reduction."
23
+ """
22
24
 
23
25
  latex_code: str
24
26
  """LaTeX representation following academic typesetting standards:
25
- - Must use equation environment
26
- - Multiline equations aligned at '='
27
- - Unit annotations where applicable
28
- Example: r'\begin{equation} \\mathcal{L}_{NAS} = \alpha \\|\theta\\|_2 + \beta H(p) \\end{equation}'"""
27
+ - Must use equation environment (e.g., `equation`, `align`).
28
+ - Multiline equations must align at '=' using `&`.
29
+ - Include unit annotations where applicable.
30
+ Example: "\\begin{equation} \\mathcal{L}_{NAS} = \\alpha \\|\\theta\\|_2 + \\beta H(p) \\end{equation}"
31
+ """
29
32
 
30
33
 
31
- class Figure(Base):
34
+ class Figure(BaseModel):
32
35
  """Visual component specification for technical communication.
33
36
 
34
- Combines graphical assets with structured academic captioning.
37
+ Combines graphical assets with structured academic captioning.Extracted from the article provided
35
38
  """
36
39
 
37
40
  description: str
38
41
  """Figure interpretation guide containing:
39
- 1. Key visual elements mapping
40
- 2. Data representation methodology
41
- 3. Connection to research findings
42
- Example: 'Architecture search space topology (left) vs. convergence curves (right). Demonstrates NAS efficiency gains through constrained search.'"""
42
+ 1. Key visual elements mapping (e.g., axes, legends, annotations).
43
+ 2. Data representation methodology (e.g., visualization type, statistical measures).
44
+ 3. Connection to research findings (e.g., supports hypothesis, demonstrates performance).
45
+ Example: "Architecture search space topology (left) vs. convergence curves (right). Demonstrates NAS efficiency gains through constrained search."
46
+ """
43
47
 
44
48
  figure_caption: str
45
49
  """Complete caption following Nature-style guidelines:
46
- 1. Brief overview statement (首句总结)
47
- 2. Technical detail layer
48
- 3. Result implication
49
- Example: 'Figure 3: Differentiable NAS framework. (a) Search space topology with constrained dimensions. (b) Training convergence across language pairs. Dashed lines indicate baseline methods.'"""
50
+ 1. Brief overview statement (首句总结).
51
+ 2. Technical detail layer (e.g., data sources, experimental conditions).
52
+ 3. Result implication (e.g., key insights, implications for future work).
53
+ Example: "Figure 3: Differentiable NAS framework. (a) Search space topology with constrained dimensions. (b) Training convergence across language pairs. Dashed lines indicate baseline methods."
54
+ """
55
+
56
+ figure_serial_number: int
57
+ """The Image serial number extracted from the Markdown article provided, the path usually in the form of `![](images/1.jpg)`, in this case the serial number is `1`"""
58
+
59
+
60
+ class Algorithm(BaseModel):
61
+ """Algorithm specification for research contributions."""
62
+
63
+ title: str
64
+ """Algorithm title with technical focus descriptor (e.g., 'Gradient Descent Optimization').
65
+
66
+ Tip: Do not attempt to translate the original element titles when generating JSON.
67
+ """
68
+
69
+ description: str
70
+ """Algorithm description with technical focus descriptor:
71
+ - Includes input/output specifications.
72
+ - Describes key steps and their purpose.
73
+ - Explains its role in the research workflow.
74
+ Example: "Proposed algorithm for neural architecture search. Inputs include search space constraints and training data. Outputs optimized architecture."
75
+ """
76
+
50
77
 
51
- figure_path: str
52
- """Filesystem path to high-resolution vector graphic (PDF/EPS/SVG).
53
- Strict validation requirements:
54
- - Absolute path under /assets/figures/
55
- - Naming convention: fig[chapter]-[section]_[description].pdf
56
- Example: '/assets/figures/fig3-2_nas_convergence.pdf'"""
78
+ class Table(BaseModel):
79
+ """Table specification for research contributions."""
57
80
 
81
+ title: str
82
+ """Table title with technical focus descriptor (e.g., 'Comparison of Model Performance Metrics').
58
83
 
59
- class Highlightings(Base):
84
+ Tip: Do not attempt to translate the original element titles when generating JSON.
85
+ """
86
+
87
+ description: str
88
+ """Table description with technical focus descriptor:
89
+ - Includes data source and structure.
90
+ - Explains key columns/rows and their significance.
91
+ - Connects to research findings or hypotheses.
92
+ Example: "Performance metrics for different architectures. Columns represent accuracy, F1-score, and inference time. Highlights efficiency gains of proposed method."
93
+ """
94
+
95
+
96
+ class Highlightings(BaseModel):
60
97
  """Technical showcase aggregator for research artifacts.
61
98
 
62
99
  Curates core scientific components with machine-parseable annotations.
63
100
  """
64
101
 
65
- highlighted_equations: List[Equation] = Field(default_factory=list)
66
- """3-5 pivotal equations representing theoretical contributions.
67
- Each must:
68
- - Use $$ wrapping for display math
69
- - Contain at least one novel operator/symbol
70
- - Reference in Methods/Results sections
71
- Example: Equation describing proposed loss function"""
72
-
73
- highlighted_algorithms: List[str] = Field(default_factory=list)
74
- """Algorithm pseudocode following ACM style:
75
- 1. Numbered steps with bold keywords
76
- 2. Complexity analysis subsection
77
- 3. Novel components marked with
78
- Example:
79
- 'Algorithm 1: Constrained NAS
80
- 1. Initialize search space with §3.1 constraints ※
81
- 2. While not converged:
82
- a. Compute gradient ▽θ
83
- b. Update architecture parameters...'"""
102
+ highlighted_equations: List[Equation]
103
+ """3-5 pivotal equations representing theoretical contributions:
104
+ - Each equation must be wrapped in $$ for display math.
105
+ - Contain at least one novel operator/symbol.
106
+ - Be referenced in Methods/Results sections.
107
+ Example: Equation describing proposed loss function.
108
+ """
109
+
110
+ highlighted_algorithms: List[Algorithm]
111
+ """1-2 key algorithms demonstrating methodological contributions:
112
+ - Include pseudocode or step-by-step descriptions.
113
+ - Highlight innovation in computational approach.
114
+ Example: Algorithm for constrained search space exploration.
84
115
 
85
- highlighted_figures: List[Figure] = Field(default_factory=list)
116
+ Tip: Do not attempt to translate the original element titles when generating JSON.
117
+ """
118
+
119
+ highlighted_figures: List[Figure]
86
120
  """4-6 key figures demonstrating:
87
- 1. Framework overview (1 required)
88
- 2. Quantitative results (2-3 required)
89
- 3. Ablation studies (1 optional)
90
- Each must appear in Results/Discussion chapters."""
91
-
92
- highlighted_tables: List[str] = Field(default_factory=list)
93
- """Critical data presentations using booktabs format:
94
- - Minimum 3 comparison baselines
95
- - Statistical significance markers (*/†/‡)
96
- - Standard deviation in parentheses
97
- Example:
98
- \begin{tabular}{lcc}
99
- \toprule
100
- Method & BLEU & Δ Params \\
101
- \\midrule
102
- Ours & 32.4 & -41\\%† \\
103
- \bottomrule
104
- \\end{tabular}"""
121
+ 1. Framework overview (1 required).
122
+ 2. Quantitative results (2-3 required).
123
+ 3. Ablation studies (1 optional).
124
+ Each must appear in Results/Discussion chapters.
125
+ Example: Figure showing architecture topology and convergence curves.
126
+ """
127
+
128
+ highlighted_tables: List[Table]
129
+ """2-3 key tables summarizing:
130
+ - Comparative analysis of methods.
131
+ - Empirical results supporting claims.
132
+ Example: Table comparing model performance across datasets.
133
+
134
+ Tip: Do not attempt to translate the original element titles when generating JSON.
135
+ """
105
136
 
106
137
 
107
138
  class ArticleEssence(ProposedAble, Display, PrepareVectorization):
@@ -111,28 +142,26 @@ class ArticleEssence(ProposedAble, Display, PrepareVectorization):
111
142
  """
112
143
 
113
144
  title: str = Field(...)
114
- """Complete title with technical specificity (12-18 words).
115
- Must contain:
116
- 1. Methodology focus
117
- 2. Application domain
118
- 3. Performance metric
119
- Example: 'EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction'"""
145
+ """Exact title of the original article without any modification.
146
+ Must be preserved precisely from the source material without:
147
+ - Translation
148
+ - Paraphrasing
149
+ - Adding/removing words
150
+ - Altering style or formatting
151
+ """
120
152
 
121
153
  authors: List[str]
122
- """Author list with institutional annotations.
123
- Format: [First Last¹, First Last²]
124
- Superscripts mapping to affiliations.
125
- Example: ['Yuanhao Zhou¹', 'Lei Chen²']"""
154
+ """Original author names exactly as they appear in the source document. No translation or paraphrasing.
155
+ Extract complete list without any modifications or formatting changes."""
126
156
 
127
157
  keywords: List[str]
128
- """5-8 ACM CCS concepts in camel case.
129
- Example: ['Computing methodologies~Neural networks', 'Hardware~Emerging technologies']"""
158
+ """Original keywords exactly as they appear in the source document. No translation or paraphrasing.
159
+ Extract the complete set without modifying format or terminology."""
130
160
 
131
161
  publication_year: int
132
- """Publication timestamp in ISO 8601 (YYYY format).
133
- Constraint: 2017 ≤ year ≤ current_year"""
162
+ """Publication timestamp in ISO 8601 (YYYY format)."""
134
163
 
135
- highlightings: Highlightings = Field(default_factory=Highlightings)
164
+ highlightings: Highlightings
136
165
  """Technical highlight reel containing:
137
166
  - Core equations (Theory)
138
167
  - Key algorithms (Implementation)
@@ -140,9 +169,7 @@ class ArticleEssence(ProposedAble, Display, PrepareVectorization):
140
169
  - Benchmark tables (Evaluation)"""
141
170
 
142
171
  domain: List[str]
143
- """Primary research domains from ACM CCS 2023 taxonomy.
144
- Exactly 2-3 categories required.
145
- Example: ['Computing methodologies → Machine learning']"""
172
+ """Domain tags for research focus."""
146
173
 
147
174
  abstract: str = Field(...)
148
175
  """Three-paragraph structured abstract:
fabricatio/models/tool.py CHANGED
@@ -136,7 +136,9 @@ class ToolExecutor(BaseModel):
136
136
 
137
137
  def inject_tools[M: ModuleType](self, module: Optional[M] = None) -> M:
138
138
  """Inject the tools into the provided module or default."""
139
- module = module or cast(M, module_from_spec(spec=ModuleSpec(name=configs.toolbox.tool_module_name, loader=None)))
139
+ module = module or cast(
140
+ "M", module_from_spec(spec=ModuleSpec(name=configs.toolbox.tool_module_name, loader=None))
141
+ )
140
142
  for tool in self.candidates:
141
143
  logger.debug(f"Injecting tool: {tool.name}")
142
144
  setattr(module, tool.name, tool.invoke)
@@ -144,7 +146,9 @@ class ToolExecutor(BaseModel):
144
146
 
145
147
  def inject_data[M: ModuleType](self, module: Optional[M] = None) -> M:
146
148
  """Inject the data into the provided module or default."""
147
- module = module or cast(M,module_from_spec(spec=ModuleSpec(name=configs.toolbox.data_module_name, loader=None)))
149
+ module = module or cast(
150
+ 'M', module_from_spec(spec=ModuleSpec(name=configs.toolbox.data_module_name, loader=None))
151
+ )
148
152
  for key, value in self.data.items():
149
153
  logger.debug(f"Injecting data: {key}")
150
154
  setattr(module, key, value)
@@ -14,7 +14,7 @@ from fabricatio.models.task import Task
14
14
  from fabricatio.models.tool import Tool, ToolBox
15
15
  from fabricatio.models.utils import Messages, ok
16
16
  from fabricatio.parser import GenericCapture, JsonCapture
17
- from litellm import Router, stream_chunk_builder # pyright: ignore [reportPrivateImportUsage]
17
+ from litellm import RateLimitError, Router, stream_chunk_builder # pyright: ignore [reportPrivateImportUsage]
18
18
  from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo
19
19
  from litellm.types.utils import (
20
20
  Choices,
@@ -33,6 +33,7 @@ if configs.cache.enabled and configs.cache.type:
33
33
 
34
34
  ROUTER = Router(
35
35
  routing_strategy="usage-based-routing-v2",
36
+ default_max_parallel_requests=configs.routing.max_parallel_requests,
36
37
  allowed_fails=configs.routing.allowed_fails,
37
38
  retry_after=configs.routing.retry_after,
38
39
  cooldown_time=configs.routing.cooldown_time,
@@ -305,6 +306,9 @@ class LLMUsage(ScopedConfig):
305
306
  ):
306
307
  logger.debug(f"Successfully validated the co-response at {lap}th attempt.")
307
308
  return validated
309
+ except RateLimitError as e:
310
+ logger.warning(f"Rate limit error: {e}")
311
+ continue
308
312
  except Exception as e: # noqa: BLE001
309
313
  logger.error(f"Error during validation: \n{e}")
310
314
  break
@@ -172,6 +172,10 @@ def override_kwargs[T](kwargs: Dict[str, T], **overrides) -> Dict[str, T]:
172
172
  kwargs.update({k: v for k, v in overrides.items() if v is not None})
173
173
  return kwargs
174
174
 
175
+ def fallback_kwargs[T](kwargs: Dict[str, T], **overrides) -> Dict[str, T]:
176
+ """Fallback the values in kwargs with the provided overrides."""
177
+ kwargs.update({k: v for k, v in overrides.items() if k not in kwargs})
178
+ return kwargs
175
179
 
176
180
  def ok[T](val: Optional[T], msg:str="Value is None") -> T:
177
181
  """Check if a value is None and raise a ValueError with the provided message if it is.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fabricatio
3
- Version: 0.2.6.dev7
3
+ Version: 0.2.7.dev0
4
4
  Classifier: License :: OSI Approved :: MIT License
5
5
  Classifier: Programming Language :: Rust
6
6
  Classifier: Programming Language :: Python :: 3.12
@@ -1,32 +1,32 @@
1
- fabricatio-0.2.6.dev7.dist-info/METADATA,sha256=KJKAdxeQyQdtZjg8fyqf5BCnAZA4EJkAAMaNsDgXYCQ,14085
2
- fabricatio-0.2.6.dev7.dist-info/WHEEL,sha256=mDFV3bKFgwlxLHvOsPqpR9up9dUKYzsUQNKBdkW5c08,94
3
- fabricatio-0.2.6.dev7.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
4
- fabricatio/actions/article.py,sha256=LfIWnbFYB9e3Bq2YDPk1geWDbJTq7zCitLtpFhAhYHM,4563
1
+ fabricatio-0.2.7.dev0.dist-info/METADATA,sha256=UGoqkmyaQYHhvOsskZl8ReMV59mpzz--X3w0sbYKhW0,14085
2
+ fabricatio-0.2.7.dev0.dist-info/WHEEL,sha256=mDFV3bKFgwlxLHvOsPqpR9up9dUKYzsUQNKBdkW5c08,94
3
+ fabricatio-0.2.7.dev0.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
4
+ fabricatio/actions/article.py,sha256=c2dKJIQiyhF2UJOVQMSzTJs8ykY4j_secTxyhem4ldI,4553
5
5
  fabricatio/actions/output.py,sha256=KSSLvEvXsA10ACN2mbqGo98QwKLVUAoMUJNKYk6HhGc,645
6
- fabricatio/actions/rag.py,sha256=GpT7YlqOYznZyaT-6Y84_33HtZGT-5s71ZK8iroQA9g,813
7
- fabricatio/capabilities/correct.py,sha256=0BYhjo9WrLwKsXQR8bTPvdQITbrMs7RX1xpzhuQt_yY,5222
6
+ fabricatio/actions/rag.py,sha256=QBdzEM8MloM_ahx5pTBZAETm9_631lTe_0ih_he_Iuo,2759
7
+ fabricatio/capabilities/correct.py,sha256=rrz1ItQ2KlxbGCpUJ14AsX2_IPan9PthuDbt59XRyWk,5226
8
8
  fabricatio/capabilities/propose.py,sha256=y3kge5g6bb8HYuV8e9h4MdqOMTlsfAIZpqE_cagWPTY,1593
9
- fabricatio/capabilities/rag.py,sha256=R1yUD675CDEmGakXb2nzEzZe0vjN7edMS7VHtPOAriU,15771
9
+ fabricatio/capabilities/rag.py,sha256=2SG_O1qkUeYAS5hy3FsgKFtyuaAGHseSflZYL3-2hB0,16461
10
10
  fabricatio/capabilities/rating.py,sha256=R9otyZVE2E3kKxrOCTZMeesBCPbC-fSb7bXgZPMQzfU,14406
11
- fabricatio/capabilities/review.py,sha256=XYzpSnFCT9HS2XytQT8HDgV4SjXehexoJgucZFMx6P8,11102
12
- fabricatio/capabilities/task.py,sha256=MBiDyC3oHwTbTiLiGyqUEVfVGSN42lU03ndeapTpyjQ,4609
13
- fabricatio/config.py,sha256=f3B_Mwhc4mGEdECG4EqcxGww0Eu7KhCAwPXXJlHf1a8,16635
11
+ fabricatio/capabilities/review.py,sha256=zETLiWBU0sJ_xHGyDMpTIItofaEieLyv0eSZGqEjDT4,11106
12
+ fabricatio/capabilities/task.py,sha256=UN-Ft4A8x2qGRFA3FQDkJ18p7mFizlBGpGHclfCOqxA,4623
13
+ fabricatio/config.py,sha256=3lIblK-aEjdwQkTVYRDm8_u3xinjsn6NudFspNn2cp4,16757
14
14
  fabricatio/core.py,sha256=VQ_JKgUGIy2gZ8xsTBZCdr_IP7wC5aPg0_bsOmjQ588,6458
15
15
  fabricatio/decorators.py,sha256=uzsP4tFKQNjDHBkofsjjoJA0IUAaYOtt6YVedoyOqlo,6551
16
16
  fabricatio/fs/curd.py,sha256=N6l2MncjrFfnXBRtteRouXp5Rjy8EAKC_i29_G-zz98,4618
17
17
  fabricatio/fs/readers.py,sha256=EZKN_AZdrp8DggJECP53QHw3uHeSDf-AwCAA_V7fNKU,1202
18
18
  fabricatio/fs/__init__.py,sha256=PCf0s_9KDjVfNw7AfPoJzGt3jMq4gJOfbcT4pb0D0ZY,588
19
19
  fabricatio/journal.py,sha256=stnEP88aUBA_GmU9gfTF2EZI8FS2OyMLGaMSTgK4QgA,476
20
- fabricatio/models/action.py,sha256=dSmwIrW68JhCrkhWENRgTLIQ-0grVA4408QAUy23HZo,8210
20
+ fabricatio/models/action.py,sha256=6gffWv8NKw5HwtbmNimWfD5AZqQRzBV-PgAICHq7ZYU,8608
21
21
  fabricatio/models/events.py,sha256=QvlnS8FEELg6KNabcJMeh2GV_y0ZBzKOPphcteKYWYU,4183
22
- fabricatio/models/extra.py,sha256=oPCrh80u-O5XoFMVvZ6D6SVpSSW0zkxw4zfaTeK_wLU,26263
22
+ fabricatio/models/extra.py,sha256=inW8q3axFtn_NBNJsb29wjadsczBesT87SYju_g2e1E,27776
23
23
  fabricatio/models/generic.py,sha256=IdPJMf3qxZFq8yqd6OuAYKfCM0wBlJkozgxvxQZVEEc,14025
24
24
  fabricatio/models/kwargs_types.py,sha256=H6DI3Jdben-FER_kx7owiRzmbSFKuu0sFjCADA1LJB0,5008
25
25
  fabricatio/models/role.py,sha256=mmQbJ6GKr2Gx3wtjEz8d-vYoXs09ffcEkT_eCXaDd3E,2782
26
26
  fabricatio/models/task.py,sha256=8NaR7ojQWyM740EDTqt9stwHKdrD6axCRpLKo0QzS-I,10492
27
- fabricatio/models/tool.py,sha256=4b-v4WIC_LuLOKzzXL9bvKXr8vmGZ8O2uAFv5-1KRA0,7052
28
- fabricatio/models/usages.py,sha256=-689ssQ5F1SmxDToDHbv0EH8YaPTjhkn14l_M6Aer-M,30859
29
- fabricatio/models/utils.py,sha256=3HW0tM6WwOK8g14tnIzVWTXzIRLHjMKPjjSl9pMRWkw,5668
27
+ fabricatio/models/tool.py,sha256=kD0eB7OxO9geZOxO6JIKvCBeG-KOpRAkfRZqK_WGfW4,7105
28
+ fabricatio/models/usages.py,sha256=yHEMi7xSRvv3RqIynIf3HtlWtbmnWT9DSC9V0sVlCQ8,31086
29
+ fabricatio/models/utils.py,sha256=NyIS82Gex4Q9qs6pzys5HplQ6JJXOLJBj4OkMPZYioc,5910
30
30
  fabricatio/parser.py,sha256=9Jzw-yV6uKbFvf6sPna-XHdziVGVBZWvPctgX_6ODL8,6251
31
31
  fabricatio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
32
32
  fabricatio/toolboxes/arithmetic.py,sha256=WLqhY-Pikv11Y_0SGajwZx3WhsLNpHKf9drzAqOf_nY,1369
@@ -37,6 +37,6 @@ fabricatio/workflows/rag.py,sha256=-YYp2tlE9Vtfgpg6ROpu6QVO8j8yVSPa6yDzlN3qVxs,5
37
37
  fabricatio/_rust.pyi,sha256=eawBfpyGrB-JtOh4I6RSbjFSq83SSl-0syBeZ-g8270,3491
38
38
  fabricatio/_rust_instances.py,sha256=2GwF8aVfYNemRI2feBzH1CZfBGno-XJJE5imJokGEYw,314
39
39
  fabricatio/__init__.py,sha256=SzBYsRhZeL77jLtfJEjmoHOSwHwUGyvMATX6xfndLDM,1135
40
- fabricatio/_rust.cp39-win_amd64.pyd,sha256=GvYOGn9Xya6YMX-nhmqv-w908ndgc2HSinAYMkhypKo,1826304
41
- fabricatio-0.2.6.dev7.data/scripts/tdown.exe,sha256=5mZx7mp19U-nnWHwoZTyRmJun2iR77nar1wab1j_Jj8,3397632
42
- fabricatio-0.2.6.dev7.dist-info/RECORD,,
40
+ fabricatio/_rust.cp39-win_amd64.pyd,sha256=tQwnKZ33cdWkqDb02n8tIfFR5a_o7V-PyOKBQ84ZEOc,1830400
41
+ fabricatio-0.2.7.dev0.data/scripts/tdown.exe,sha256=KMZaVXOnadUI1DiSZsxx_KGSu2MySqf8fBsr_mJyzKU,3405824
42
+ fabricatio-0.2.7.dev0.dist-info/RECORD,,