fabricatio 0.2.6.dev6__cp39-cp39-win_amd64.whl → 0.2.6.dev8__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
fabricatio/actions/rag.py CHANGED
@@ -3,6 +3,7 @@
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
8
9
 
@@ -13,13 +14,13 @@ class InjectToDB(Action, RAG):
13
14
  output_key: str = "collection_name"
14
15
 
15
16
  async def _execute[T: PrepareVectorization](
16
- self, to_inject: T | List[T], collection_name: Optional[str] = "my_collection", **_
17
+ self, to_inject: Optional[T] | List[Optional[T]], collection_name: Optional[str] = "my_collection", **_
17
18
  ) -> Optional[str]:
18
19
  if not isinstance(to_inject, list):
19
20
  to_inject = [to_inject]
20
-
21
+ logger.info(f"Injecting {len(to_inject)} items into the collection '{collection_name}'")
21
22
  await self.view(collection_name, create=True).consume_string(
22
- [t.prepare_vectorization(self.embedding_max_sequence_length) for t in to_inject],
23
+ [t.prepare_vectorization(self.embedding_max_sequence_length) for t in to_inject if isinstance(t,PrepareVectorization)],
23
24
  )
24
25
 
25
26
  return collection_name
@@ -15,7 +15,7 @@ from fabricatio.config import configs
15
15
  from fabricatio.journal import logger
16
16
  from fabricatio.models.kwargs_types import (
17
17
  ChooseKwargs,
18
- CollectionSimpleConfigKwargs,
18
+ CollectionConfigKwargs,
19
19
  EmbeddingKwargs,
20
20
  FetchKwargs,
21
21
  LLMKwargs,
@@ -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]
@@ -102,17 +110,24 @@ class RAG(EmbeddingUsage):
102
110
  ]
103
111
 
104
112
  def view(
105
- self, collection_name: Optional[str], create: bool = False, **kwargs: Unpack[CollectionSimpleConfigKwargs]
113
+ self, collection_name: Optional[str], create: bool = False, **kwargs: Unpack[CollectionConfigKwargs]
106
114
  ) -> Self:
107
115
  """View the specified collection.
108
116
 
109
117
  Args:
110
118
  collection_name (str): The name of the collection.
111
119
  create (bool): Whether to create the collection if it does not exist.
112
- **kwargs (Unpack[CollectionSimpleConfigKwargs]): Additional keyword arguments for collection configuration.
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},
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
 
@@ -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
@@ -1,11 +1,12 @@
1
1
  """Extra models for built-in actions."""
2
2
 
3
- from typing import List
3
+ from typing import List, Self
4
4
 
5
5
  from fabricatio.models.generic import Base, Display, FinalizedDumpAble, PrepareVectorization, ProposedAble
6
6
  from pydantic import Field
7
7
 
8
8
 
9
+ # <editor-fold desc="ArticleEssence">
9
10
  class Equation(Base):
10
11
  """Mathematical formalism specification for research contributions.
11
12
 
@@ -108,28 +109,25 @@ class ArticleEssence(ProposedAble, Display, PrepareVectorization):
108
109
 
109
110
  Encodes research artifacts with dual human-machine interpretability.
110
111
  """
111
-
112
112
  title: str = Field(...)
113
- """Complete title with technical specificity (12-18 words).
114
- Must contain:
115
- 1. Methodology focus
116
- 2. Application domain
117
- 3. Performance metric
118
- Example: 'EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction'"""
113
+ """Exact title of the original article without any modification.
114
+ Must be preserved precisely from the source material without:
115
+ - Translation
116
+ - Paraphrasing
117
+ - Adding/removing words
118
+ - Altering style or formatting
119
+ Example: The exact published title as it appears in the original document"""
119
120
 
120
121
  authors: List[str]
121
- """Author list with institutional annotations.
122
- Format: [First Last¹, First Last²]
123
- Superscripts mapping to affiliations.
124
- Example: ['Yuanhao Zhou¹', 'Lei Chen²']"""
122
+ """Original author names exactly as they appear in the source document. No translation or paraphrasing.
123
+ Extract complete list without any modifications or formatting changes."""
125
124
 
126
125
  keywords: List[str]
127
- """5-8 ACM CCS concepts in camel case.
128
- Example: ['Computing methodologies~Neural networks', 'Hardware~Emerging technologies']"""
126
+ """Original keywords exactly as they appear in the source document. No translation or paraphrasing.
127
+ Extract the complete set without modifying format or terminology."""
129
128
 
130
129
  publication_year: int
131
- """Publication timestamp in ISO 8601 (YYYY format).
132
- Constraint: 2017 ≤ year ≤ current_year"""
130
+ """Publication timestamp in ISO 8601 (YYYY format)."""
133
131
 
134
132
  highlightings: Highlightings = Field(default_factory=Highlightings)
135
133
  """Technical highlight reel containing:
