hamtaa-texttools 1.1.16__tar.gz → 1.1.18__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.
- {hamtaa_texttools-1.1.16/hamtaa_texttools.egg-info → hamtaa_texttools-1.1.18}/PKG-INFO +3 -2
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/README.md +1 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18/hamtaa_texttools.egg-info}/PKG-INFO +3 -2
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/hamtaa_texttools.egg-info/SOURCES.txt +9 -7
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/pyproject.toml +2 -1
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/tests/test_all_async_tools.py +11 -1
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/tests/test_all_tools.py +14 -2
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/tests/test_output_validation.py +2 -2
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/__init__.py +1 -1
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/batch/batch_runner.py +75 -64
- {hamtaa_texttools-1.1.16/texttools/tools → hamtaa_texttools-1.1.18/texttools}/internals/async_operator.py +96 -48
- hamtaa_texttools-1.1.18/texttools/internals/exceptions.py +28 -0
- {hamtaa_texttools-1.1.16/texttools/tools → hamtaa_texttools-1.1.18/texttools}/internals/models.py +63 -56
- hamtaa_texttools-1.1.18/texttools/internals/prompt_loader.py +80 -0
- {hamtaa_texttools-1.1.16/texttools/tools → hamtaa_texttools-1.1.18/texttools}/internals/sync_operator.py +92 -47
- hamtaa_texttools-1.1.18/texttools/prompts/propositionize.yaml +15 -0
- hamtaa_texttools-1.1.18/texttools/tools/async_tools.py +1110 -0
- hamtaa_texttools-1.1.18/texttools/tools/sync_tools.py +1110 -0
- hamtaa_texttools-1.1.16/texttools/tools/async_tools.py +0 -804
- hamtaa_texttools-1.1.16/texttools/tools/internals/prompt_loader.py +0 -56
- hamtaa_texttools-1.1.16/texttools/tools/sync_tools.py +0 -804
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/LICENSE +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/MANIFEST.in +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/hamtaa_texttools.egg-info/dependency_links.txt +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/hamtaa_texttools.egg-info/requires.txt +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/hamtaa_texttools.egg-info/top_level.txt +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/setup.cfg +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/batch/batch_config.py +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/batch/internals/batch_manager.py +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/batch/internals/utils.py +0 -0
- {hamtaa_texttools-1.1.16/texttools/tools → hamtaa_texttools-1.1.18/texttools}/internals/formatters.py +0 -0
- {hamtaa_texttools-1.1.16/texttools/tools → hamtaa_texttools-1.1.18/texttools}/internals/operator_utils.py +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/README.md +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/categorize.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/detect_entity.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/extract_entities.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/extract_keywords.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/is_question.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/merge_questions.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/rewrite.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/run_custom.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/subject_to_question.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/summarize.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/text_to_question.yaml +0 -0
- {hamtaa_texttools-1.1.16 → hamtaa_texttools-1.1.18}/texttools/prompts/translate.yaml +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: hamtaa-texttools
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.18
|
|
4
4
|
Summary: A high-level NLP toolkit built on top of modern LLMs.
|
|
5
|
-
Author-email: Tohidi <the.mohammad.tohidi@gmail.com>, Montazer <montazerh82@gmail.com>, Givechi <mohamad.m.givechi@gmail.com>, MoosaviNejad <erfanmoosavi84@gmail.com>
|
|
5
|
+
Author-email: Tohidi <the.mohammad.tohidi@gmail.com>, Montazer <montazerh82@gmail.com>, Givechi <mohamad.m.givechi@gmail.com>, MoosaviNejad <erfanmoosavi84@gmail.com>, Zareshahi <a.zareshahi1377@gmail.com>
|
|
6
6
|
License: MIT License
|
|
7
7
|
|
|
8
8
|
Copyright (c) 2025 Hamtaa
|
|
@@ -60,6 +60,7 @@ Each tool is designed to work with structured outputs (JSON / Pydantic).
|
|
|
60
60
|
- **`subject_to_question()`** - Generates questions about a specific subject
|
|
61
61
|
- **`summarize()`** - Text summarization
|
|
62
62
|
- **`translate()`** - Text translation between languages
|
|
63
|
+
- **`propositionize()`** - Convert text to atomic independence meaningful sentences
|
|
63
64
|
- **`run_custom()`** - Allows users to define a custom tool with an arbitrary BaseModel
|
|
64
65
|
|
|
65
66
|
---
|
|
@@ -25,6 +25,7 @@ Each tool is designed to work with structured outputs (JSON / Pydantic).
|
|
|
25
25
|
- **`subject_to_question()`** - Generates questions about a specific subject
|
|
26
26
|
- **`summarize()`** - Text summarization
|
|
27
27
|
- **`translate()`** - Text translation between languages
|
|
28
|
+
- **`propositionize()`** - Convert text to atomic independence meaningful sentences
|
|
28
29
|
- **`run_custom()`** - Allows users to define a custom tool with an arbitrary BaseModel
|
|
29
30
|
|
|
30
31
|
---
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: hamtaa-texttools
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.18
|
|
4
4
|
Summary: A high-level NLP toolkit built on top of modern LLMs.
|
|
5
|
-
Author-email: Tohidi <the.mohammad.tohidi@gmail.com>, Montazer <montazerh82@gmail.com>, Givechi <mohamad.m.givechi@gmail.com>, MoosaviNejad <erfanmoosavi84@gmail.com>
|
|
5
|
+
Author-email: Tohidi <the.mohammad.tohidi@gmail.com>, Montazer <montazerh82@gmail.com>, Givechi <mohamad.m.givechi@gmail.com>, MoosaviNejad <erfanmoosavi84@gmail.com>, Zareshahi <a.zareshahi1377@gmail.com>
|
|
6
6
|
License: MIT License
|
|
7
7
|
|
|
8
8
|
Copyright (c) 2025 Hamtaa
|
|
@@ -60,6 +60,7 @@ Each tool is designed to work with structured outputs (JSON / Pydantic).
|
|
|
60
60
|
- **`subject_to_question()`** - Generates questions about a specific subject
|
|
61
61
|
- **`summarize()`** - Text summarization
|
|
62
62
|
- **`translate()`** - Text translation between languages
|
|
63
|
+
- **`propositionize()`** - Convert text to atomic independence meaningful sentences
|
|
63
64
|
- **`run_custom()`** - Allows users to define a custom tool with an arbitrary BaseModel
|
|
64
65
|
|
|
65
66
|
---
|
|
@@ -15,6 +15,13 @@ texttools/batch/batch_config.py
|
|
|
15
15
|
texttools/batch/batch_runner.py
|
|
16
16
|
texttools/batch/internals/batch_manager.py
|
|
17
17
|
texttools/batch/internals/utils.py
|
|
18
|
+
texttools/internals/async_operator.py
|
|
19
|
+
texttools/internals/exceptions.py
|
|
20
|
+
texttools/internals/formatters.py
|
|
21
|
+
texttools/internals/models.py
|
|
22
|
+
texttools/internals/operator_utils.py
|
|
23
|
+
texttools/internals/prompt_loader.py
|
|
24
|
+
texttools/internals/sync_operator.py
|
|
18
25
|
texttools/prompts/README.md
|
|
19
26
|
texttools/prompts/categorize.yaml
|
|
20
27
|
texttools/prompts/detect_entity.yaml
|
|
@@ -22,6 +29,7 @@ texttools/prompts/extract_entities.yaml
|
|
|
22
29
|
texttools/prompts/extract_keywords.yaml
|
|
23
30
|
texttools/prompts/is_question.yaml
|
|
24
31
|
texttools/prompts/merge_questions.yaml
|
|
32
|
+
texttools/prompts/propositionize.yaml
|
|
25
33
|
texttools/prompts/rewrite.yaml
|
|
26
34
|
texttools/prompts/run_custom.yaml
|
|
27
35
|
texttools/prompts/subject_to_question.yaml
|
|
@@ -29,10 +37,4 @@ texttools/prompts/summarize.yaml
|
|
|
29
37
|
texttools/prompts/text_to_question.yaml
|
|
30
38
|
texttools/prompts/translate.yaml
|
|
31
39
|
texttools/tools/async_tools.py
|
|
32
|
-
texttools/tools/sync_tools.py
|
|
33
|
-
texttools/tools/internals/async_operator.py
|
|
34
|
-
texttools/tools/internals/formatters.py
|
|
35
|
-
texttools/tools/internals/models.py
|
|
36
|
-
texttools/tools/internals/operator_utils.py
|
|
37
|
-
texttools/tools/internals/prompt_loader.py
|
|
38
|
-
texttools/tools/internals/sync_operator.py
|
|
40
|
+
texttools/tools/sync_tools.py
|
|
@@ -4,12 +4,13 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "hamtaa-texttools"
|
|
7
|
-
version = "1.1.
|
|
7
|
+
version = "1.1.18"
|
|
8
8
|
authors = [
|
|
9
9
|
{ name = "Tohidi", email = "the.mohammad.tohidi@gmail.com" },
|
|
10
10
|
{ name = "Montazer", email = "montazerh82@gmail.com" },
|
|
11
11
|
{ name = "Givechi", email = "mohamad.m.givechi@gmail.com" },
|
|
12
12
|
{ name = "MoosaviNejad", email = "erfanmoosavi84@gmail.com" },
|
|
13
|
+
{ name = "Zareshahi", email = "a.zareshahi1377@gmail.com" },
|
|
13
14
|
]
|
|
14
15
|
description = "A high-level NLP toolkit built on top of modern LLMs."
|
|
15
16
|
readme = "README.md"
|
|
@@ -21,7 +21,10 @@ t = AsyncTheTool(client=client, model=MODEL)
|
|
|
21
21
|
|
|
22
22
|
async def main():
|
|
23
23
|
category_task = t.categorize(
|
|
24
|
-
"سلام حالت چطوره؟",
|
|
24
|
+
"سلام حالت چطوره؟",
|
|
25
|
+
categories=["هیچکدام", "دینی", "فلسفه"],
|
|
26
|
+
logprobs=True,
|
|
27
|
+
top_logprobs=-1,
|
|
25
28
|
)
|
|
26
29
|
keywords_task = t.extract_keywords("Tomorrow, we will be dead by the car crash")
|
|
27
30
|
entities_task = t.extract_entities("We will be dead by the car crash")
|
|
@@ -40,6 +43,10 @@ async def main():
|
|
|
40
43
|
questions_task = t.subject_to_question("Friendship", 3)
|
|
41
44
|
summary_task = t.summarize("Tomorrow, we will be dead by the car crash")
|
|
42
45
|
translation_task = t.translate("سلام حالت چطوره؟", target_language="English")
|
|
46
|
+
propositionize_task = t.propositionize(
|
|
47
|
+
"جنگ جهانی دوم در سال ۱۹۳۹ آغاز شد و آلمان به لهستان حمله کرد.",
|
|
48
|
+
output_lang="Persian",
|
|
49
|
+
)
|
|
43
50
|
(
|
|
44
51
|
category,
|
|
45
52
|
keywords,
|
|
@@ -51,6 +58,7 @@ async def main():
|
|
|
51
58
|
questions,
|
|
52
59
|
summary,
|
|
53
60
|
translation,
|
|
61
|
+
propositionize,
|
|
54
62
|
) = await asyncio.gather(
|
|
55
63
|
category_task,
|
|
56
64
|
keywords_task,
|
|
@@ -62,6 +70,7 @@ async def main():
|
|
|
62
70
|
questions_task,
|
|
63
71
|
summary_task,
|
|
64
72
|
translation_task,
|
|
73
|
+
propositionize_task,
|
|
65
74
|
)
|
|
66
75
|
|
|
67
76
|
for tool_output in (
|
|
@@ -75,6 +84,7 @@ async def main():
|
|
|
75
84
|
questions,
|
|
76
85
|
summary,
|
|
77
86
|
translation,
|
|
87
|
+
propositionize,
|
|
78
88
|
):
|
|
79
89
|
print(repr(tool_output))
|
|
80
90
|
|
|
@@ -19,7 +19,12 @@ client = OpenAI(base_url=BASE_URL, api_key=API_KEY)
|
|
|
19
19
|
t = TheTool(client=client, model=MODEL)
|
|
20
20
|
|
|
21
21
|
# Categorizer: list mode
|
|
22
|
-
category = t.categorize(
|
|
22
|
+
category = t.categorize(
|
|
23
|
+
"سلام حالت چطوره؟",
|
|
24
|
+
categories=["هیچکدام", "دینی", "فلسفه"],
|
|
25
|
+
logprobs=True,
|
|
26
|
+
top_logprobs=-1,
|
|
27
|
+
)
|
|
23
28
|
print(repr(category))
|
|
24
29
|
|
|
25
30
|
# Categorizer: tree mode
|
|
@@ -46,7 +51,7 @@ keywords = t.extract_keywords(
|
|
|
46
51
|
print(repr(keywords))
|
|
47
52
|
|
|
48
53
|
# NER Extractor
|
|
49
|
-
entities = t.extract_entities("We will be dead by the car crash")
|
|
54
|
+
entities = t.extract_entities("We will be dead by the car crash", with_analysis=True)
|
|
50
55
|
print(repr(entities))
|
|
51
56
|
|
|
52
57
|
|
|
@@ -84,6 +89,13 @@ print(repr(summary))
|
|
|
84
89
|
translation = t.translate("سلام حالت چطوره؟", target_language="English")
|
|
85
90
|
print(repr(translation))
|
|
86
91
|
|
|
92
|
+
# propositionize
|
|
93
|
+
propositionize = t.propositionize(
|
|
94
|
+
"جنگ جهانی دوم در سال ۱۹۳۹ آغاز شد و آلمان به لهستان حمله کرد.",
|
|
95
|
+
output_lang="Persian",
|
|
96
|
+
)
|
|
97
|
+
print(repr(propositionize))
|
|
98
|
+
|
|
87
99
|
|
|
88
100
|
# Custom tool
|
|
89
101
|
class Student(BaseModel):
|
|
@@ -2,6 +2,6 @@ from .batch.batch_runner import BatchJobRunner
|
|
|
2
2
|
from .batch.batch_config import BatchConfig
|
|
3
3
|
from .tools.sync_tools import TheTool
|
|
4
4
|
from .tools.async_tools import AsyncTheTool
|
|
5
|
-
from .
|
|
5
|
+
from .internals.models import CategoryTree
|
|
6
6
|
|
|
7
7
|
__all__ = ["TheTool", "AsyncTheTool", "BatchJobRunner", "BatchConfig", "CategoryTree"]
|
|
@@ -11,7 +11,8 @@ from pydantic import BaseModel
|
|
|
11
11
|
|
|
12
12
|
from texttools.batch.internals.batch_manager import BatchManager
|
|
13
13
|
from texttools.batch.batch_config import BatchConfig
|
|
14
|
-
from texttools.
|
|
14
|
+
from texttools.internals.models import StrOutput
|
|
15
|
+
from texttools.internals.exceptions import TextToolsError, ConfigurationError
|
|
15
16
|
|
|
16
17
|
# Base Model type for output models
|
|
17
18
|
T = TypeVar("T", bound=BaseModel)
|
|
@@ -27,22 +28,26 @@ class BatchJobRunner:
|
|
|
27
28
|
def __init__(
|
|
28
29
|
self, config: BatchConfig = BatchConfig(), output_model: Type[T] = StrOutput
|
|
29
30
|
):
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
31
|
+
try:
|
|
32
|
+
self._config = config
|
|
33
|
+
self._system_prompt = config.system_prompt
|
|
34
|
+
self._job_name = config.job_name
|
|
35
|
+
self._input_data_path = config.input_data_path
|
|
36
|
+
self._output_data_filename = config.output_data_filename
|
|
37
|
+
self._model = config.model
|
|
38
|
+
self._output_model = output_model
|
|
39
|
+
self._manager = self._init_manager()
|
|
40
|
+
self._data = self._load_data()
|
|
41
|
+
self._parts: list[list[dict[str, Any]]] = []
|
|
42
|
+
# Map part index to job name
|
|
43
|
+
self._part_idx_to_job_name: dict[int, str] = {}
|
|
44
|
+
# Track retry attempts per part
|
|
45
|
+
self._part_attempts: dict[int, int] = {}
|
|
46
|
+
self._partition_data()
|
|
47
|
+
Path(self._config.BASE_OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
|
|
48
|
+
|
|
49
|
+
except Exception as e:
|
|
50
|
+
raise ConfigurationError(f"Batch runner initialization failed: {e}")
|
|
46
51
|
|
|
47
52
|
def _init_manager(self) -> BatchManager:
|
|
48
53
|
load_dotenv()
|
|
@@ -162,56 +167,62 @@ class BatchJobRunner:
|
|
|
162
167
|
|
|
163
168
|
Submits jobs, monitors progress, handles retries, and saves results.
|
|
164
169
|
"""
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
f"Job completed. Fetching results for part {part_idx + 1}..."
|
|
179
|
-
)
|
|
180
|
-
output_data, log = self._manager.fetch_results(
|
|
181
|
-
job_name=job_name, remove_cache=False
|
|
182
|
-
)
|
|
183
|
-
output_data = self._config.import_function(output_data)
|
|
184
|
-
self._save_results(output_data, log, part_idx)
|
|
185
|
-
logger.info(f"Fetched and saved results for part {part_idx + 1}.")
|
|
186
|
-
finished_this_round.append(part_idx)
|
|
187
|
-
elif status == "failed":
|
|
188
|
-
attempt = self._part_attempts.get(part_idx, 0) + 1
|
|
189
|
-
self._part_attempts[part_idx] = attempt
|
|
190
|
-
if attempt <= self._config.max_retries:
|
|
170
|
+
try:
|
|
171
|
+
# Submit all jobs up-front for concurrent execution
|
|
172
|
+
self._submit_all_jobs()
|
|
173
|
+
pending_parts: set[int] = set(self._part_idx_to_job_name.keys())
|
|
174
|
+
logger.info(f"Pending parts: {sorted(pending_parts)}")
|
|
175
|
+
# Polling loop
|
|
176
|
+
while pending_parts:
|
|
177
|
+
finished_this_round: list[int] = []
|
|
178
|
+
for part_idx in list(pending_parts):
|
|
179
|
+
job_name = self._part_idx_to_job_name[part_idx]
|
|
180
|
+
status = self._manager.check_status(job_name=job_name)
|
|
181
|
+
logger.info(f"Status for {job_name}: {status}")
|
|
182
|
+
if status == "completed":
|
|
191
183
|
logger.info(
|
|
192
|
-
f"Job
|
|
184
|
+
f"Job completed. Fetching results for part {part_idx + 1}..."
|
|
193
185
|
)
|
|
194
|
-
self._manager.
|
|
195
|
-
|
|
196
|
-
payload = self._to_manager_payload(self._parts[part_idx])
|
|
197
|
-
new_job_name = (
|
|
198
|
-
f"{self._job_name}_part_{part_idx + 1}_retry_{attempt}"
|
|
186
|
+
output_data, log = self._manager.fetch_results(
|
|
187
|
+
job_name=job_name, remove_cache=False
|
|
199
188
|
)
|
|
200
|
-
self.
|
|
201
|
-
self.
|
|
202
|
-
else:
|
|
189
|
+
output_data = self._config.import_function(output_data)
|
|
190
|
+
self._save_results(output_data, log, part_idx)
|
|
203
191
|
logger.info(
|
|
204
|
-
f"
|
|
192
|
+
f"Fetched and saved results for part {part_idx + 1}."
|
|
205
193
|
)
|
|
206
194
|
finished_this_round.append(part_idx)
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
195
|
+
elif status == "failed":
|
|
196
|
+
attempt = self._part_attempts.get(part_idx, 0) + 1
|
|
197
|
+
self._part_attempts[part_idx] = attempt
|
|
198
|
+
if attempt <= self._config.max_retries:
|
|
199
|
+
logger.info(
|
|
200
|
+
f"Job {job_name} failed (attempt {attempt}). Retrying after short backoff..."
|
|
201
|
+
)
|
|
202
|
+
self._manager._clear_state(job_name)
|
|
203
|
+
time.sleep(10)
|
|
204
|
+
payload = self._to_manager_payload(self._parts[part_idx])
|
|
205
|
+
new_job_name = (
|
|
206
|
+
f"{self._job_name}_part_{part_idx + 1}_retry_{attempt}"
|
|
207
|
+
)
|
|
208
|
+
self._manager.start(payload, job_name=new_job_name)
|
|
209
|
+
self._part_idx_to_job_name[part_idx] = new_job_name
|
|
210
|
+
else:
|
|
211
|
+
logger.info(
|
|
212
|
+
f"Job {job_name} failed after {attempt - 1} retries. Marking as failed."
|
|
213
|
+
)
|
|
214
|
+
finished_this_round.append(part_idx)
|
|
215
|
+
else:
|
|
216
|
+
# Still running or queued
|
|
217
|
+
continue
|
|
218
|
+
# Remove finished parts
|
|
219
|
+
for part_idx in finished_this_round:
|
|
220
|
+
pending_parts.discard(part_idx)
|
|
221
|
+
if pending_parts:
|
|
222
|
+
logger.info(
|
|
223
|
+
f"Waiting {self._config.poll_interval_seconds}s before next status check for parts: {sorted(pending_parts)}"
|
|
224
|
+
)
|
|
225
|
+
time.sleep(self._config.poll_interval_seconds)
|
|
226
|
+
|
|
227
|
+
except Exception as e:
|
|
228
|
+
raise TextToolsError(f"Batch job execution failed: {e}")
|
|
@@ -5,10 +5,16 @@ import logging
|
|
|
5
5
|
from openai import AsyncOpenAI
|
|
6
6
|
from pydantic import BaseModel
|
|
7
7
|
|
|
8
|
-
from texttools.
|
|
9
|
-
from texttools.
|
|
10
|
-
from texttools.
|
|
11
|
-
from texttools.
|
|
8
|
+
from texttools.internals.models import ToolOutput
|
|
9
|
+
from texttools.internals.operator_utils import OperatorUtils
|
|
10
|
+
from texttools.internals.formatters import Formatter
|
|
11
|
+
from texttools.internals.prompt_loader import PromptLoader
|
|
12
|
+
from texttools.internals.exceptions import (
|
|
13
|
+
TextToolsError,
|
|
14
|
+
LLMError,
|
|
15
|
+
ValidationError,
|
|
16
|
+
PromptError,
|
|
17
|
+
)
|
|
12
18
|
|
|
13
19
|
# Base Model type for output models
|
|
14
20
|
T = TypeVar("T", bound=BaseModel)
|
|
@@ -35,15 +41,33 @@ class AsyncOperator:
|
|
|
35
41
|
Calls OpenAI API for analysis using the configured prompt template.
|
|
36
42
|
Returns the analyzed content as a string.
|
|
37
43
|
"""
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
44
|
+
try:
|
|
45
|
+
analyze_prompt = prompt_configs["analyze_template"]
|
|
46
|
+
|
|
47
|
+
if not analyze_prompt:
|
|
48
|
+
raise PromptError("Analyze template is empty")
|
|
49
|
+
|
|
50
|
+
analyze_message = [OperatorUtils.build_user_message(analyze_prompt)]
|
|
51
|
+
completion = await self._client.chat.completions.create(
|
|
52
|
+
model=self._model,
|
|
53
|
+
messages=analyze_message,
|
|
54
|
+
temperature=temperature,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
if not completion.choices:
|
|
58
|
+
raise LLMError("No choices returned from LLM")
|
|
59
|
+
|
|
60
|
+
analysis = completion.choices[0].message.content.strip()
|
|
61
|
+
|
|
62
|
+
if not analysis:
|
|
63
|
+
raise LLMError("Empty analysis response")
|
|
64
|
+
|
|
65
|
+
return analysis.strip()
|
|
66
|
+
|
|
67
|
+
except Exception as e:
|
|
68
|
+
if isinstance(e, (PromptError, LLMError)):
|
|
69
|
+
raise
|
|
70
|
+
raise LLMError(f"Analysis failed: {e}")
|
|
47
71
|
|
|
48
72
|
async def _parse_completion(
|
|
49
73
|
self,
|
|
@@ -58,21 +82,37 @@ class AsyncOperator:
|
|
|
58
82
|
Parses a chat completion using OpenAI's structured output format.
|
|
59
83
|
Returns both the parsed object and the raw completion for logprobs.
|
|
60
84
|
"""
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
85
|
+
try:
|
|
86
|
+
request_kwargs = {
|
|
87
|
+
"model": self._model,
|
|
88
|
+
"messages": message,
|
|
89
|
+
"response_format": output_model,
|
|
90
|
+
"temperature": temperature,
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if logprobs:
|
|
94
|
+
request_kwargs["logprobs"] = True
|
|
95
|
+
request_kwargs["top_logprobs"] = top_logprobs
|
|
96
|
+
if priority:
|
|
97
|
+
request_kwargs["extra_body"] = {"priority": priority}
|
|
98
|
+
completion = await self._client.beta.chat.completions.parse(
|
|
99
|
+
**request_kwargs
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
if not completion.choices:
|
|
103
|
+
raise LLMError("No choices returned from LLM")
|
|
104
|
+
|
|
105
|
+
parsed = completion.choices[0].message.parsed
|
|
106
|
+
|
|
107
|
+
if not parsed:
|
|
108
|
+
raise LLMError("Failed to parse LLM response")
|
|
109
|
+
|
|
110
|
+
return parsed, completion
|
|
111
|
+
|
|
112
|
+
except Exception as e:
|
|
113
|
+
if isinstance(e, LLMError):
|
|
114
|
+
raise
|
|
115
|
+
raise LLMError(f"Completion failed: {e}")
|
|
76
116
|
|
|
77
117
|
async def run(
|
|
78
118
|
self,
|
|
@@ -94,13 +134,13 @@ class AsyncOperator:
|
|
|
94
134
|
**extra_kwargs,
|
|
95
135
|
) -> ToolOutput:
|
|
96
136
|
"""
|
|
97
|
-
Execute the
|
|
137
|
+
Execute the LLM pipeline with the given input text. (Async)
|
|
98
138
|
"""
|
|
99
|
-
prompt_loader = PromptLoader()
|
|
100
|
-
formatter = Formatter()
|
|
101
|
-
output = ToolOutput()
|
|
102
|
-
|
|
103
139
|
try:
|
|
140
|
+
prompt_loader = PromptLoader()
|
|
141
|
+
formatter = Formatter()
|
|
142
|
+
output = ToolOutput()
|
|
143
|
+
|
|
104
144
|
# Prompt configs contain two keys: main_template and analyze template, both are string
|
|
105
145
|
prompt_configs = prompt_loader.load(
|
|
106
146
|
prompt_file=prompt_file,
|
|
@@ -139,6 +179,9 @@ class AsyncOperator:
|
|
|
139
179
|
|
|
140
180
|
messages = formatter.user_merge_format(messages)
|
|
141
181
|
|
|
182
|
+
if logprobs and (not isinstance(top_logprobs, int) or top_logprobs < 2):
|
|
183
|
+
raise ValueError("top_logprobs should be an integer greater than 1")
|
|
184
|
+
|
|
142
185
|
parsed, completion = await self._parse_completion(
|
|
143
186
|
messages, output_model, temperature, logprobs, top_logprobs, priority
|
|
144
187
|
)
|
|
@@ -147,6 +190,15 @@ class AsyncOperator:
|
|
|
147
190
|
|
|
148
191
|
# Retry logic if validation fails
|
|
149
192
|
if validator and not validator(output.result):
|
|
193
|
+
if (
|
|
194
|
+
not isinstance(max_validation_retries, int)
|
|
195
|
+
or max_validation_retries < 1
|
|
196
|
+
):
|
|
197
|
+
raise ValueError(
|
|
198
|
+
"max_validation_retries should be a positive integer"
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
succeeded = False
|
|
150
202
|
for attempt in range(max_validation_retries):
|
|
151
203
|
logger.warning(
|
|
152
204
|
f"Validation failed, retrying for the {attempt + 1} time."
|
|
@@ -154,6 +206,7 @@ class AsyncOperator:
|
|
|
154
206
|
|
|
155
207
|
# Generate new temperature for retry
|
|
156
208
|
retry_temperature = OperatorUtils.get_retry_temp(temperature)
|
|
209
|
+
|
|
157
210
|
try:
|
|
158
211
|
parsed, completion = await self._parse_completion(
|
|
159
212
|
messages,
|
|
@@ -161,28 +214,23 @@ class AsyncOperator:
|
|
|
161
214
|
retry_temperature,
|
|
162
215
|
logprobs,
|
|
163
216
|
top_logprobs,
|
|
217
|
+
priority=priority,
|
|
164
218
|
)
|
|
165
219
|
|
|
166
220
|
output.result = parsed.result
|
|
167
221
|
|
|
168
222
|
# Check if retry was successful
|
|
169
223
|
if validator(output.result):
|
|
170
|
-
|
|
171
|
-
f"Validation passed on retry attempt {attempt + 1}"
|
|
172
|
-
)
|
|
224
|
+
succeeded = True
|
|
173
225
|
break
|
|
174
|
-
else:
|
|
175
|
-
logger.warning(
|
|
176
|
-
f"Validation still failing after retry attempt {attempt + 1}"
|
|
177
|
-
)
|
|
178
226
|
|
|
179
|
-
except
|
|
227
|
+
except LLMError as e:
|
|
180
228
|
logger.error(f"Retry attempt {attempt + 1} failed: {e}")
|
|
181
|
-
# Continue to next retry attempt if this one fails
|
|
182
229
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
230
|
+
if not succeeded:
|
|
231
|
+
raise ValidationError(
|
|
232
|
+
f"Validation failed after {max_validation_retries} retries"
|
|
233
|
+
)
|
|
186
234
|
|
|
187
235
|
if logprobs:
|
|
188
236
|
output.logprobs = OperatorUtils.extract_logprobs(completion)
|
|
@@ -194,7 +242,7 @@ class AsyncOperator:
|
|
|
194
242
|
|
|
195
243
|
return output
|
|
196
244
|
|
|
245
|
+
except (PromptError, LLMError, ValidationError):
|
|
246
|
+
raise
|
|
197
247
|
except Exception as e:
|
|
198
|
-
|
|
199
|
-
output.errors.append(str(e))
|
|
200
|
-
return output
|
|
248
|
+
raise TextToolsError(f"Unexpected error in operator: {e}")
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
class TextToolsError(Exception):
|
|
2
|
+
"""Base exception for all TextTools errors."""
|
|
3
|
+
|
|
4
|
+
pass
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class PromptError(TextToolsError):
|
|
8
|
+
"""Errors related to prompt loading and formatting."""
|
|
9
|
+
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class LLMError(TextToolsError):
|
|
14
|
+
"""Errors from LLM API calls."""
|
|
15
|
+
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ValidationError(TextToolsError):
|
|
20
|
+
"""Errors from output validation."""
|
|
21
|
+
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ConfigurationError(TextToolsError):
|
|
26
|
+
"""Errors from misconfiguration."""
|
|
27
|
+
|
|
28
|
+
pass
|