hamtaa-texttools 1.0.3__py3-none-any.whl → 1.0.5__py3-none-any.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.
Potentially problematic release.
This version of hamtaa-texttools might be problematic. Click here for more details.
- {hamtaa_texttools-1.0.3.dist-info → hamtaa_texttools-1.0.5.dist-info}/METADATA +192 -141
- hamtaa_texttools-1.0.5.dist-info/RECORD +30 -0
- {hamtaa_texttools-1.0.3.dist-info → hamtaa_texttools-1.0.5.dist-info}/licenses/LICENSE +20 -20
- {hamtaa_texttools-1.0.3.dist-info → hamtaa_texttools-1.0.5.dist-info}/top_level.txt +0 -0
- texttools/__init__.py +9 -9
- texttools/batch/__init__.py +4 -4
- texttools/batch/batch_manager.py +240 -240
- texttools/batch/batch_runner.py +212 -212
- texttools/formatters/base_formatter.py +33 -33
- texttools/formatters/{user_merge_formatter/user_merge_formatter.py → user_merge_formatter.py} +30 -30
- texttools/prompts/README.md +31 -31
- texttools/prompts/categorizer.yaml +28 -31
- texttools/prompts/custom_tool.yaml +7 -0
- texttools/prompts/keyword_extractor.yaml +18 -14
- texttools/prompts/ner_extractor.yaml +20 -21
- texttools/prompts/question_detector.yaml +13 -14
- texttools/prompts/question_generator.yaml +19 -22
- texttools/prompts/question_merger.yaml +45 -48
- texttools/prompts/rewriter.yaml +111 -0
- texttools/prompts/subject_question_generator.yaml +22 -26
- texttools/prompts/summarizer.yaml +13 -11
- texttools/prompts/translator.yaml +14 -14
- texttools/tools/__init__.py +4 -4
- texttools/tools/async_the_tool.py +277 -263
- texttools/tools/internals/async_operator.py +297 -288
- texttools/tools/internals/operator.py +295 -306
- texttools/tools/internals/output_models.py +52 -62
- texttools/tools/internals/prompt_loader.py +76 -82
- texttools/tools/the_tool.py +501 -400
- hamtaa_texttools-1.0.3.dist-info/RECORD +0 -29
- texttools/prompts/question_rewriter.yaml +0 -46
- {hamtaa_texttools-1.0.3.dist-info → hamtaa_texttools-1.0.5.dist-info}/WHEEL +0 -0
texttools/batch/batch_runner.py
CHANGED
|
@@ -1,212 +1,212 @@
|
|
|
1
|
-
import json
|
|
2
|
-
import os
|
|
3
|
-
import time
|
|
4
|
-
from dataclasses import dataclass
|
|
5
|
-
from pathlib import Path
|
|
6
|
-
from typing import Any, Callable
|
|
7
|
-
|
|
8
|
-
from openai import OpenAI
|
|
9
|
-
from pydantic import BaseModel
|
|
10
|
-
|
|
11
|
-
from texttools.batch.batch_manager import SimpleBatchManager
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class Output(BaseModel):
|
|
15
|
-
output: str
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def export_data(data):
|
|
19
|
-
"""
|
|
20
|
-
Produces a structure of the following form from an initial data structure:
|
|
21
|
-
[
|
|
22
|
-
{"id": str, "content": str},...
|
|
23
|
-
]
|
|
24
|
-
"""
|
|
25
|
-
return data
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def import_data(data):
|
|
29
|
-
"""
|
|
30
|
-
Takes the output and adds and aggregates it to the original structure.
|
|
31
|
-
"""
|
|
32
|
-
return data
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
@dataclass
|
|
36
|
-
class BatchConfig:
|
|
37
|
-
"""
|
|
38
|
-
Configuration for batch job runner.
|
|
39
|
-
"""
|
|
40
|
-
|
|
41
|
-
system_prompt: str = ""
|
|
42
|
-
job_name: str = ""
|
|
43
|
-
input_data_path: str = ""
|
|
44
|
-
output_data_filename: str = ""
|
|
45
|
-
model: str = "gpt-4.1-mini"
|
|
46
|
-
MAX_BATCH_SIZE: int = 100
|
|
47
|
-
MAX_TOTAL_TOKENS: int = 2000000
|
|
48
|
-
CHARS_PER_TOKEN: float = 2.7
|
|
49
|
-
PROMPT_TOKEN_MULTIPLIER: int = 1000
|
|
50
|
-
BASE_OUTPUT_DIR: str = "Data/batch_entity_result"
|
|
51
|
-
import_function: Callable = import_data
|
|
52
|
-
export_function: Callable = export_data
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
class BatchJobRunner:
|
|
56
|
-
"""
|
|
57
|
-
Orchestrates the execution of batched LLM processing jobs.
|
|
58
|
-
|
|
59
|
-
Handles data loading, partitioning, job execution via SimpleBatchManager,
|
|
60
|
-
and result saving. Manages the complete workflow from input data to processed outputs,
|
|
61
|
-
including retries and progress tracking across multiple batch parts.
|
|
62
|
-
"""
|
|
63
|
-
|
|
64
|
-
def __init__(
|
|
65
|
-
self, config: BatchConfig = BatchConfig(), output_model: type = Output
|
|
66
|
-
):
|
|
67
|
-
self.config = config
|
|
68
|
-
self.system_prompt = config.system_prompt
|
|
69
|
-
self.job_name = config.job_name
|
|
70
|
-
self.input_data_path = config.input_data_path
|
|
71
|
-
self.output_data_filename = config.output_data_filename
|
|
72
|
-
self.model = config.model
|
|
73
|
-
self.output_model = output_model
|
|
74
|
-
self.manager = self._init_manager()
|
|
75
|
-
self.data = self._load_data()
|
|
76
|
-
self.parts: list[list[dict[str, Any]]] = []
|
|
77
|
-
self._partition_data()
|
|
78
|
-
Path(self.config.BASE_OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
|
|
79
|
-
|
|
80
|
-
def _init_manager(self) -> SimpleBatchManager:
|
|
81
|
-
api_key = os.getenv("OPENAI_API_KEY")
|
|
82
|
-
client = OpenAI(api_key=api_key)
|
|
83
|
-
return SimpleBatchManager(
|
|
84
|
-
client=client,
|
|
85
|
-
model=self.model,
|
|
86
|
-
prompt_template=self.system_prompt,
|
|
87
|
-
output_model=self.output_model,
|
|
88
|
-
)
|
|
89
|
-
|
|
90
|
-
def _load_data(self):
|
|
91
|
-
with open(self.input_data_path, "r", encoding="utf-8") as f:
|
|
92
|
-
data = json.load(f)
|
|
93
|
-
data = self.config.export_function(data)
|
|
94
|
-
|
|
95
|
-
# Ensure data is a list of dicts with 'id' and 'content' as strings
|
|
96
|
-
if not isinstance(data, list):
|
|
97
|
-
raise ValueError(
|
|
98
|
-
'Exported data must be a list in this form: [ {"id": str, "content": str},...]'
|
|
99
|
-
)
|
|
100
|
-
for item in data:
|
|
101
|
-
if not (isinstance(item, dict) and "id" in item and "content" in item):
|
|
102
|
-
raise ValueError(
|
|
103
|
-
"Each item must be a dict with 'id' and 'content' keys."
|
|
104
|
-
)
|
|
105
|
-
if not (isinstance(item["id"], str) and isinstance(item["content"], str)):
|
|
106
|
-
raise ValueError("'id' and 'content' must be strings.")
|
|
107
|
-
return data
|
|
108
|
-
|
|
109
|
-
def _partition_data(self):
|
|
110
|
-
total_length = sum(len(item["content"]) for item in self.data)
|
|
111
|
-
prompt_length = len(self.system_prompt)
|
|
112
|
-
total = total_length + (prompt_length * len(self.data))
|
|
113
|
-
calculation = total / self.config.CHARS_PER_TOKEN
|
|
114
|
-
print(
|
|
115
|
-
f"Total chars: {total_length}, Prompt chars: {prompt_length}, Total: {total}, Tokens: {calculation}"
|
|
116
|
-
)
|
|
117
|
-
if calculation < self.config.MAX_TOTAL_TOKENS:
|
|
118
|
-
self.parts = [self.data]
|
|
119
|
-
else:
|
|
120
|
-
# Partition into chunks of MAX_BATCH_SIZE
|
|
121
|
-
self.parts = [
|
|
122
|
-
self.data[i : i + self.config.MAX_BATCH_SIZE]
|
|
123
|
-
for i in range(0, len(self.data), self.config.MAX_BATCH_SIZE)
|
|
124
|
-
]
|
|
125
|
-
print(f"Data split into {len(self.parts)} part(s)")
|
|
126
|
-
|
|
127
|
-
def run(self):
|
|
128
|
-
for idx, part in enumerate(self.parts):
|
|
129
|
-
if self._result_exists(idx):
|
|
130
|
-
print(f"Skipping part {idx + 1}: result already exists.")
|
|
131
|
-
continue
|
|
132
|
-
part_job_name = (
|
|
133
|
-
f"{self.job_name}_part_{idx + 1}"
|
|
134
|
-
if len(self.parts) > 1
|
|
135
|
-
else self.job_name
|
|
136
|
-
)
|
|
137
|
-
print(
|
|
138
|
-
f"\n--- Processing part {idx + 1}/{len(self.parts)}: {part_job_name} ---"
|
|
139
|
-
)
|
|
140
|
-
self._process_part(part, part_job_name, idx)
|
|
141
|
-
|
|
142
|
-
def _process_part(
|
|
143
|
-
self, part: list[dict[str, Any]], part_job_name: str, part_idx: int
|
|
144
|
-
):
|
|
145
|
-
while True:
|
|
146
|
-
print(f"Starting job for part: {part_job_name}")
|
|
147
|
-
self.manager.start(part, job_name=part_job_name)
|
|
148
|
-
print("Started batch job. Checking status...")
|
|
149
|
-
while True:
|
|
150
|
-
status = self.manager.check_status(job_name=part_job_name)
|
|
151
|
-
print(f"Status: {status}")
|
|
152
|
-
if status == "completed":
|
|
153
|
-
print("Job completed. Fetching results...")
|
|
154
|
-
output_data, log = self.manager.fetch_results(
|
|
155
|
-
job_name=part_job_name, remove_cache=False
|
|
156
|
-
)
|
|
157
|
-
output_data = self.config.import_function(output_data)
|
|
158
|
-
self._save_results(output_data, log, part_idx)
|
|
159
|
-
print("Fetched and saved results for this part.")
|
|
160
|
-
return
|
|
161
|
-
elif status == "failed":
|
|
162
|
-
print("Job failed. Clearing state, waiting, and retrying...")
|
|
163
|
-
self.manager._clear_state(part_job_name)
|
|
164
|
-
# Wait before retrying
|
|
165
|
-
time.sleep(10)
|
|
166
|
-
# Break inner loop to restart the job
|
|
167
|
-
break
|
|
168
|
-
else:
|
|
169
|
-
# Wait before checking again
|
|
170
|
-
time.sleep(5)
|
|
171
|
-
|
|
172
|
-
def _save_results(
|
|
173
|
-
self, output_data: list[dict[str, Any]], log: list[Any], part_idx: int
|
|
174
|
-
):
|
|
175
|
-
part_suffix = f"_part_{part_idx + 1}" if len(self.parts) > 1 else ""
|
|
176
|
-
result_path = (
|
|
177
|
-
Path(self.config.BASE_OUTPUT_DIR)
|
|
178
|
-
/ f"{Path(self.output_data_filename).stem}{part_suffix}.json"
|
|
179
|
-
)
|
|
180
|
-
if not output_data:
|
|
181
|
-
print("No output data to save. Skipping this part.")
|
|
182
|
-
return
|
|
183
|
-
else:
|
|
184
|
-
with open(result_path, "w", encoding="utf-8") as f:
|
|
185
|
-
json.dump(output_data, f, ensure_ascii=False, indent=4)
|
|
186
|
-
if log:
|
|
187
|
-
log_path = (
|
|
188
|
-
Path(self.config.BASE_OUTPUT_DIR)
|
|
189
|
-
/ f"{Path(self.output_data_filename).stem}{part_suffix}_log.json"
|
|
190
|
-
)
|
|
191
|
-
with open(log_path, "w", encoding="utf-8") as f:
|
|
192
|
-
json.dump(log, f, ensure_ascii=False, indent=4)
|
|
193
|
-
|
|
194
|
-
def _result_exists(self, part_idx: int) -> bool:
|
|
195
|
-
part_suffix = f"_part_{part_idx + 1}" if len(self.parts) > 1 else ""
|
|
196
|
-
result_path = (
|
|
197
|
-
Path(self.config.BASE_OUTPUT_DIR)
|
|
198
|
-
/ f"{Path(self.output_data_path).stem}{part_suffix}.json"
|
|
199
|
-
)
|
|
200
|
-
return result_path.exists()
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
if __name__ == "__main__":
|
|
204
|
-
print("=== Batch Job Runner ===")
|
|
205
|
-
config = BatchConfig(
|
|
206
|
-
system_prompt="",
|
|
207
|
-
job_name="job_name",
|
|
208
|
-
input_data_path="Data.json",
|
|
209
|
-
output_data_filename="output",
|
|
210
|
-
)
|
|
211
|
-
runner = BatchJobRunner(config)
|
|
212
|
-
runner.run()
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import time
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Callable
|
|
7
|
+
|
|
8
|
+
from openai import OpenAI
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
|
|
11
|
+
from texttools.batch.batch_manager import SimpleBatchManager
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Output(BaseModel):
|
|
15
|
+
output: str
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def export_data(data):
|
|
19
|
+
"""
|
|
20
|
+
Produces a structure of the following form from an initial data structure:
|
|
21
|
+
[
|
|
22
|
+
{"id": str, "content": str},...
|
|
23
|
+
]
|
|
24
|
+
"""
|
|
25
|
+
return data
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def import_data(data):
|
|
29
|
+
"""
|
|
30
|
+
Takes the output and adds and aggregates it to the original structure.
|
|
31
|
+
"""
|
|
32
|
+
return data
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class BatchConfig:
|
|
37
|
+
"""
|
|
38
|
+
Configuration for batch job runner.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
system_prompt: str = ""
|
|
42
|
+
job_name: str = ""
|
|
43
|
+
input_data_path: str = ""
|
|
44
|
+
output_data_filename: str = ""
|
|
45
|
+
model: str = "gpt-4.1-mini"
|
|
46
|
+
MAX_BATCH_SIZE: int = 100
|
|
47
|
+
MAX_TOTAL_TOKENS: int = 2000000
|
|
48
|
+
CHARS_PER_TOKEN: float = 2.7
|
|
49
|
+
PROMPT_TOKEN_MULTIPLIER: int = 1000
|
|
50
|
+
BASE_OUTPUT_DIR: str = "Data/batch_entity_result"
|
|
51
|
+
import_function: Callable = import_data
|
|
52
|
+
export_function: Callable = export_data
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class BatchJobRunner:
|
|
56
|
+
"""
|
|
57
|
+
Orchestrates the execution of batched LLM processing jobs.
|
|
58
|
+
|
|
59
|
+
Handles data loading, partitioning, job execution via SimpleBatchManager,
|
|
60
|
+
and result saving. Manages the complete workflow from input data to processed outputs,
|
|
61
|
+
including retries and progress tracking across multiple batch parts.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def __init__(
|
|
65
|
+
self, config: BatchConfig = BatchConfig(), output_model: type = Output
|
|
66
|
+
):
|
|
67
|
+
self.config = config
|
|
68
|
+
self.system_prompt = config.system_prompt
|
|
69
|
+
self.job_name = config.job_name
|
|
70
|
+
self.input_data_path = config.input_data_path
|
|
71
|
+
self.output_data_filename = config.output_data_filename
|
|
72
|
+
self.model = config.model
|
|
73
|
+
self.output_model = output_model
|
|
74
|
+
self.manager = self._init_manager()
|
|
75
|
+
self.data = self._load_data()
|
|
76
|
+
self.parts: list[list[dict[str, Any]]] = []
|
|
77
|
+
self._partition_data()
|
|
78
|
+
Path(self.config.BASE_OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
|
|
79
|
+
|
|
80
|
+
def _init_manager(self) -> SimpleBatchManager:
|
|
81
|
+
api_key = os.getenv("OPENAI_API_KEY")
|
|
82
|
+
client = OpenAI(api_key=api_key)
|
|
83
|
+
return SimpleBatchManager(
|
|
84
|
+
client=client,
|
|
85
|
+
model=self.model,
|
|
86
|
+
prompt_template=self.system_prompt,
|
|
87
|
+
output_model=self.output_model,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def _load_data(self):
|
|
91
|
+
with open(self.input_data_path, "r", encoding="utf-8") as f:
|
|
92
|
+
data = json.load(f)
|
|
93
|
+
data = self.config.export_function(data)
|
|
94
|
+
|
|
95
|
+
# Ensure data is a list of dicts with 'id' and 'content' as strings
|
|
96
|
+
if not isinstance(data, list):
|
|
97
|
+
raise ValueError(
|
|
98
|
+
'Exported data must be a list in this form: [ {"id": str, "content": str},...]'
|
|
99
|
+
)
|
|
100
|
+
for item in data:
|
|
101
|
+
if not (isinstance(item, dict) and "id" in item and "content" in item):
|
|
102
|
+
raise ValueError(
|
|
103
|
+
"Each item must be a dict with 'id' and 'content' keys."
|
|
104
|
+
)
|
|
105
|
+
if not (isinstance(item["id"], str) and isinstance(item["content"], str)):
|
|
106
|
+
raise ValueError("'id' and 'content' must be strings.")
|
|
107
|
+
return data
|
|
108
|
+
|
|
109
|
+
def _partition_data(self):
|
|
110
|
+
total_length = sum(len(item["content"]) for item in self.data)
|
|
111
|
+
prompt_length = len(self.system_prompt)
|
|
112
|
+
total = total_length + (prompt_length * len(self.data))
|
|
113
|
+
calculation = total / self.config.CHARS_PER_TOKEN
|
|
114
|
+
print(
|
|
115
|
+
f"Total chars: {total_length}, Prompt chars: {prompt_length}, Total: {total}, Tokens: {calculation}"
|
|
116
|
+
)
|
|
117
|
+
if calculation < self.config.MAX_TOTAL_TOKENS:
|
|
118
|
+
self.parts = [self.data]
|
|
119
|
+
else:
|
|
120
|
+
# Partition into chunks of MAX_BATCH_SIZE
|
|
121
|
+
self.parts = [
|
|
122
|
+
self.data[i : i + self.config.MAX_BATCH_SIZE]
|
|
123
|
+
for i in range(0, len(self.data), self.config.MAX_BATCH_SIZE)
|
|
124
|
+
]
|
|
125
|
+
print(f"Data split into {len(self.parts)} part(s)")
|
|
126
|
+
|
|
127
|
+
def run(self):
|
|
128
|
+
for idx, part in enumerate(self.parts):
|
|
129
|
+
if self._result_exists(idx):
|
|
130
|
+
print(f"Skipping part {idx + 1}: result already exists.")
|
|
131
|
+
continue
|
|
132
|
+
part_job_name = (
|
|
133
|
+
f"{self.job_name}_part_{idx + 1}"
|
|
134
|
+
if len(self.parts) > 1
|
|
135
|
+
else self.job_name
|
|
136
|
+
)
|
|
137
|
+
print(
|
|
138
|
+
f"\n--- Processing part {idx + 1}/{len(self.parts)}: {part_job_name} ---"
|
|
139
|
+
)
|
|
140
|
+
self._process_part(part, part_job_name, idx)
|
|
141
|
+
|
|
142
|
+
def _process_part(
|
|
143
|
+
self, part: list[dict[str, Any]], part_job_name: str, part_idx: int
|
|
144
|
+
):
|
|
145
|
+
while True:
|
|
146
|
+
print(f"Starting job for part: {part_job_name}")
|
|
147
|
+
self.manager.start(part, job_name=part_job_name)
|
|
148
|
+
print("Started batch job. Checking status...")
|
|
149
|
+
while True:
|
|
150
|
+
status = self.manager.check_status(job_name=part_job_name)
|
|
151
|
+
print(f"Status: {status}")
|
|
152
|
+
if status == "completed":
|
|
153
|
+
print("Job completed. Fetching results...")
|
|
154
|
+
output_data, log = self.manager.fetch_results(
|
|
155
|
+
job_name=part_job_name, remove_cache=False
|
|
156
|
+
)
|
|
157
|
+
output_data = self.config.import_function(output_data)
|
|
158
|
+
self._save_results(output_data, log, part_idx)
|
|
159
|
+
print("Fetched and saved results for this part.")
|
|
160
|
+
return
|
|
161
|
+
elif status == "failed":
|
|
162
|
+
print("Job failed. Clearing state, waiting, and retrying...")
|
|
163
|
+
self.manager._clear_state(part_job_name)
|
|
164
|
+
# Wait before retrying
|
|
165
|
+
time.sleep(10)
|
|
166
|
+
# Break inner loop to restart the job
|
|
167
|
+
break
|
|
168
|
+
else:
|
|
169
|
+
# Wait before checking again
|
|
170
|
+
time.sleep(5)
|
|
171
|
+
|
|
172
|
+
def _save_results(
|
|
173
|
+
self, output_data: list[dict[str, Any]], log: list[Any], part_idx: int
|
|
174
|
+
):
|
|
175
|
+
part_suffix = f"_part_{part_idx + 1}" if len(self.parts) > 1 else ""
|
|
176
|
+
result_path = (
|
|
177
|
+
Path(self.config.BASE_OUTPUT_DIR)
|
|
178
|
+
/ f"{Path(self.output_data_filename).stem}{part_suffix}.json"
|
|
179
|
+
)
|
|
180
|
+
if not output_data:
|
|
181
|
+
print("No output data to save. Skipping this part.")
|
|
182
|
+
return
|
|
183
|
+
else:
|
|
184
|
+
with open(result_path, "w", encoding="utf-8") as f:
|
|
185
|
+
json.dump(output_data, f, ensure_ascii=False, indent=4)
|
|
186
|
+
if log:
|
|
187
|
+
log_path = (
|
|
188
|
+
Path(self.config.BASE_OUTPUT_DIR)
|
|
189
|
+
/ f"{Path(self.output_data_filename).stem}{part_suffix}_log.json"
|
|
190
|
+
)
|
|
191
|
+
with open(log_path, "w", encoding="utf-8") as f:
|
|
192
|
+
json.dump(log, f, ensure_ascii=False, indent=4)
|
|
193
|
+
|
|
194
|
+
def _result_exists(self, part_idx: int) -> bool:
|
|
195
|
+
part_suffix = f"_part_{part_idx + 1}" if len(self.parts) > 1 else ""
|
|
196
|
+
result_path = (
|
|
197
|
+
Path(self.config.BASE_OUTPUT_DIR)
|
|
198
|
+
/ f"{Path(self.output_data_path).stem}{part_suffix}.json"
|
|
199
|
+
)
|
|
200
|
+
return result_path.exists()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
if __name__ == "__main__":
|
|
204
|
+
print("=== Batch Job Runner ===")
|
|
205
|
+
config = BatchConfig(
|
|
206
|
+
system_prompt="",
|
|
207
|
+
job_name="job_name",
|
|
208
|
+
input_data_path="Data.json",
|
|
209
|
+
output_data_filename="output",
|
|
210
|
+
)
|
|
211
|
+
runner = BatchJobRunner(config)
|
|
212
|
+
runner.run()
|
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
from abc import ABC, abstractmethod
|
|
2
|
-
from typing import Any
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
class BaseFormatter(ABC):
|
|
6
|
-
"""
|
|
7
|
-
Adapter to convert a conversation into a specific LLM API's input format.
|
|
8
|
-
|
|
9
|
-
Concrete implementations transform standardized messages (e.g., list[dict]) into the
|
|
10
|
-
exact payload required by a provider (e.g., OpenAI's message list, a single string, etc.).
|
|
11
|
-
"""
|
|
12
|
-
|
|
13
|
-
@abstractmethod
|
|
14
|
-
def format(
|
|
15
|
-
self,
|
|
16
|
-
messages: Any,
|
|
17
|
-
) -> Any:
|
|
18
|
-
"""
|
|
19
|
-
Transform the input messages into a provider-specific payload.
|
|
20
|
-
|
|
21
|
-
Args:
|
|
22
|
-
messages: The input conversation. While often a list of dicts with
|
|
23
|
-
'role' and 'content' keys, the exact type and structure may vary
|
|
24
|
-
by implementation.
|
|
25
|
-
|
|
26
|
-
Returns:
|
|
27
|
-
A payload in the format expected by the target LLM API. This could be:
|
|
28
|
-
- A list of role-content dictionaries (e.g., for OpenAI)
|
|
29
|
-
- A single formatted string (e.g., for completion-style APIs)
|
|
30
|
-
- A complex dictionary with additional parameters
|
|
31
|
-
- Any other provider-specific data structure
|
|
32
|
-
"""
|
|
33
|
-
pass
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class BaseFormatter(ABC):
|
|
6
|
+
"""
|
|
7
|
+
Adapter to convert a conversation into a specific LLM API's input format.
|
|
8
|
+
|
|
9
|
+
Concrete implementations transform standardized messages (e.g., list[dict]) into the
|
|
10
|
+
exact payload required by a provider (e.g., OpenAI's message list, a single string, etc.).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
def format(
|
|
15
|
+
self,
|
|
16
|
+
messages: Any,
|
|
17
|
+
) -> Any:
|
|
18
|
+
"""
|
|
19
|
+
Transform the input messages into a provider-specific payload.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
messages: The input conversation. While often a list of dicts with
|
|
23
|
+
'role' and 'content' keys, the exact type and structure may vary
|
|
24
|
+
by implementation.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
A payload in the format expected by the target LLM API. This could be:
|
|
28
|
+
- A list of role-content dictionaries (e.g., for OpenAI)
|
|
29
|
+
- A single formatted string (e.g., for completion-style APIs)
|
|
30
|
+
- A complex dictionary with additional parameters
|
|
31
|
+
- Any other provider-specific data structure
|
|
32
|
+
"""
|
|
33
|
+
pass
|
texttools/formatters/{user_merge_formatter/user_merge_formatter.py → user_merge_formatter.py}
RENAMED
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
from texttools.formatters.base_formatter import BaseFormatter
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
class UserMergeFormatter(BaseFormatter):
|
|
5
|
-
"""
|
|
6
|
-
Merges consecutive user messages into a single message, separated by newlines.
|
|
7
|
-
|
|
8
|
-
This is useful for condensing a multi-turn user input into a single coherent
|
|
9
|
-
message for the LLM. Assistant and system messages are left unchanged and
|
|
10
|
-
act as separators between user message groups.
|
|
11
|
-
|
|
12
|
-
Raises:
|
|
13
|
-
ValueError: If the input messages have invalid structure or roles.
|
|
14
|
-
"""
|
|
15
|
-
|
|
16
|
-
def format(self, messages: list[dict[str, str]]) -> list[dict[str, str]]:
|
|
17
|
-
merged: list[dict[str, str]] = []
|
|
18
|
-
|
|
19
|
-
for message in messages:
|
|
20
|
-
role, content = message["role"], message["content"].strip()
|
|
21
|
-
|
|
22
|
-
# Merge with previous user turn
|
|
23
|
-
if merged and role == "user" and merged[-1]["role"] == "user":
|
|
24
|
-
merged[-1]["content"] += "\n" + content
|
|
25
|
-
|
|
26
|
-
# Otherwise, start a new turn
|
|
27
|
-
else:
|
|
28
|
-
merged.append({"role": role, "content": content})
|
|
29
|
-
|
|
30
|
-
return merged
|
|
1
|
+
from texttools.formatters.base_formatter import BaseFormatter
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class UserMergeFormatter(BaseFormatter):
|
|
5
|
+
"""
|
|
6
|
+
Merges consecutive user messages into a single message, separated by newlines.
|
|
7
|
+
|
|
8
|
+
This is useful for condensing a multi-turn user input into a single coherent
|
|
9
|
+
message for the LLM. Assistant and system messages are left unchanged and
|
|
10
|
+
act as separators between user message groups.
|
|
11
|
+
|
|
12
|
+
Raises:
|
|
13
|
+
ValueError: If the input messages have invalid structure or roles.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def format(self, messages: list[dict[str, str]]) -> list[dict[str, str]]:
|
|
17
|
+
merged: list[dict[str, str]] = []
|
|
18
|
+
|
|
19
|
+
for message in messages:
|
|
20
|
+
role, content = message["role"], message["content"].strip()
|
|
21
|
+
|
|
22
|
+
# Merge with previous user turn
|
|
23
|
+
if merged and role == "user" and merged[-1]["role"] == "user":
|
|
24
|
+
merged[-1]["content"] += "\n" + content
|
|
25
|
+
|
|
26
|
+
# Otherwise, start a new turn
|
|
27
|
+
else:
|
|
28
|
+
merged.append({"role": role, "content": content})
|
|
29
|
+
|
|
30
|
+
return merged
|
texttools/prompts/README.md
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
# Prompts
|
|
2
|
-
|
|
3
|
-
## Overview
|
|
4
|
-
This folder contains YAML files for all prompts used in the project. Each file represents a separate prompt template, which can be loaded by tools or scripts that require structured prompts for AI models.
|
|
5
|
-
|
|
6
|
-
## Structure
|
|
7
|
-
- **prompt_file.yaml**: Each YAML file represents a single prompt template.
|
|
8
|
-
- **main_template**: The main instruction template for the model.
|
|
9
|
-
- **analyze_template** (optional): A secondary reasoning template used before generating the final response.
|
|
10
|
-
- **Modes** (optional): Some prompts may have multiple modes (e.g., `default`, `reason`) to allow different behaviors.
|
|
11
|
-
|
|
12
|
-
### Example YAML Structure
|
|
13
|
-
```yaml
|
|
14
|
-
main_template:
|
|
15
|
-
default: |
|
|
16
|
-
Your main instructions here with placeholders like {input}.
|
|
17
|
-
reason: |
|
|
18
|
-
Optional reasoning instructions here.
|
|
19
|
-
|
|
20
|
-
analyze_template:
|
|
21
|
-
default: |
|
|
22
|
-
Analyze and summarize the input.
|
|
23
|
-
reason: |
|
|
24
|
-
Optional detailed analysis template.
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
## Guidelines
|
|
28
|
-
1. **Naming**: Use descriptive names for each YAML file corresponding to the tool or task it serves.
|
|
29
|
-
2. **Placeholders**: Use `{input}` or other relevant placeholders to dynamically inject data.
|
|
30
|
-
3. **Modes**: If using modes, ensure both `main_template` and `analyze_template` contain the corresponding keys.
|
|
31
|
-
4. **Consistency**: Keep formatting consistent across files for easier parsing by scripts.
|
|
1
|
+
# Prompts
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
This folder contains YAML files for all prompts used in the project. Each file represents a separate prompt template, which can be loaded by tools or scripts that require structured prompts for AI models.
|
|
5
|
+
|
|
6
|
+
## Structure
|
|
7
|
+
- **prompt_file.yaml**: Each YAML file represents a single prompt template.
|
|
8
|
+
- **main_template**: The main instruction template for the model.
|
|
9
|
+
- **analyze_template** (optional): A secondary reasoning template used before generating the final response.
|
|
10
|
+
- **Modes** (optional): Some prompts may have multiple modes (e.g., `default`, `reason`) to allow different behaviors.
|
|
11
|
+
|
|
12
|
+
### Example YAML Structure
|
|
13
|
+
```yaml
|
|
14
|
+
main_template:
|
|
15
|
+
default: |
|
|
16
|
+
Your main instructions here with placeholders like {input}.
|
|
17
|
+
reason: |
|
|
18
|
+
Optional reasoning instructions here.
|
|
19
|
+
|
|
20
|
+
analyze_template:
|
|
21
|
+
default: |
|
|
22
|
+
Analyze and summarize the input.
|
|
23
|
+
reason: |
|
|
24
|
+
Optional detailed analysis template.
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Guidelines
|
|
28
|
+
1. **Naming**: Use descriptive names for each YAML file corresponding to the tool or task it serves.
|
|
29
|
+
2. **Placeholders**: Use `{input}` or other relevant placeholders to dynamically inject data.
|
|
30
|
+
3. **Modes**: If using modes, ensure both `main_template` and `analyze_template` contain the corresponding keys.
|
|
31
|
+
4. **Consistency**: Keep formatting consistent across files for easier parsing by scripts.
|