@@ -200,6 +198,9 @@ class ArticleEssence(ProposedAble, Display, PrepareVectorization):
200
198
  return self.model_dump_json()
201
199
 
202
200
 
201
+ # </editor-fold>
202
+
203
+
203
204
  class ArticleProposal(ProposedAble, Display):
204
205
  """Structured proposal for academic paper development with core research elements.
205
206
 
@@ -221,119 +222,434 @@ class ArticleProposal(ProposedAble, Display):
221
222
  """Methodological components (list of techniques/tools).
222
223
  Example: ['Differentiable architecture search', 'Transformer-based search space', 'Multi-lingual perplexity evaluation']"""
223
224
 
225
+ technical_approaches: List[str] = Field(default_factory=list)
224
226
 
225
- class ArticleSubsectionOutline(Base):
226
- """Atomic content unit within academic paper sections.
227
227
 
228
- Provides structured content specification for LLM-generated subsections.
229
- """
228
+ # <editor-fold desc="ArticleOutline">
229
+ class ArticleSubsectionOutline(Base):
230
+ """Atomic research component specification for academic paper generation."""
230
231
 
231
232
  title: str = Field(...)
232
- """Subsection title reflecting specific content focus (Title Case, 3-8 words).
233
- Example: 'Differentiable Search Space Design'"""
233
+ """Technical focus descriptor following ACL title conventions:
234
+ - Title Case with 4-8 word limit
235
+ - Contains method and domain components
236
+ Example: 'Differentiable Search Space Optimization'"""
234
237
 
235
238
  description: str = Field(...)
236
- """Content specification with three required elements:
237
- 1. Core technical content
238
- 2. Structural purpose in section
239
- 3. Research significance
240
- Example: 'Introduces continuous relaxation method for search space, enabling gradient-based optimization. Forms technical foundation for Section 3. Critical for reducing search complexity.'"""
239
+ """Tripartite content specification with strict structure:
240
+ 1. Technical Core: Method/algorithm/formalism (1 sentence)
241
+ 2. Structural Role: Placement rationale in section (1 clause)
242
+ 3. Research Value: Contribution to paper's thesis (1 clause)
241
243
 
244
+ Example: 'Introduces entropy-constrained architecture parameters enabling
245
+ gradient-based NAS. Serves as foundation for Section 3.2. Critical for
246
+ maintaining search space diversity while ensuring convergence.'"""
242
247
 
243
- class ArticleSectionOutline(Base):
244
- """Primary organizational unit within paper chapters.
245
248
 
246
- Defines section-level structure with nested subsections for hierarchical content organization.
247
- """
249
+ class ArticleSectionOutline(Base):
250
+ """Methodological unit organizing related technical components."""
248
251
 
249
252
  title: str = Field(...)
250
- """Section title indicating methodological phase or conceptual component (Title Case).
251
- Example: 'Architecture Search Methodology'"""
253
+ """Process-oriented header with phase identification:
254
+ - Title Case with 5-10 word limit
255
+ - Indicates research stage/methodological focus
256
+ Example: 'Cross-Lingual Evaluation Protocol'"""
252
257
 
253
258
  description: str = Field(...)
