fabricatio 0.2.6.dev4__tar.gz → 0.2.6.dev5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/PKG-INFO +1 -1
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/make_diary/diary.py +1 -1
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/pyproject.toml +1 -1
- fabricatio-0.2.6.dev5/python/fabricatio/capabilities/covalidate.py +160 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/capabilities/task.py +2 -2
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/config.py +18 -15
- fabricatio-0.2.6.dev5/python/fabricatio/models/action.py +219 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/models/extra.py +1 -1
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/models/role.py +32 -7
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/models/usages.py +5 -4
- fabricatio-0.2.6.dev5/templates/built-in/co_validation.hbs +26 -0
- fabricatio-0.2.6.dev5/templates.tar.gz +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/uv.lock +1 -1
- fabricatio-0.2.6.dev4/python/fabricatio/models/action.py +0 -158
- fabricatio-0.2.6.dev4/templates.tar.gz +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/.github/workflows/build-package.yaml +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/.github/workflows/ruff.yaml +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/.github/workflows/tests.yaml +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/.gitignore +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/.python-version +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/Cargo.lock +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/Cargo.toml +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/LICENSE +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/Makefile +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/README.md +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/correct/correct.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/correct/correct_loop.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/extract_and_review/.gitignore +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/extract_and_review/extract_and_review.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/extract_article/extract.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/llm_usages/llm_usage.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/make_a_rating/rating.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/make_diary/commits.json +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/minor/hello_fabricatio.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/minor/write_a_poem.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/propose_task/propose.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/reviewer/review.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/search_bibtex/.gitignore +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/search_bibtex/search.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/simple_chat/chat.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/simple_rag/simple_rag.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/task_handle/handle_task.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/write_outline/.gitignore +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/write_outline/write_outline.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/examples/write_outline/write_outline_corrected.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/__init__.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/_rust.pyi +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/_rust_instances.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/actions/article.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/actions/output.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/actions/rag.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/capabilities/correct.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/capabilities/propose.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/capabilities/rag.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/capabilities/rating.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/capabilities/review.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/core.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/decorators.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/fs/__init__.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/fs/curd.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/fs/readers.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/journal.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/models/events.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/models/generic.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/models/kwargs_types.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/models/task.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/models/tool.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/models/utils.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/parser.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/py.typed +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/toolboxes/__init__.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/toolboxes/arithmetic.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/toolboxes/fs.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/workflows/articles.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/python/fabricatio/workflows/rag.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/src/bib_tools.rs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/src/hash.rs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/src/hbs_helpers.rs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/src/lib.rs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/src/templates.rs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/binary-exploitation-ctf-solver.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/claude-xml.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/clean-up-code.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/correct.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/create_json_obj.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/cryptography-ctf-solver.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/dependencies.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/document-the-code.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/draft_rating_criteria.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/draft_rating_manual.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/draft_rating_weights_klee.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/draft_tool_usage_code.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/extract_criteria_from_reasons.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/extract_reasons_from_examples.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/find-security-vulnerabilities.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/fix-bugs.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/generic_string.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/improve-performance.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/liststr.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/make_choice.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/make_judgment.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/pathstr.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/rate_fine_grind.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/refactor.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/refined_query.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/retrieved_display.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/reverse-engineering-ctf-solver.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/review_string.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/task_briefing.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/web-ctf-solver.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/write-git-commit.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/write-github-pull-request.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/templates/built-in/write-github-readme.hbs +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/tests/test_config.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/tests/test_models/test_action.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/tests/test_models/test_advanced.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/tests/test_models/test_generic.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/tests/test_models/test_role.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/tests/test_models/test_task.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/tests/test_models/test_tool.py +0 -0
- {fabricatio-0.2.6.dev4 → fabricatio-0.2.6.dev5}/tests/test_models/test_usages.py +0 -0
@@ -57,7 +57,7 @@ class DumpText(Action):
|
|
57
57
|
["dump the text contained in `text_to_dump` to a file", "only return the path of the written file"]
|
58
58
|
)
|
59
59
|
|
60
|
-
path = await self.
|
60
|
+
path = await self.handle_fine_grind(
|
61
61
|
task_input,
|
62
62
|
{"text_to_dump": dump_text},
|
63
63
|
)
|
@@ -0,0 +1,160 @@
|
|
1
|
+
"""Co-validation capability for LLMs."""
|
2
|
+
|
3
|
+
from asyncio import gather
|
4
|
+
from typing import Callable, List, Optional, Union, Unpack, overload
|
5
|
+
|
6
|
+
from fabricatio import TEMPLATE_MANAGER
|
7
|
+
from fabricatio.config import configs
|
8
|
+
from fabricatio.journal import logger
|
9
|
+
from fabricatio.models.kwargs_types import GenerateKwargs
|
10
|
+
from fabricatio.models.usages import LLMUsage
|
11
|
+
|
12
|
+
|
13
|
+
class CoValidate(LLMUsage):
|
14
|
+
"""Class that represents a co-validation capability using multiple LLMs.
|
15
|
+
|
16
|
+
This class provides methods to validate responses by attempting multiple approaches:
|
17
|
+
1. Using the primary LLM to generate a response
|
18
|
+
2. Using a secondary (co-) model to refine responses that fail validation
|
19
|
+
3. Trying multiple times if needed
|
20
|
+
"""
|
21
|
+
|
22
|
+
@overload
|
23
|
+
async def aask_covalidate[T](
|
24
|
+
self,
|
25
|
+
question: str,
|
26
|
+
validator: Callable[[str], T | None],
|
27
|
+
co_model: Optional[str] = None,
|
28
|
+
co_temperature: Optional[float] = None,
|
29
|
+
co_top_p: Optional[float] = None,
|
30
|
+
co_max_tokens: Optional[int] = None,
|
31
|
+
max_validations: int = 2,
|
32
|
+
default: None = None,
|
33
|
+
**kwargs: Unpack[GenerateKwargs],
|
34
|
+
) -> T | None: ...
|
35
|
+
|
36
|
+
@overload
|
37
|
+
async def aask_covalidate[T](
|
38
|
+
self,
|
39
|
+
question: str,
|
40
|
+
validator: Callable[[str], T | None],
|
41
|
+
co_model: Optional[str] = None,
|
42
|
+
co_temperature: Optional[float] = None,
|
43
|
+
co_top_p: Optional[float] = None,
|
44
|
+
co_max_tokens: Optional[int] = None,
|
45
|
+
max_validations: int = 2,
|
46
|
+
default: T = ...,
|
47
|
+
**kwargs: Unpack[GenerateKwargs],
|
48
|
+
) -> T: ...
|
49
|
+
|
50
|
+
@overload
|
51
|
+
async def aask_covalidate[T](
|
52
|
+
self,
|
53
|
+
question: List[str],
|
54
|
+
validator: Callable[[str], T | None],
|
55
|
+
co_model: Optional[str] = None,
|
56
|
+
co_temperature: Optional[float] = None,
|
57
|
+
co_top_p: Optional[float] = None,
|
58
|
+
co_max_tokens: Optional[int] = None,
|
59
|
+
max_validations: int = 2,
|
60
|
+
default: None = None,
|
61
|
+
**kwargs: Unpack[GenerateKwargs],
|
62
|
+
) -> List[T | None]: ...
|
63
|
+
|
64
|
+
@overload
|
65
|
+
async def aask_covalidate[T](
|
66
|
+
self,
|
67
|
+
question: List[str],
|
68
|
+
validator: Callable[[str], T | None],
|
69
|
+
co_model: Optional[str] = None,
|
70
|
+
co_temperature: Optional[float] = None,
|
71
|
+
co_top_p: Optional[float] = None,
|
72
|
+
co_max_tokens: Optional[int] = None,
|
73
|
+
max_validations: int = 2,
|
74
|
+
default: T = ...,
|
75
|
+
**kwargs: Unpack[GenerateKwargs],
|
76
|
+
) -> List[T]: ...
|
77
|
+
|
78
|
+
async def aask_covalidate[T](
|
79
|
+
self,
|
80
|
+
question: Union[str, List[str]],
|
81
|
+
validator: Callable[[str], T | None],
|
82
|
+
co_model: Optional[str] = None,
|
83
|
+
co_temperature: Optional[float] = None,
|
84
|
+
co_top_p: Optional[float] = None,
|
85
|
+
co_max_tokens: Optional[int] = None,
|
86
|
+
max_validations: int = 2,
|
87
|
+
default: Optional[T] = None,
|
88
|
+
**kwargs: Unpack[GenerateKwargs],
|
89
|
+
) -> Union[T | None, List[T | None]]:
|
90
|
+
"""Ask the LLM with co-validation to obtain a validated response.
|
91
|
+
|
92
|
+
This method attempts to generate a response that passes validation using two approaches:
|
93
|
+
1. First, it asks the primary LLM using the original question
|
94
|
+
2. If validation fails, it uses a secondary (co-) model with a template to improve the response
|
95
|
+
3. The process repeats up to max_validations times
|
96
|
+
|
97
|
+
Args:
|
98
|
+
question: String question or list of questions to ask
|
99
|
+
validator: Function that validates responses, returns result or None if invalid
|
100
|
+
co_model: Optional model name for the co-validator
|
101
|
+
co_temperature: Optional temperature setting for the co-validator
|
102
|
+
co_top_p: Optional top_p setting for the co-validator
|
103
|
+
co_max_tokens: Optional maximum tokens for the co-validator response
|
104
|
+
max_validations: Maximum number of validation attempts
|
105
|
+
default: Default value to return if validation fails
|
106
|
+
**kwargs: Additional keyword arguments passed to aask method
|
107
|
+
|
108
|
+
Returns:
|
109
|
+
The validated result (T) or default if validation fails.
|
110
|
+
If input is a list of questions, returns a list of results.
|
111
|
+
"""
|
112
|
+
|
113
|
+
async def validate_single_question(q: str) -> Optional[T]:
|
114
|
+
"""Process a single question with validation attempts."""
|
115
|
+
validation_kwargs = kwargs.copy()
|
116
|
+
|
117
|
+
for lap in range(max_validations):
|
118
|
+
try:
|
119
|
+
# First attempt: direct question to primary model
|
120
|
+
response = await self.aask(question=q, **validation_kwargs)
|
121
|
+
if response and (validated := validator(response)):
|
122
|
+
logger.debug(f"Successfully validated the primary response at {lap}th attempt.")
|
123
|
+
return validated
|
124
|
+
|
125
|
+
# Second attempt: use co-model with validation template
|
126
|
+
co_prompt = TEMPLATE_MANAGER.render_template(
|
127
|
+
configs.templates.co_validation_template,
|
128
|
+
{"original_q": q, "original_a": response},
|
129
|
+
)
|
130
|
+
co_response = await self.aask(
|
131
|
+
question=co_prompt,
|
132
|
+
model=co_model,
|
133
|
+
temperature=co_temperature,
|
134
|
+
top_p=co_top_p,
|
135
|
+
max_tokens=co_max_tokens,
|
136
|
+
)
|
137
|
+
|
138
|
+
if co_response and (validated := validator(co_response)):
|
139
|
+
logger.debug(f"Successfully validated the co-response at {lap}th attempt.")
|
140
|
+
return validated
|
141
|
+
|
142
|
+
except Exception as e: # noqa: BLE001
|
143
|
+
logger.error(f"Error during validation: \n{e}")
|
144
|
+
break
|
145
|
+
|
146
|
+
# Disable caching for subsequent attempts
|
147
|
+
if not validation_kwargs.get("no_cache"):
|
148
|
+
validation_kwargs["no_cache"] = True
|
149
|
+
logger.debug("Disabled cache for the next attempt")
|
150
|
+
|
151
|
+
if default is None:
|
152
|
+
logger.error(f"Failed to validate the response after {max_validations} attempts.")
|
153
|
+
return default
|
154
|
+
|
155
|
+
# Handle single question or list of questions
|
156
|
+
if isinstance(question, str):
|
157
|
+
return await validate_single_question(question)
|
158
|
+
|
159
|
+
# Process multiple questions in parallel
|
160
|
+
return await gather(*[validate_single_question(q) for q in question])
|
@@ -84,7 +84,7 @@ class HandleTask(WithBriefing, ToolBoxUsage):
|
|
84
84
|
**self.prepend(cast(Dict[str, Any], kwargs)),
|
85
85
|
)
|
86
86
|
|
87
|
-
async def
|
87
|
+
async def handle_fine_grind(
|
88
88
|
self,
|
89
89
|
task: Task,
|
90
90
|
data: Dict[str, Any],
|
@@ -110,4 +110,4 @@ class HandleTask(WithBriefing, ToolBoxUsage):
|
|
110
110
|
|
111
111
|
async def handle(self, task: Task, data: Dict[str, Any], **kwargs: Unpack[ValidateKwargs]) -> Optional[Tuple]:
|
112
112
|
"""Asynchronously handles a task based on a given task object and parameters."""
|
113
|
-
return await self.
|
113
|
+
return await self.handle_fine_grind(task, data, **kwargs)
|
@@ -48,37 +48,37 @@ class LLMConfig(BaseModel):
|
|
48
48
|
"""
|
49
49
|
|
50
50
|
model_config = ConfigDict(use_attribute_docstrings=True)
|
51
|
-
api_endpoint: HttpUrl = Field(default=HttpUrl("https://api.openai.com"))
|
51
|
+
api_endpoint: Optional[HttpUrl] = Field(default=HttpUrl("https://api.openai.com"))
|
52
52
|
"""OpenAI API Endpoint."""
|
53
53
|
|
54
|
-
api_key: SecretStr = Field(default=SecretStr(""))
|
54
|
+
api_key: Optional[SecretStr] = Field(default=SecretStr("sk-setyourkey"))
|
55
55
|
"""OpenAI API key. Empty by default for security reasons, should be set before use."""
|
56
56
|
|
57
|
-
timeout: PositiveInt = Field(default=300)
|
57
|
+
timeout: Optional[PositiveInt] = Field(default=300)
|
58
58
|
"""The timeout of the LLM model in seconds. Default is 300 seconds as per request."""
|
59
59
|
|
60
|
-
max_retries: PositiveInt = Field(default=3)
|
60
|
+
max_retries: Optional[PositiveInt] = Field(default=3)
|
61
61
|
"""The maximum number of retries. Default is 3 retries."""
|
62
62
|
|
63
|
-
model: str = Field(default="gpt-3.5-turbo")
|
63
|
+
model: Optional[str] = Field(default="gpt-3.5-turbo")
|
64
64
|
"""The LLM model name. Set to 'gpt-3.5-turbo' as per request."""
|
65
65
|
|
66
|
-
temperature: NonNegativeFloat = Field(default=1.0)
|
66
|
+
temperature: Optional[NonNegativeFloat] = Field(default=1.0)
|
67
67
|
"""The temperature of the LLM model. Controls randomness in generation. Set to 1.0 as per request."""
|
68
68
|
|
69
|
-
stop_sign: str | List[str] = Field(
|
69
|
+
stop_sign: Optional[str | List[str]] = Field(default="")
|
70
70
|
"""The stop sign of the LLM model. No default stop sign specified."""
|
71
71
|
|
72
|
-
top_p: NonNegativeFloat = Field(default=0.35)
|
72
|
+
top_p: Optional[NonNegativeFloat] = Field(default=0.35)
|
73
73
|
"""The top p of the LLM model. Controls diversity via nucleus sampling. Set to 0.35 as per request."""
|
74
74
|
|
75
|
-
generation_count: PositiveInt = Field(default=1)
|
75
|
+
generation_count: Optional[PositiveInt] = Field(default=1)
|
76
76
|
"""The number of generations to generate. Default is 1."""
|
77
77
|
|
78
|
-
stream: bool = Field(default=False)
|
78
|
+
stream: Optional[bool] = Field(default=False)
|
79
79
|
"""Whether to stream the LLM model's response. Default is False."""
|
80
80
|
|
81
|
-
max_tokens: PositiveInt = Field(default=8192)
|
81
|
+
max_tokens: Optional[PositiveInt] = Field(default=8192)
|
82
82
|
"""The maximum number of tokens to generate. Set to 8192 as per request."""
|
83
83
|
|
84
84
|
rpm: Optional[PositiveInt] = Field(default=100)
|
@@ -93,7 +93,7 @@ class EmbeddingConfig(BaseModel):
|
|
93
93
|
|
94
94
|
model_config = ConfigDict(use_attribute_docstrings=True)
|
95
95
|
|
96
|
-
model: str = Field(default="text-embedding-ada-002")
|
96
|
+
model: Optional[str] = Field(default="text-embedding-ada-002")
|
97
97
|
"""The embedding model name. """
|
98
98
|
|
99
99
|
dimensions: Optional[PositiveInt] = Field(default=None)
|
@@ -102,10 +102,10 @@ class EmbeddingConfig(BaseModel):
|
|
102
102
|
timeout: Optional[PositiveInt] = Field(default=None)
|
103
103
|
"""The timeout of the embedding model in seconds."""
|
104
104
|
|
105
|
-
max_sequence_length: PositiveInt = Field(default=8192)
|
105
|
+
max_sequence_length: Optional[PositiveInt] = Field(default=8192)
|
106
106
|
"""The maximum sequence length of the embedding model. Default is 8192 as per request."""
|
107
107
|
|
108
|
-
caching: bool = Field(default=False)
|
108
|
+
caching: Optional[bool] = Field(default=False)
|
109
109
|
"""Whether to cache the embedding. Default is False."""
|
110
110
|
|
111
111
|
api_endpoint: Optional[HttpUrl] = None
|
@@ -232,6 +232,9 @@ class TemplateConfig(BaseModel):
|
|
232
232
|
correct_template: str = Field(default="correct")
|
233
233
|
"""The name of the correct template which will be used to correct a string."""
|
234
234
|
|
235
|
+
co_validation_template: str = Field(default="co_validation")
|
236
|
+
"""The name of the co-validation template which will be used to co-validate a string."""
|
237
|
+
|
235
238
|
|
236
239
|
class MagikaConfig(BaseModel):
|
237
240
|
"""Magika configuration class."""
|
@@ -272,7 +275,7 @@ class RagConfig(BaseModel):
|
|
272
275
|
|
273
276
|
model_config = ConfigDict(use_attribute_docstrings=True)
|
274
277
|
|
275
|
-
milvus_uri: HttpUrl = Field(default=HttpUrl("http://localhost:19530"))
|
278
|
+
milvus_uri: Optional[HttpUrl] = Field(default=HttpUrl("http://localhost:19530"))
|
276
279
|
"""The URI of the Milvus server."""
|
277
280
|
milvus_timeout: Optional[PositiveFloat] = Field(default=None)
|
278
281
|
"""The timeout of the Milvus server."""
|
@@ -0,0 +1,219 @@
|
|
1
|
+
"""Module that contains the classes for actions and workflows.
|
2
|
+
|
3
|
+
This module defines the Action and WorkFlow classes, which are used for
|
4
|
+
creating and executing sequences of actions in a task-based context.
|
5
|
+
"""
|
6
|
+
|
7
|
+
import traceback
|
8
|
+
from abc import abstractmethod
|
9
|
+
from asyncio import Queue, create_task
|
10
|
+
from typing import Any, Dict, Self, Tuple, Type, Union, final
|
11
|
+
|
12
|
+
from fabricatio.capabilities.correct import Correct
|
13
|
+
from fabricatio.capabilities.covalidate import CoValidate
|
14
|
+
from fabricatio.capabilities.task import HandleTask, ProposeTask
|
15
|
+
from fabricatio.journal import logger
|
16
|
+
from fabricatio.models.generic import WithBriefing
|
17
|
+
from fabricatio.models.task import Task
|
18
|
+
from fabricatio.models.usages import ToolBoxUsage
|
19
|
+
from pydantic import Field, PrivateAttr
|
20
|
+
|
21
|
+
|
22
|
+
class Action(HandleTask, ProposeTask, Correct, CoValidate):
|
23
|
+
"""Class that represents an action to be executed in a workflow.
|
24
|
+
|
25
|
+
Actions are the atomic units of work in a workflow. Each action performs
|
26
|
+
a specific operation and can modify the shared context data.
|
27
|
+
"""
|
28
|
+
|
29
|
+
name: str = Field(default="")
|
30
|
+
"""The name of the action."""
|
31
|
+
|
32
|
+
description: str = Field(default="")
|
33
|
+
"""The description of the action."""
|
34
|
+
|
35
|
+
personality: str = Field(default="")
|
36
|
+
"""The personality traits or context for the action executor."""
|
37
|
+
|
38
|
+
output_key: str = Field(default="")
|
39
|
+
"""The key used to store this action's output in the context dictionary."""
|
40
|
+
|
41
|
+
@final
|
42
|
+
def model_post_init(self, __context: Any) -> None:
|
43
|
+
"""Initialize the action by setting default name and description if not provided.
|
44
|
+
|
45
|
+
Args:
|
46
|
+
__context: The context to be used for initialization.
|
47
|
+
"""
|
48
|
+
self.name = self.name or self.__class__.__name__
|
49
|
+
self.description = self.description or self.__class__.__doc__ or ""
|
50
|
+
|
51
|
+
@abstractmethod
|
52
|
+
async def _execute(self, **cxt) -> Any:
|
53
|
+
"""Execute the action logic with the provided context arguments.
|
54
|
+
|
55
|
+
This method must be implemented by subclasses to define the actual behavior.
|
56
|
+
|
57
|
+
Args:
|
58
|
+
**cxt: The context dictionary containing input and output data.
|
59
|
+
|
60
|
+
Returns:
|
61
|
+
Any: The result of the action execution.
|
62
|
+
"""
|
63
|
+
pass
|
64
|
+
|
65
|
+
@final
|
66
|
+
async def act(self, cxt: Dict[str, Any]) -> Dict[str, Any]:
|
67
|
+
"""Perform the action and update the context with results.
|
68
|
+
|
69
|
+
Args:
|
70
|
+
cxt: The context dictionary containing input and output data.
|
71
|
+
|
72
|
+
Returns:
|
73
|
+
Dict[str, Any]: The updated context dictionary.
|
74
|
+
"""
|
75
|
+
ret = await self._execute(**cxt)
|
76
|
+
|
77
|
+
if self.output_key:
|
78
|
+
logger.debug(f"Setting output: {self.output_key}")
|
79
|
+
cxt[self.output_key] = ret
|
80
|
+
|
81
|
+
return cxt
|
82
|
+
|
83
|
+
@property
|
84
|
+
def briefing(self) -> str:
|
85
|
+
"""Return a formatted description of the action including personality context if available.
|
86
|
+
|
87
|
+
Returns:
|
88
|
+
str: Formatted briefing text with personality and action description.
|
89
|
+
"""
|
90
|
+
if self.personality:
|
91
|
+
return f"## Your personality: \n{self.personality}\n# The action you are going to perform: \n{super().briefing}"
|
92
|
+
return f"# The action you are going to perform: \n{super().briefing}"
|
93
|
+
|
94
|
+
|
95
|
+
class WorkFlow(WithBriefing, ToolBoxUsage):
|
96
|
+
"""Class that represents a sequence of actions to be executed for a task.
|
97
|
+
|
98
|
+
A workflow manages the execution of multiple actions in sequence, passing
|
99
|
+
a shared context between them and handling task lifecycle events.
|
100
|
+
"""
|
101
|
+
|
102
|
+
_context: Queue[Dict[str, Any]] = PrivateAttr(default_factory=lambda: Queue(maxsize=1))
|
103
|
+
"""Queue for storing the workflow execution context."""
|
104
|
+
|
105
|
+
_instances: Tuple[Action, ...] = PrivateAttr(default_factory=tuple)
|
106
|
+
"""Instantiated action objects to be executed in this workflow."""
|
107
|
+
|
108
|
+
steps: Tuple[Union[Type[Action], Action], ...] = Field(...)
|
109
|
+
"""The sequence of actions to be executed, can be action classes or instances."""
|
110
|
+
|
111
|
+
task_input_key: str = Field(default="task_input")
|
112
|
+
"""Key used to store the input task in the context dictionary."""
|
113
|
+
|
114
|
+
task_output_key: str = Field(default="task_output")
|
115
|
+
"""Key used to extract the final result from the context dictionary."""
|
116
|
+
|
117
|
+
extra_init_context: Dict[str, Any] = Field(default_factory=dict, frozen=True)
|
118
|
+
"""Additional initial context values to be included at workflow start."""
|
119
|
+
|
120
|
+
def model_post_init(self, __context: Any) -> None:
|
121
|
+
"""Initialize the workflow by instantiating any action classes.
|
122
|
+
|
123
|
+
Args:
|
124
|
+
__context: The context to be used for initialization.
|
125
|
+
"""
|
126
|
+
# Convert any action classes to instances
|
127
|
+
self._instances = tuple(step if isinstance(step, Action) else step() for step in self.steps)
|
128
|
+
|
129
|
+
def inject_personality(self, personality: str) -> Self:
|
130
|
+
"""Set the personality for all actions that don't have one defined.
|
131
|
+
|
132
|
+
Args:
|
133
|
+
personality: The personality text to inject.
|
134
|
+
|
135
|
+
Returns:
|
136
|
+
Self: The workflow instance for method chaining.
|
137
|
+
"""
|
138
|
+
for action in filter(lambda a: not a.personality, self._instances):
|
139
|
+
action.personality = personality
|
140
|
+
return self
|
141
|
+
|
142
|
+
async def serve(self, task: Task) -> None:
|
143
|
+
"""Execute the workflow to fulfill the given task.
|
144
|
+
|
145
|
+
This method manages the complete lifecycle of processing a task through
|
146
|
+
the workflow's sequence of actions.
|
147
|
+
|
148
|
+
Args:
|
149
|
+
task: The task to be processed.
|
150
|
+
"""
|
151
|
+
await task.start()
|
152
|
+
await self._init_context(task)
|
153
|
+
|
154
|
+
current_action = None
|
155
|
+
try:
|
156
|
+
# Process each action in sequence
|
157
|
+
for step in self._instances:
|
158
|
+
current_action = step.name
|
159
|
+
logger.debug(f"Executing step: {current_action}")
|
160
|
+
|
161
|
+
# Get current context and execute action
|
162
|
+
context = await self._context.get()
|
163
|
+
act_task = create_task(step.act(context))
|
164
|
+
|
165
|
+
# Handle task cancellation
|
166
|
+
if task.is_cancelled():
|
167
|
+
act_task.cancel(f"Cancelled by task: {task.name}")
|
168
|
+
break
|
169
|
+
|
170
|
+
# Update context with modified values
|
171
|
+
modified_ctx = await act_task
|
172
|
+
await self._context.put(modified_ctx)
|
173
|
+
|
174
|
+
logger.info(f"Finished executing workflow: {self.name}")
|
175
|
+
|
176
|
+
# Get final context and extract result
|
177
|
+
final_ctx = await self._context.get()
|
178
|
+
result = final_ctx.get(self.task_output_key)
|
179
|
+
|
180
|
+
if self.task_output_key not in final_ctx:
|
181
|
+
logger.warning(
|
182
|
+
f"Task output key: {self.task_output_key} not found in the context, None will be returned. "
|
183
|
+
f"You can check if `Action.output_key` is set the same as `WorkFlow.task_output_key`."
|
184
|
+
)
|
185
|
+
|
186
|
+
await task.finish(result)
|
187
|
+
|
188
|
+
except RuntimeError as e:
|
189
|
+
logger.error(f"Error during task: {current_action} execution: {e}")
|
190
|
+
logger.error(traceback.format_exc())
|
191
|
+
await task.fail()
|
192
|
+
|
193
|
+
async def _init_context[T](self, task: Task[T]) -> None:
|
194
|
+
"""Initialize the context dictionary for workflow execution.
|
195
|
+
|
196
|
+
Args:
|
197
|
+
task: The task being served by this workflow.
|
198
|
+
"""
|
199
|
+
logger.debug(f"Initializing context for workflow: {self.name}")
|
200
|
+
initial_context = {self.task_input_key: task, **dict(self.extra_init_context)}
|
201
|
+
await self._context.put(initial_context)
|
202
|
+
|
203
|
+
def steps_fallback_to_self(self) -> Self:
|
204
|
+
"""Configure all steps to use this workflow's configuration as fallback.
|
205
|
+
|
206
|
+
Returns:
|
207
|
+
Self: The workflow instance for method chaining.
|
208
|
+
"""
|
209
|
+
self.hold_to(self._instances)
|
210
|
+
return self
|
211
|
+
|
212
|
+
def steps_supply_tools_from_self(self) -> Self:
|
213
|
+
"""Provide this workflow's tools to all steps in the workflow.
|
214
|
+
|
215
|
+
Returns:
|
216
|
+
Self: The workflow instance for method chaining.
|
217
|
+
"""
|
218
|
+
self.provide_tools_to(self._instances)
|
219
|
+
return self
|
@@ -26,7 +26,7 @@ class Figure(Base):
|
|
26
26
|
"""The caption accompanying the figure, summarizing its main points and academic value."""
|
27
27
|
|
28
28
|
figure_path: str
|
29
|
-
"""The
|
29
|
+
"""The exact path to the figure file, must exist in the file system, SHALL never be a PLACEHOLDER."""
|
30
30
|
|
31
31
|
|
32
32
|
class Highlightings(Base):
|
@@ -1,8 +1,9 @@
|
|
1
|
-
"""Module that contains the Role class."""
|
1
|
+
"""Module that contains the Role class for managing workflows and their event registrations."""
|
2
2
|
|
3
3
|
from typing import Any, Self, Set
|
4
4
|
|
5
5
|
from fabricatio.capabilities.correct import Correct
|
6
|
+
from fabricatio.capabilities.covalidate import CoValidate
|
6
7
|
from fabricatio.capabilities.task import HandleTask, ProposeTask
|
7
8
|
from fabricatio.core import env
|
8
9
|
from fabricatio.journal import logger
|
@@ -12,20 +13,37 @@ from fabricatio.models.tool import ToolBox
|
|
12
13
|
from pydantic import Field
|
13
14
|
|
14
15
|
|
15
|
-
class Role(ProposeTask, HandleTask, Correct):
|
16
|
-
"""Class that represents a role with a registry of events and workflows.
|
16
|
+
class Role(ProposeTask, HandleTask, Correct, CoValidate):
|
17
|
+
"""Class that represents a role with a registry of events and workflows.
|
18
|
+
|
19
|
+
A Role serves as a container for workflows, managing their registration to events
|
20
|
+
and providing them with shared configuration like tools and personality.
|
21
|
+
|
22
|
+
Attributes:
|
23
|
+
registry: Mapping of events to workflows that handle them
|
24
|
+
toolboxes: Set of toolboxes available to this role and its workflows
|
25
|
+
"""
|
17
26
|
|
18
27
|
registry: dict[Event | str, WorkFlow] = Field(default_factory=dict)
|
19
|
-
"""
|
28
|
+
"""The registry of events and workflows."""
|
20
29
|
|
21
30
|
toolboxes: Set[ToolBox] = Field(default_factory=set)
|
31
|
+
"""Collection of tools available to this role."""
|
22
32
|
|
23
33
|
def model_post_init(self, __context: Any) -> None:
|
24
|
-
"""
|
34
|
+
"""Initialize the role by resolving configurations and registering workflows.
|
35
|
+
|
36
|
+
Args:
|
37
|
+
__context: The context used for initialization
|
38
|
+
"""
|
25
39
|
self.resolve_configuration().register_workflows()
|
26
40
|
|
27
41
|
def register_workflows(self) -> Self:
|
28
|
-
"""Register
|
42
|
+
"""Register each workflow in the registry to its corresponding event in the event bus.
|
43
|
+
|
44
|
+
Returns:
|
45
|
+
Self: The role instance for method chaining
|
46
|
+
"""
|
29
47
|
for event, workflow in self.registry.items():
|
30
48
|
logger.debug(
|
31
49
|
f"Registering workflow: `{workflow.name}` for event: `{Event.instantiate_from(event).collapse()}`"
|
@@ -34,7 +52,14 @@ class Role(ProposeTask, HandleTask, Correct):
|
|
34
52
|
return self
|
35
53
|
|
36
54
|
def resolve_configuration(self) -> Self:
|
37
|
-
"""
|
55
|
+
"""Apply role-level configuration to all workflows in the registry.
|
56
|
+
|
57
|
+
This includes setting up fallback configurations, injecting personality traits,
|
58
|
+
and providing tool access to workflows and their steps.
|
59
|
+
|
60
|
+
Returns:
|
61
|
+
Self: The role instance for method chaining
|
62
|
+
"""
|
38
63
|
for workflow in self.registry.values():
|
39
64
|
logger.debug(f"Resolving config for workflow: `{workflow.name}`")
|
40
65
|
(
|
@@ -213,7 +213,7 @@ class LLMUsage(ScopedConfig):
|
|
213
213
|
self,
|
214
214
|
question: str,
|
215
215
|
validator: Callable[[str], T | None],
|
216
|
-
default: T
|
216
|
+
default: T = ...,
|
217
217
|
max_validations: PositiveInt = 2,
|
218
218
|
**kwargs: Unpack[GenerateKwargs],
|
219
219
|
) -> T: ...
|
@@ -222,7 +222,7 @@ class LLMUsage(ScopedConfig):
|
|
222
222
|
self,
|
223
223
|
question: List[str],
|
224
224
|
validator: Callable[[str], T | None],
|
225
|
-
default: T
|
225
|
+
default: T = ...,
|
226
226
|
max_validations: PositiveInt = 2,
|
227
227
|
**kwargs: Unpack[GenerateKwargs],
|
228
228
|
) -> List[T]: ...
|
@@ -277,8 +277,9 @@ class LLMUsage(ScopedConfig):
|
|
277
277
|
except Exception as e: # noqa: BLE001
|
278
278
|
logger.error(f"Error during validation: \n{e}")
|
279
279
|
break
|
280
|
-
kwargs
|
281
|
-
|
280
|
+
if not kwargs.get("no_cache"):
|
281
|
+
kwargs["no_cache"] = True
|
282
|
+
logger.debug("Closed the cache for the next attempt")
|
282
283
|
if default is None:
|
283
284
|
logger.error(f"Failed to validate the response after {max_validations} attempts.")
|
284
285
|
return default
|
@@ -0,0 +1,26 @@
|
|
1
|
+
{{!-- Co-validation template to help improve responses that failed validation --}}
|
2
|
+
--- VALIDATION TASK ---
|
3
|
+
|
4
|
+
You are an expert validation assistant. Your task is to improve a response that failed to meet validation requirements.
|
5
|
+
|
6
|
+
--- ORIGINAL QUESTION ---
|
7
|
+
|
8
|
+
{{original_q}}
|
9
|
+
|
10
|
+
--- FAILED RESPONSE ---
|
11
|
+
|
12
|
+
{{original_a}}
|
13
|
+
|
14
|
+
--- INSTRUCTIONS ---
|
15
|
+
|
16
|
+
Create a new response that will pass validation by:
|
17
|
+
- Following all instructions in the original question precisely
|
18
|
+
- Using correct formatting (especially for structured data/JSON/code)
|
19
|
+
- Fixing logical errors or inconsistencies from the previous response
|
20
|
+
- Ensuring completeness and accuracy
|
21
|
+
|
22
|
+
--- IMPORTANT NOTES ---
|
23
|
+
- Provide ONLY the improved response, which **MUST** fit the Original question's Validation requirements
|
24
|
+
- Do NOT include explanations or commentary
|
25
|
+
- Do NOT add headers or prefixes to your response
|
26
|
+
|
Binary file
|