254
- """Functional description covering:
255
- 1. Section's research stage
256
- 2. Key contributions
257
- 3. Flow relationship with adjacent sections
258
- Example: 'Presents core NAS framework building on literature from Section 2. Introduces novel constrained search space. Leads to implementation details in Section 4.'"""
259
-
260
- subsections: List[ArticleSubsectionOutline]
261
- """Ordered sequence of 3-5 subsections implementing IMRaD structure within section. Maintains logical flow from problem statement to technical solution."""
259
+ """Functional specification with four required elements:
260
+ 1. Research Stage: Paper progression position
261
+ 2. Technical Innovations: Novel components
262
+ 3. Scholarly Context: Relationship to prior work
263
+ 4. Forward Flow: Connection to subsequent sections
264
+
265
+ Example: 'Implements constrained NAS framework building on Section 2's
266
+ theoretical foundations. Introduces dynamic resource allocation mechanism.
267
+ Directly supports Results section through ablation study parameters.'"""
268
+
269
+ subsections: List[ArticleSubsectionOutline] = Field(..., min_length=3, max_length=5)
270
+ """IMRaD-compliant substructure with technical progression:
271
+ 1. Conceptual Framework
272
+ 2. Methodological Details
273
+ 3. Implementation Strategy
274
+ 4. Validation Approach
275
+ 5. Transition Logic
276
+
277
+ Example Flow:
278
+ [
279
+ 'Search Space Constraints',
280
+ 'Gradient Optimization Protocol',
281
+ 'Multi-GPU Implementation',
282
+ 'Convergence Validation',
283
+ 'Cross-Lingual Extension'
284
+ ]"""
262
285
 
263
286
 
264
287
  class ArticleChapterOutline(Base):
265
- """Macro-level paper organization unit.
266
-
267
- Represents major paper divisions (Introduction, Methodology, etc.) with hierarchical section structure.
268
- """
288
+ """Macro-structural unit implementing standard academic paper organization."""
269
289
 
270
290
  title: str = Field(...)
271
- """Chapter title reflecting standard academic sections (Title Case).
272
- Example: 'Experimental Evaluation', 'Theoretical Framework'"""
291
+ """IMRaD-compliant chapter title with domain specification:
292
+ - Title Case with 2-4 word limit
293
+ - Matches standard paper sections
294
+ Example: 'Multilingual Evaluation Results'"""
273
295
 
274
296
  description: str = Field(...)
275
- """Chapter role specification containing:
276
- 1. Research phase covered
277
- 2. Chapter-specific objectives
278
- 3. Relationship to overall paper thesis
279
- Example: 'Validates NAS framework through multilingual experiments. Demonstrates method effectiveness across 10 language pairs. Supports core thesis of parameter-efficient architecture search.'"""
280
-
281
- sections: List[ArticleSectionOutline]
282
- """3-5 sections implementing chapter's main function. Ordered to maintain academic paper logic:
283
- Introduction Related Work Methods → Experiments → Analysis"""
297
+ """Strategic chapter definition containing:
298
+ 1. Research Phase: Introduction/Methods/Results/etc.
299
+ 2. Chapter Objectives: 3-5 specific goals
300
+ 3. Thesis Alignment: Supported claims/contributions
301
+ 4. Structural Flow: Adjacent chapter relationships
302
+
303
+ Example: 'Presents cross-lingual NAS results across 10 language pairs.
304
+ Validates efficiency claims from Introduction. Provides empirical basis
305
+ for Discussion chapter. Contrasts with single-language baselines.'"""
306
+
307
+ sections: List[ArticleSectionOutline] = Field(..., min_length=3, max_length=5)
308
+ """Standard academic progression implementing chapter goals:
309
+ 1. Context Establishment
310
+ 2. Technical Presentation
311
+ 3. Empirical Validation
312
+ 4. Comparative Analysis
313
+ 5. Synthesis
314
+
315
+ Example Structure:
316
+ [
317
+ 'Experimental Setup',
318
+ 'Monolingual Baselines',
319
+ 'Cross-Lingual Transfer',
320
+ 'Low-Resource Scaling',
321
+ 'Error Analysis'
322
+ ]"""
284
323
 
285
324
 
286
325
  class ArticleOutline(ProposedAble, Display, FinalizedDumpAble):
287
- """Complete hierarchical structure for academic paper generation.
288
-
289
- Provides multi-level outline specification for LLM-based paper drafting with strict academic conventions.
290
- """
326
+ """Complete academic paper blueprint with hierarchical validation."""
291
327
 
292
328
  title: str = Field(...)
293
- """Full paper title with technical specificity (Title Case, 12-18 words).
294
- Example: 'Parameter-Efficient Neural Architecture Search for Low-Resource Machine Translation: A Cross-Lingual Transfer Approach'"""
329
+ """Full technical title following ACL 2024 guidelines:
330
+ - Title Case with 12-18 word limit
331
+ - Structure: [Method] for [Task] via [Approach] in [Domain]
332
+ Example: 'Efficient Differentiable NAS for Low-Resource MT Through
333
+ Parameter-Sharing: A Cross-Lingual Study'"""
295
334
 
296
335
  prospect: str = Field(...)
297
- """Unified problem-solution statement combining:
298
- 1. Core research gap
299
- 2. Proposed methodology
300
- 3. Expected contribution
301
- Example: 'Addressing NAS computational barriers in low-resource NLP through differentiable constrained search spaces and cross-lingual transfer metrics, enabling efficient architecture discovery for 50+ languages.'"""
302
-
303
- chapters: List[ArticleChapterOutline]
304
- """Standard academic structure (5-8 chapters):
305
- 1. Introduction
306
- 2. Related Work
307
- 3. Methodology
308
- 4. Experiments
309
- 5. Results
310
- 6. Discussion
311
- 7. Conclusion
312
- Maintains IMRaD logical flow with clear inter-chapter transitions."""
336
+ """Consolidated research statement with four pillars:
337
+ 1. Problem Identification: Current limitations
338
+ 2. Methodological Response: Technical approach
339
+ 3. Empirical Validation: Evaluation strategy
340
+ 4. Scholarly Impact: Field contributions
341
+
342
+ Example: 'Addressing NAS computational barriers through constrained
343
+ differentiable search spaces, validated via cross-lingual MT experiments
344
+ across 50+ languages, enabling efficient architecture discovery with
345
+ 60% reduced search costs.'"""
346
+
347
+ chapters: List[ArticleChapterOutline] = Field(..., min_length=5, max_length=8)
348
+ """IMRaD structure with enhanced academic validation:
349
+ 1. Introduction: Problem Space & Contributions
350
+ 2. Background: Theoretical Foundations
351
+ 3. Methods: Technical Innovations
352
+ 4. Experiments: Protocol Design
353
+ 5. Results: Empirical Findings
354
+ 6. Discussion: Interpretation & Limitations
355
+ 7. Conclusion: Synthesis & Future Work
356
+ 8. Appendices: Supplementary Materials"""
313
357
 
314
358
  def finalized_dump(self) -> str:
315
- """Generates standardized hierarchical markup for paper drafting systems.
359
+ """Generates standardized hierarchical markup for academic publishing systems.
360
+
361
+ Implements ACL 2024 outline conventions with four-level structure:
362
+ = Chapter Title (Level 1)
363
+ == Section Title (Level 2)
364
+ === Subsection Title (Level 3)
365
+ ==== Subsubsection Title (Level 4)
316
366
 
317
367
  Returns:
318
- str: Multi-level outline using academic markup conventions:
319
- = Chapter Title
320
- == Section Title
321
- === Subsection Title
322
- ==== Subsubsection Title (if needed)
368
+ str: Strictly formatted outline with academic sectioning
323
369
 
324
370
  Example:
325
371
  = Methodology
326
372
  == Neural Architecture Search Framework
327
373
  === Differentiable Search Space
328
- === Constrained Optimization Approach
374
+ ==== Constrained Optimization Parameters
375
+ === Implementation Details
376
+ == Evaluation Protocol
329
377
  """
330
378
  lines: List[str] = []
379
+ for i, chapter in enumerate(self.chapters, 1):
380
+ lines.append(f"= Chapter {i}: {chapter.title}")
381
+ for j, section in enumerate(chapter.sections, 1):
382
+ lines.append(f"== {i}.{j} {section.title}")
383
+ for k, subsection in enumerate(section.subsections, 1):
384
+ lines.append(f"=== {i}.{j}.{k} {subsection.title}")
385
+ return "\n".join(lines)
386
+
387
+
388
+ # </editor-fold>
389
+
390
+
391
+ # <editor-fold desc="Article">
392
+ class Paragraph(ProposedAble):
393
+ """Structured academic paragraph blueprint for controlled content generation."""
394
+
395
+ description: str
396
+ """Functional summary of the paragraph's role in document structure.
397
+ Example: 'Establishes NAS efficiency improvements through differentiable methods'"""
398
+
399
+ writing_aim: List[str]
400
+ """Specific communicative objectives for this paragraph's content.
401
+ Example: ['Introduce gradient-based NAS', 'Compare computational costs',
402
+ 'Link efficiency to practical applications']"""
403
+
404
+ lines: List[str]
405
+ """Hierarchically structured content with enforced rhetorical elements:
406
+ 1. Topic Sentence: Principal claim/position (1 sentence)
407
+ 2. Development: Evidence chain with citations (2-4 sentences)
408
+ 3. Synthesis: Interpretation & significance (1 sentence)
409
+ 4. Transition: Logical bridge to next paragraph (optional)
410
+
411
+ Example: [
412
+ 'Differentiable NAS revolutionized architecture search efficiency.',
413
+ 'DARTS reduced search costs from 2000+ to 4 GPU days (Liu et al., 2019) while maintaining competitive ImageNet accuracy.',
414
+ 'This order-of-magnitude improvement enables NAS deployment in resource-constrained research contexts.',
415
+ 'These efficiency gains directly impact our framework's design choices as detailed in Section 3.'
416
+ ]"""
417
+
418
+
419
+ class SectionRef(ProposedAble):
420
+ """Cross-component reference system for maintaining document consistency."""
421
+
422
+ ref_chapter_title: str
423
+ """Title of referenced chapter (e.g., 'Methodology')"""
424
+
425
+ ref_section_title: str
426
+ """Exact section header text (e.g., '3.2 Gradient Optimization')"""
331
427
 
332
- for chapter in self.chapters:
333
- lines.append(f"= {chapter.title}")
334
- for section in chapter.sections:
335
- lines.append(f"== {section.title}")
336
- for subsection in section.subsections:
337
- lines.append(f"=== {subsection.title}")
428
+ ref_subsection_title: str
429
+ """Specific subsection identifier (e.g., '3.2.1 Learning Rate Scheduling')"""
338
430
 
339
- return "\n\n".join(lines)
431
+
432
+ class ArticleBase(ProposedAble, Display):
433
+ """Foundation for hierarchical document components with dependency tracking."""
434
+
435
+ description: str
436
+ """Functional purpose statement for this component's role in the paper.
437
+ Example: 'Defines evaluation metrics for cross-lingual transfer experiments'"""
438
+
439
+ writing_aim: List[str]
440
+ """Author intentions mapped to rhetorical moves:
441
+ Example: ['Establish metric validity', 'Compare with baseline approaches',
442
+ 'Justify threshold selection']"""
443
+
444
+ title: str = Field(...)
445
+ """Standardized academic header following ACL style guidelines:
446
+ - Title Case with maximal 12-word length
447
+ - No abbreviations without prior definition
448
+ Example: 'Multilingual Benchmark Construction'"""
449
+
450
+ support_to: List[SectionRef]
451
+ """Upstream dependencies requiring this component's validation.
452
+ Format: List of hierarchical references to supported claims/sections
453
+ Example: [SectionRef(chapter='Results', section='4.1', subsection='4.1.2')]"""
454
+
455
+ depend_on: List[SectionRef]
456
+ """Downstream prerequisites for content validity.
457
+ Format: List of references to foundational components
458
+ Example: [SectionRef(chapter='Methods', section='2.3', subsection='2.3.4')]"""
459
+
460
+
461
+ class ArticleSubsection(ArticleBase):
462
+ """Atomic argumentative unit with technical specificity."""
463
+
464
+ title: str = Field(...)
465
+ """Technical descriptor with maximal information density:
466
+ Format: [Method]-[Domain]-[Innovation]
467
+ Example: 'Transformer-Based Architecture Search Space'"""
468
+
469
+ support_to: List[SectionRef]
470
+ """Immediate parent components and supported hypotheses.
471
+ Example: [SectionRef(chapter='Methods', section='3', subsection='3.1')]"""
472
+
473
+ depend_on: List[SectionRef]
474
+ """Technical dependencies including equations, algorithms, and datasets.
475
+ Example: [SectionRef(chapter='Background', section='2.2', subsection='2.2.3')]"""
476
+
477
+ paragraphs: List[Paragraph] = Field(..., min_length=3, max_length=5)
478
+ """Technical exposition following ACM writing guidelines:
479
+ 1. Contextualization: Position in research design
480
+ 2. Technical Detail: Equations/algorithms/code
481
+ 3. Validation: Citations/experimental confirmation
482
+ 4. Interpretation: Scholarly significance
483
+ 5. Transition: Logical connection to subsequent content
484
+
485
+ Example Paragraph Chain:
486
+ [
487
+ 'Our search space builds on standard CNN architectures...',
488
+ 'Formally, we define architecture parameters $\\alpha \\in R^d$ where...',
489
+ 'This parameterization reduces search complexity by 42% compared to...',
490
+ 'The efficiency gains validate our approach to...'
491
+ ]"""
492
+
493
+
494
+ class ArticleSection(ArticleBase):
495
+ """Methodological complete unit presenting cohesive research phase."""
496
+
497
+ title: str = Field(...)
498
+ """Process-oriented header indicating methodological scope.
499
+ Example: 'Cross-Lingual Transfer Evaluation Protocol'"""
500
+
501
+ support_to: List[SectionRef]
502
+ """Supported research questions and paper-level claims.
503
+ Example: [SectionRef(chapter='Introduction', section='1', subsection='1.2')]"""
504
+
505
+ depend_on: List[SectionRef]
506
+ """Required methodological components and theoretical frameworks.
507
+ Example: [SectionRef(chapter='Background', section='2', subsection='2.4')]"""
508
+
509
+ subsections: List[ArticleSubsection] = Field(..., min_length=3, max_length=5)
510
+ """Thematic progression implementing section's research function:
511
+ 1. Conceptual Framework
512
+ 2. Technical Implementation
513
+ 3. Experimental Validation
514
+ 4. Comparative Analysis
515
+ 5. Synthesis
516
+
517
+ Example Subsection Flow:
518
+ [
519
+ 'Evaluation Metrics',
520
+ 'Dataset Preparation',
521
+ 'Baseline Comparisons',
522
+ 'Ablation Studies',
523
+ 'Interpretation Framework'
524
+ ]"""
525
+
526
+
527
+ class ArticleChapter(ArticleBase):
528
+ """Macro-structural unit implementing IMRaD document architecture."""
529
+
530
+ title: str = Field(...)
531
+ """Standard IMRaD chapter title with domain specification.
532
+ Example: 'Neural Architecture Search for Low-Resource Languages'"""
533
+
534
+ support_to: List[SectionRef]
535
+ """Supported thesis statements and paper-level contributions.
536
+ Example: [SectionRef(chapter='Abstract', section='', subsection='')]"""
537
+
538
+ depend_on: List[SectionRef]
539
+ """Foundational chapters and external knowledge prerequisites.
540
+ Example: [SectionRef(chapter='Related Work', section='2', subsection='2.3')]"""
541
+
542
+ sections: List[ArticleSection] = Field(..., min_length=3, max_length=5)
543
+ """Complete research narrative implementing chapter objectives:
544
+ 1. Context Establishment
545
+ 2. Methodology Exposition
546
+ 3. Results Presentation
547
+ 4. Critical Analysis
548
+ 5. Synthesis
549
+
550
+ Example Section Hierarchy:
551
+ [
552
+ 'Theoretical Framework',
553
+ 'Experimental Design',
554
+ 'Results Analysis',
555
+ 'Threats to Validity',
556
+ 'Comparative Discussion'
557
+ ]"""
558
+
559
+
560
+ class Article(ProposedAble, Display):
561
+ """Complete academic paper specification with validation constraints."""
562
+
563
+ title: str = Field(...)
564
+ """Full technical descriptor following ACL 2024 guidelines:
565
+ Structure: [Method] for [Task] in [Domain]: [Subtitle with Technical Focus]
566
+ Example: 'Efficient Differentiable NAS for Low-Resource MT:
567
+ A Parameter-Sharing Approach to Cross-Lingual Transfer'"""
568
+
569
+ abstract: str = Field(...)
570
+ """Structured summary with controlled natural language:
571
+ 1. Context: 2 clauses (problem + gap)
572
+ 2. Methods: 3 clauses (approach + innovation + implementation)
573
+ 3. Results: 3 clauses (metrics + comparisons + significance)
574
+ 4. Impact: 2 clauses (theoretical + practical)
575
+
576
+ Example: 'Neural architecture search (NAS) faces prohibitive... [150 words]'"""
577
+
578
+ chapters: List[ArticleChapter] = Field(..., min_length=5, max_length=8)
579
+ """IMRaD-compliant document structure with enhanced validation:
580
+ 1. Introduction: Motivation & Contributions
581
+ 2. Background: Literature & Theory
582
+ 3. Methods: Technical Implementation
583
+ 4. Experiments: Protocols & Setup
584
+ 5. Results: Empirical Findings
585
+ 6. Discussion: Interpretation & Limitations
586
+ 7. Conclusion: Summary & Future Work
587
+
588
+ Additional: Appendices, Ethics Review, Reproducibility Statements"""
589
+
590
+ def init_from_outline(self, outline: ArticleOutline) -> Self:
591
+ """Initialize the article from a given outline.
592
+
593
+ Args:
594
+ outline (ArticleOutline): The outline to initialize from.
595
+
596
+ Returns:
597
+ Self: The current instance of the article.
598
+ """
599
+ # Set the title from the outline
600
+ self.title = outline.title
601
+
602
+ # Initialize chapters based on outline's chapters
603
+ self.chapters = []
604
+
605
+ for chapter_outline in outline.chapters:
606
+ # Create a new chapter
607
+ chapter = ArticleChapter(
608
+ title=chapter_outline.title,
609
+ description=chapter_outline.description,
610
+ writing_aim=["Implement " + chapter_outline.description],
611
+ support_to=[],
612
+ depend_on=[],
613
+ sections=[],
614
+ )
615
+
616
+ # Create sections for each chapter
617
+ for section_outline in chapter_outline.sections:
618
+ section = ArticleSection(
619
+ title=section_outline.title,
620
+ description=section_outline.description,
621
+ writing_aim=["Address " + section_outline.description],
622
+ support_to=[],
623
+ depend_on=[],
624
+ subsections=[],
625
+ )
626
+
627
+ # Create subsections for each section
628
+ for subsection_outline in section_outline.subsections:
629
+ subsection = ArticleSubsection(
630
+ title=subsection_outline.title,
631
+ description=subsection_outline.description,
632
+ writing_aim=["Explain " + subsection_outline.description],
633
+ support_to=[],
634
+ depend_on=[],
635
+ paragraphs=[
636
+ Paragraph(
637
+ description=f"Implementation of {subsection_outline.title}",
638
+ writing_aim=["Present key concepts", "Support main arguments"],
639
+ lines=[],
640
+ )
641
+ ],
642
+ )
643
+ section.subsections.append(subsection)
644
+
645
+ chapter.sections.append(section)
646
+
647
+ self.chapters.append(chapter)
648
+
649
+ # Generate a placeholder abstract from the outline's prospect
650
+ self.abstract = f"Abstract: {outline.prospect}"
651
+
652
+ return self
653
+
654
+
655
+ # </editor-fold>
@@ -1,19 +1,29 @@
1
1
  """This module contains the types for the keyword arguments of the methods in the models module."""
2
2
 
3
+ from importlib.util import find_spec
3
4
  from typing import Any, Required, TypedDict
4
5
 
5
6
  from litellm.caching.caching import CacheMode
6
7
  from litellm.types.caching import CachingSupportedCallTypes
7
8
 
9
+ if find_spec("pymilvus"):
10
+ from pymilvus import CollectionSchema
11
+ from pymilvus.milvus_client import IndexParams
8
12
 
9
- class CollectionSimpleConfigKwargs(TypedDict, total=False):
10
- """Configuration parameters for a vector collection.
13
+ class CollectionConfigKwargs(TypedDict, total=False):
14
+ """Configuration parameters for a vector collection.
11
15
 
12
- These arguments are typically used when configuring connections to vector databases.
13
- """
16
+ These arguments are typically used when configuring connections to vector databases.
17
+ """
14
18
 
15
- dimension: int | None
16
- timeout: float
19
+ dimension: int | None
20
+ primary_field_name: str
21
+ id_type: str
22
+ vector_field_name: str
23
+ metric_type: str
24
+ timeout: float | None
25
+ schema: CollectionSchema | None
26
+ index_params: IndexParams | None
17
27
 
18
28
 
19
29
  class FetchKwargs(TypedDict, total=False):
@@ -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.dev6
3
+ Version: 0.2.6.dev8
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.dev6.dist-info/METADATA,sha256=b28GiuNopBEWlnMn7RmUNnS5MbiuFIU_wGXEGuH6gCY,14085
2
- fabricatio-0.2.6.dev6.dist-info/WHEEL,sha256=mDFV3bKFgwlxLHvOsPqpR9up9dUKYzsUQNKBdkW5c08,94
3
- fabricatio-0.2.6.dev6.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
1
+ fabricatio-0.2.6.dev8.dist-info/METADATA,sha256=teU7Pg274Y7dl9-wIMG_T4ueJrjmeg9HX60Z1I680uI,14085
2
+ fabricatio-0.2.6.dev8.dist-info/WHEEL,sha256=mDFV3bKFgwlxLHvOsPqpR9up9dUKYzsUQNKBdkW5c08,94
3
+ fabricatio-0.2.6.dev8.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
4
4
  fabricatio/actions/article.py,sha256=LfIWnbFYB9e3Bq2YDPk1geWDbJTq7zCitLtpFhAhYHM,4563
5
5
  fabricatio/actions/output.py,sha256=KSSLvEvXsA10ACN2mbqGo98QwKLVUAoMUJNKYk6HhGc,645
6
- fabricatio/actions/rag.py,sha256=GpT7YlqOYznZyaT-6Y84_33HtZGT-5s71ZK8iroQA9g,813
6
+ fabricatio/actions/rag.py,sha256=Qe3WMcSsTqcH_DXN1Jd0sFz8tJ19_Eqez6pesC6t9UM,1006
7
7
  fabricatio/capabilities/correct.py,sha256=0BYhjo9WrLwKsXQR8bTPvdQITbrMs7RX1xpzhuQt_yY,5222
8
8
  fabricatio/capabilities/propose.py,sha256=y3kge5g6bb8HYuV8e9h4MdqOMTlsfAIZpqE_cagWPTY,1593
9
- fabricatio/capabilities/rag.py,sha256=VcFusFHb5Lz58kfd14JIrCh78uJkAs47SS6-bIGkwFo,15789
9
+ fabricatio/capabilities/rag.py,sha256=RGP3VswqIBCK5TJxIUw-LuWL_9K2-QvVSSz1O7EU-4A,16459
10
10
  fabricatio/capabilities/rating.py,sha256=R9otyZVE2E3kKxrOCTZMeesBCPbC-fSb7bXgZPMQzfU,14406
11
11
  fabricatio/capabilities/review.py,sha256=XYzpSnFCT9HS2XytQT8HDgV4SjXehexoJgucZFMx6P8,11102
12
12
  fabricatio/capabilities/task.py,sha256=MBiDyC3oHwTbTiLiGyqUEVfVGSN42lU03ndeapTpyjQ,4609
13
- fabricatio/config.py,sha256=f3B_Mwhc4mGEdECG4EqcxGww0Eu7KhCAwPXXJlHf1a8,16635
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=kV4mZgLjpZEXlna9IRLl2OwbUw3dkCHkcviDG4Cr9ow,8589
21
21
  fabricatio/models/events.py,sha256=QvlnS8FEELg6KNabcJMeh2GV_y0ZBzKOPphcteKYWYU,4183
22
- fabricatio/models/extra.py,sha256=nFB9WSqHVs6V7OVhLfRLnzFObaOJldRcrYdsC93ZCDY,13787
22
+ fabricatio/models/extra.py,sha256=5FJmU_jH8MBNgOX5b35l_4iOwgz4HCoByZ873mmC0-4,26314
23
23
  fabricatio/models/generic.py,sha256=IdPJMf3qxZFq8yqd6OuAYKfCM0wBlJkozgxvxQZVEEc,14025
24
- fabricatio/models/kwargs_types.py,sha256=XiXuHLWttp8MjNqQr1WdMFYVKVZdsa5Vg0nHLhNKCyA,4627
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
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
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=0xarl48qmXpp_BFtTKkg0cm6aLNGDviWyY3gPKMOL9Y,1826304
41
- fabricatio-0.2.6.dev6.data/scripts/tdown.exe,sha256=sfJBs8p8BKKChg9vZPVR7PNnNgv9hqUm3uZ3558Zxqk,3397632
42
- fabricatio-0.2.6.dev6.dist-info/RECORD,,
40
+ fabricatio/_rust.cp39-win_amd64.pyd,sha256=0v1LHLSeVy_BcO4ssj64nGq_ksd78f6oLjtEvTVQFuQ,1830400
41
+ fabricatio-0.2.6.dev8.data/scripts/tdown.exe,sha256=NWvImTrrUptePGBwlr5wJ7bnR-rl1QocamTTutb3axI,3405824
42
+ fabricatio-0.2.6.dev8.dist-info/RECORD,,