llm_batch_helper 0.1.3__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.
- llm_batch_helper-0.1.3/LICENSE +201 -0
- llm_batch_helper-0.1.3/PKG-INFO +282 -0
- llm_batch_helper-0.1.3/README.md +253 -0
- llm_batch_helper-0.1.3/llm_batch_helper/__init__.py +15 -0
- llm_batch_helper-0.1.3/llm_batch_helper/cache.py +34 -0
- llm_batch_helper-0.1.3/llm_batch_helper/config.py +32 -0
- llm_batch_helper-0.1.3/llm_batch_helper/exceptions.py +7 -0
- llm_batch_helper-0.1.3/llm_batch_helper/input_handlers.py +84 -0
- llm_batch_helper-0.1.3/llm_batch_helper/providers.py +232 -0
- llm_batch_helper-0.1.3/pyproject.toml +59 -0
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
@@ -0,0 +1,282 @@
|
|
1
|
+
Metadata-Version: 2.3
|
2
|
+
Name: llm_batch_helper
|
3
|
+
Version: 0.1.3
|
4
|
+
Summary: A Python package that enables batch submission of prompts to LLM APIs, with built-in async capabilities and response caching.
|
5
|
+
License: MIT
|
6
|
+
Keywords: llm,openai,batch,async,ai,nlp,api
|
7
|
+
Author: Tianyi Peng
|
8
|
+
Author-email: tianyipeng95@gmail.com
|
9
|
+
Requires-Python: >=3.11,<4.0
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
11
|
+
Classifier: Intended Audience :: Developers
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
20
|
+
Requires-Dist: httpx (>=0.24.0,<0.25.0)
|
21
|
+
Requires-Dist: openai (>=1.0.0,<2.0.0)
|
22
|
+
Requires-Dist: python-dotenv (>=1.0.0,<2.0.0)
|
23
|
+
Requires-Dist: tenacity (>=8.0.0,<9.0.0)
|
24
|
+
Requires-Dist: tqdm (>=4.65.0,<5.0.0)
|
25
|
+
Project-URL: Homepage, https://github.com/TianyiPeng/LLM_batch_helper
|
26
|
+
Project-URL: Repository, https://github.com/TianyiPeng/LLM_batch_helper
|
27
|
+
Description-Content-Type: text/markdown
|
28
|
+
|
29
|
+
# LLM Batch Helper
|
30
|
+
|
31
|
+
A Python package that enables batch submission of prompts to LLM APIs, with built-in async capabilities and response caching.
|
32
|
+
|
33
|
+
## Features
|
34
|
+
|
35
|
+
- **Async Processing**: Submit multiple prompts concurrently for faster processing
|
36
|
+
- **Response Caching**: Automatically cache responses to avoid redundant API calls
|
37
|
+
- **Multiple Input Formats**: Support for both file-based and list-based prompts
|
38
|
+
- **Provider Support**: Works with OpenAI API
|
39
|
+
- **Retry Logic**: Built-in retry mechanism with exponential backoff
|
40
|
+
- **Verification Callbacks**: Custom verification for response quality
|
41
|
+
- **Progress Tracking**: Real-time progress bars for batch operations
|
42
|
+
|
43
|
+
## Installation
|
44
|
+
|
45
|
+
### For Users (Recommended)
|
46
|
+
|
47
|
+
```bash
|
48
|
+
# Install from PyPI
|
49
|
+
pip install llm_batch_helper
|
50
|
+
```
|
51
|
+
|
52
|
+
### For Development
|
53
|
+
|
54
|
+
```bash
|
55
|
+
# Clone the repository
|
56
|
+
git clone https://github.com/TianyiPeng/LLM_batch_helper.git
|
57
|
+
cd llm_batch_helper
|
58
|
+
|
59
|
+
# Install with Poetry
|
60
|
+
poetry install
|
61
|
+
|
62
|
+
# Activate the virtual environment
|
63
|
+
poetry shell
|
64
|
+
```
|
65
|
+
|
66
|
+
## Quick Start
|
67
|
+
|
68
|
+
### 1. Set up environment variables
|
69
|
+
|
70
|
+
```bash
|
71
|
+
# For OpenAI
|
72
|
+
export OPENAI_API_KEY="your-openai-api-key"
|
73
|
+
```
|
74
|
+
|
75
|
+
### 2. Interactive Tutorial (Recommended)
|
76
|
+
|
77
|
+
Check out the comprehensive Jupyter notebook [tutorial](https://github.com/TianyiPeng/LLM_batch_helper/blob/main/tutorials/llm_batch_helper_tutorial.ipynb).
|
78
|
+
|
79
|
+
The tutorial covers all features with interactive examples!
|
80
|
+
|
81
|
+
### 3. Basic usage
|
82
|
+
|
83
|
+
```python
|
84
|
+
import asyncio
|
85
|
+
from llm_batch_helper import LLMConfig, process_prompts_batch
|
86
|
+
|
87
|
+
async def main():
|
88
|
+
# Create configuration
|
89
|
+
config = LLMConfig(
|
90
|
+
model_name="gpt-4o-mini",
|
91
|
+
temperature=0.7,
|
92
|
+
max_tokens=100,
|
93
|
+
max_concurrent_requests=30 # number of concurrent requests with asyncIO
|
94
|
+
)
|
95
|
+
|
96
|
+
# Process prompts
|
97
|
+
prompts = [
|
98
|
+
"What is the capital of France?",
|
99
|
+
"What is 2+2?",
|
100
|
+
"Who wrote 'Hamlet'?"
|
101
|
+
]
|
102
|
+
|
103
|
+
results = await process_prompts_batch(
|
104
|
+
config=config,
|
105
|
+
provider="openai",
|
106
|
+
prompts=prompts,
|
107
|
+
cache_dir="cache"
|
108
|
+
)
|
109
|
+
|
110
|
+
# Print results
|
111
|
+
for prompt_id, response in results.items():
|
112
|
+
print(f"{prompt_id}: {response['response_text']}")
|
113
|
+
|
114
|
+
if __name__ == "__main__":
|
115
|
+
asyncio.run(main())
|
116
|
+
```
|
117
|
+
|
118
|
+
## Usage Examples
|
119
|
+
|
120
|
+
### File-based Prompts
|
121
|
+
|
122
|
+
```python
|
123
|
+
import asyncio
|
124
|
+
from llm_batch_helper import LLMConfig, process_prompts_batch
|
125
|
+
|
126
|
+
async def process_files():
|
127
|
+
config = LLMConfig(
|
128
|
+
model_name="gpt-4o-mini",
|
129
|
+
temperature=0.7,
|
130
|
+
max_tokens=200
|
131
|
+
)
|
132
|
+
|
133
|
+
# Process all .txt files in a directory
|
134
|
+
results = await process_prompts_batch(
|
135
|
+
config=config,
|
136
|
+
provider="openai",
|
137
|
+
input_dir="prompts", # Directory containing .txt files
|
138
|
+
cache_dir="cache",
|
139
|
+
force=False # Use cached responses if available
|
140
|
+
)
|
141
|
+
|
142
|
+
return results
|
143
|
+
|
144
|
+
asyncio.run(process_files())
|
145
|
+
```
|
146
|
+
|
147
|
+
### Custom Verification
|
148
|
+
|
149
|
+
```python
|
150
|
+
from llm_batch_helper import LLMConfig
|
151
|
+
|
152
|
+
def verify_response(prompt_id, llm_response_data, original_prompt_text, **kwargs):
|
153
|
+
"""Custom verification callback"""
|
154
|
+
response_text = llm_response_data.get("response_text", "")
|
155
|
+
|
156
|
+
# Check minimum length
|
157
|
+
if len(response_text) < kwargs.get("min_length", 10):
|
158
|
+
return False
|
159
|
+
|
160
|
+
# Check for specific keywords
|
161
|
+
if "error" in response_text.lower():
|
162
|
+
return False
|
163
|
+
|
164
|
+
return True
|
165
|
+
|
166
|
+
config = LLMConfig(
|
167
|
+
model_name="gpt-4o-mini",
|
168
|
+
temperature=0.7,
|
169
|
+
verification_callback=verify_response,
|
170
|
+
verification_callback_args={"min_length": 20}
|
171
|
+
)
|
172
|
+
```
|
173
|
+
|
174
|
+
|
175
|
+
|
176
|
+
## API Reference
|
177
|
+
|
178
|
+
### LLMConfig
|
179
|
+
|
180
|
+
Configuration class for LLM requests.
|
181
|
+
|
182
|
+
```python
|
183
|
+
LLMConfig(
|
184
|
+
model_name: str,
|
185
|
+
temperature: float = 0.7,
|
186
|
+
max_tokens: Optional[int] = None,
|
187
|
+
system_instruction: Optional[str] = None,
|
188
|
+
max_retries: int = 10,
|
189
|
+
max_concurrent_requests: int = 5,
|
190
|
+
verification_callback: Optional[Callable] = None,
|
191
|
+
verification_callback_args: Optional[Dict] = None
|
192
|
+
)
|
193
|
+
```
|
194
|
+
|
195
|
+
### process_prompts_batch
|
196
|
+
|
197
|
+
Main function for batch processing of prompts.
|
198
|
+
|
199
|
+
```python
|
200
|
+
async def process_prompts_batch(
|
201
|
+
config: LLMConfig,
|
202
|
+
provider: str, # "openai"
|
203
|
+
prompts: Optional[List[str]] = None,
|
204
|
+
input_dir: Optional[str] = None,
|
205
|
+
cache_dir: str = "llm_cache",
|
206
|
+
force: bool = False,
|
207
|
+
desc: str = "Processing prompts"
|
208
|
+
) -> Dict[str, Dict[str, Any]]
|
209
|
+
```
|
210
|
+
|
211
|
+
### LLMCache
|
212
|
+
|
213
|
+
Caching functionality for responses.
|
214
|
+
|
215
|
+
```python
|
216
|
+
cache = LLMCache(cache_dir="my_cache")
|
217
|
+
|
218
|
+
# Check for cached response
|
219
|
+
cached = cache.get_cached_response(prompt_id)
|
220
|
+
|
221
|
+
# Save response to cache
|
222
|
+
cache.save_response(prompt_id, prompt_text, response_data)
|
223
|
+
|
224
|
+
# Clear all cached responses
|
225
|
+
cache.clear_cache()
|
226
|
+
```
|
227
|
+
|
228
|
+
## Project Structure
|
229
|
+
|
230
|
+
```
|
231
|
+
llm_batch_helper/
|
232
|
+
├── pyproject.toml # Poetry configuration
|
233
|
+
├── poetry.lock # Locked dependencies
|
234
|
+
├── README.md # This file
|
235
|
+
├── LICENSE # License file
|
236
|
+
├── llm_batch_helper/ # Main package
|
237
|
+
│ ├── __init__.py # Package exports
|
238
|
+
│ ├── cache.py # Response caching
|
239
|
+
│ ├── config.py # Configuration classes
|
240
|
+
│ ├── providers.py # LLM provider implementations
|
241
|
+
│ ├── input_handlers.py # Input processing utilities
|
242
|
+
│ └── exceptions.py # Custom exceptions
|
243
|
+
├── examples/ # Usage examples
|
244
|
+
│ ├── example.py # Basic usage example
|
245
|
+
│ ├── prompts/ # Sample prompt files
|
246
|
+
│ └── llm_cache/ # Example cache directory
|
247
|
+
└── tutorials/ # Interactive tutorials
|
248
|
+
└── llm_batch_helper_tutorial.ipynb # Comprehensive Jupyter notebook tutorial
|
249
|
+
```
|
250
|
+
|
251
|
+
## Supported Models
|
252
|
+
|
253
|
+
### OpenAI
|
254
|
+
- gpt-4o-mini
|
255
|
+
- gpt-4o
|
256
|
+
- gpt-4
|
257
|
+
- gpt-3.5-turbo
|
258
|
+
|
259
|
+
## Contributing
|
260
|
+
|
261
|
+
1. Fork the repository
|
262
|
+
2. Create a feature branch
|
263
|
+
3. Make your changes
|
264
|
+
4. Add tests if applicable
|
265
|
+
5. Run the test suite
|
266
|
+
6. Submit a pull request
|
267
|
+
|
268
|
+
## License
|
269
|
+
|
270
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
271
|
+
|
272
|
+
## Changelog
|
273
|
+
|
274
|
+
### v0.1.0
|
275
|
+
- Initial release
|
276
|
+
- Support for OpenAI API
|
277
|
+
- Async batch processing
|
278
|
+
- Response caching
|
279
|
+
- File and list-based input support
|
280
|
+
- Custom verification callbacks
|
281
|
+
- Poetry package management
|
282
|
+
|
@@ -0,0 +1,253 @@
|
|
1
|
+
# LLM Batch Helper
|
2
|
+
|
3
|
+
A Python package that enables batch submission of prompts to LLM APIs, with built-in async capabilities and response caching.
|
4
|
+
|
5
|
+
## Features
|
6
|
+
|
7
|
+
- **Async Processing**: Submit multiple prompts concurrently for faster processing
|
8
|
+
- **Response Caching**: Automatically cache responses to avoid redundant API calls
|
9
|
+
- **Multiple Input Formats**: Support for both file-based and list-based prompts
|
10
|
+
- **Provider Support**: Works with OpenAI API
|
11
|
+
- **Retry Logic**: Built-in retry mechanism with exponential backoff
|
12
|
+
- **Verification Callbacks**: Custom verification for response quality
|
13
|
+
- **Progress Tracking**: Real-time progress bars for batch operations
|
14
|
+
|
15
|
+
## Installation
|
16
|
+
|
17
|
+
### For Users (Recommended)
|
18
|
+
|
19
|
+
```bash
|
20
|
+
# Install from PyPI
|
21
|
+
pip install llm_batch_helper
|
22
|
+
```
|
23
|
+
|
24
|
+
### For Development
|
25
|
+
|
26
|
+
```bash
|
27
|
+
# Clone the repository
|
28
|
+
git clone https://github.com/TianyiPeng/LLM_batch_helper.git
|
29
|
+
cd llm_batch_helper
|
30
|
+
|
31
|
+
# Install with Poetry
|
32
|
+
poetry install
|
33
|
+
|
34
|
+
# Activate the virtual environment
|
35
|
+
poetry shell
|
36
|
+
```
|
37
|
+
|
38
|
+
## Quick Start
|
39
|
+
|
40
|
+
### 1. Set up environment variables
|
41
|
+
|
42
|
+
```bash
|
43
|
+
# For OpenAI
|
44
|
+
export OPENAI_API_KEY="your-openai-api-key"
|
45
|
+
```
|
46
|
+
|
47
|
+
### 2. Interactive Tutorial (Recommended)
|
48
|
+
|
49
|
+
Check out the comprehensive Jupyter notebook [tutorial](https://github.com/TianyiPeng/LLM_batch_helper/blob/main/tutorials/llm_batch_helper_tutorial.ipynb).
|
50
|
+
|
51
|
+
The tutorial covers all features with interactive examples!
|
52
|
+
|
53
|
+
### 3. Basic usage
|
54
|
+
|
55
|
+
```python
|
56
|
+
import asyncio
|
57
|
+
from llm_batch_helper import LLMConfig, process_prompts_batch
|
58
|
+
|
59
|
+
async def main():
|
60
|
+
# Create configuration
|
61
|
+
config = LLMConfig(
|
62
|
+
model_name="gpt-4o-mini",
|
63
|
+
temperature=0.7,
|
64
|
+
max_tokens=100,
|
65
|
+
max_concurrent_requests=30 # number of concurrent requests with asyncIO
|
66
|
+
)
|
67
|
+
|
68
|
+
# Process prompts
|
69
|
+
prompts = [
|
70
|
+
"What is the capital of France?",
|
71
|
+
"What is 2+2?",
|
72
|
+
"Who wrote 'Hamlet'?"
|
73
|
+
]
|
74
|
+
|
75
|
+
results = await process_prompts_batch(
|
76
|
+
config=config,
|
77
|
+
provider="openai",
|
78
|
+
prompts=prompts,
|
79
|
+
cache_dir="cache"
|
80
|
+
)
|
81
|
+
|
82
|
+
# Print results
|
83
|
+
for prompt_id, response in results.items():
|
84
|
+
print(f"{prompt_id}: {response['response_text']}")
|
85
|
+
|
86
|
+
if __name__ == "__main__":
|
87
|
+
asyncio.run(main())
|
88
|
+
```
|
89
|
+
|
90
|
+
## Usage Examples
|
91
|
+
|
92
|
+
### File-based Prompts
|
93
|
+
|
94
|
+
```python
|
95
|
+
import asyncio
|
96
|
+
from llm_batch_helper import LLMConfig, process_prompts_batch
|
97
|
+
|
98
|
+
async def process_files():
|
99
|
+
config = LLMConfig(
|
100
|
+
model_name="gpt-4o-mini",
|
101
|
+
temperature=0.7,
|
102
|
+
max_tokens=200
|
103
|
+
)
|
104
|
+
|
105
|
+
# Process all .txt files in a directory
|
106
|
+
results = await process_prompts_batch(
|
107
|
+
config=config,
|
108
|
+
provider="openai",
|
109
|
+
input_dir="prompts", # Directory containing .txt files
|
110
|
+
cache_dir="cache",
|
111
|
+
force=False # Use cached responses if available
|
112
|
+
)
|
113
|
+
|
114
|
+
return results
|
115
|
+
|
116
|
+
asyncio.run(process_files())
|
117
|
+
```
|
118
|
+
|
119
|
+
### Custom Verification
|
120
|
+
|
121
|
+
```python
|
122
|
+
from llm_batch_helper import LLMConfig
|
123
|
+
|
124
|
+
def verify_response(prompt_id, llm_response_data, original_prompt_text, **kwargs):
|
125
|
+
"""Custom verification callback"""
|
126
|
+
response_text = llm_response_data.get("response_text", "")
|
127
|
+
|
128
|
+
# Check minimum length
|
129
|
+
if len(response_text) < kwargs.get("min_length", 10):
|
130
|
+
return False
|
131
|
+
|
132
|
+
# Check for specific keywords
|
133
|
+
if "error" in response_text.lower():
|
134
|
+
return False
|
135
|
+
|
136
|
+
return True
|
137
|
+
|
138
|
+
config = LLMConfig(
|
139
|
+
model_name="gpt-4o-mini",
|
140
|
+
temperature=0.7,
|
141
|
+
verification_callback=verify_response,
|
142
|
+
verification_callback_args={"min_length": 20}
|
143
|
+
)
|
144
|
+
```
|
145
|
+
|
146
|
+
|
147
|
+
|
148
|
+
## API Reference
|
149
|
+
|
150
|
+
### LLMConfig
|
151
|
+
|
152
|
+
Configuration class for LLM requests.
|
153
|
+
|
154
|
+
```python
|
155
|
+
LLMConfig(
|
156
|
+
model_name: str,
|
157
|
+
temperature: float = 0.7,
|
158
|
+
max_tokens: Optional[int] = None,
|
159
|
+
system_instruction: Optional[str] = None,
|
160
|
+
max_retries: int = 10,
|
161
|
+
max_concurrent_requests: int = 5,
|
162
|
+
verification_callback: Optional[Callable] = None,
|
163
|
+
verification_callback_args: Optional[Dict] = None
|
164
|
+
)
|
165
|
+
```
|
166
|
+
|
167
|
+
### process_prompts_batch
|
168
|
+
|
169
|
+
Main function for batch processing of prompts.
|
170
|
+
|
171
|
+
```python
|
172
|
+
async def process_prompts_batch(
|
173
|
+
config: LLMConfig,
|
174
|
+
provider: str, # "openai"
|
175
|
+
prompts: Optional[List[str]] = None,
|
176
|
+
input_dir: Optional[str] = None,
|
177
|
+
cache_dir: str = "llm_cache",
|
178
|
+
force: bool = False,
|
179
|
+
desc: str = "Processing prompts"
|
180
|
+
) -> Dict[str, Dict[str, Any]]
|
181
|
+
```
|
182
|
+
|
183
|
+
### LLMCache
|
184
|
+
|
185
|
+
Caching functionality for responses.
|
186
|
+
|
187
|
+
```python
|
188
|
+
cache = LLMCache(cache_dir="my_cache")
|
189
|
+
|
190
|
+
# Check for cached response
|
191
|
+
cached = cache.get_cached_response(prompt_id)
|
192
|
+
|
193
|
+
# Save response to cache
|
194
|
+
cache.save_response(prompt_id, prompt_text, response_data)
|
195
|
+
|
196
|
+
# Clear all cached responses
|
197
|
+
cache.clear_cache()
|
198
|
+
```
|
199
|
+
|
200
|
+
## Project Structure
|
201
|
+
|
202
|
+
```
|
203
|
+
llm_batch_helper/
|
204
|
+
├── pyproject.toml # Poetry configuration
|
205
|
+
├── poetry.lock # Locked dependencies
|
206
|
+
├── README.md # This file
|
207
|
+
├── LICENSE # License file
|
208
|
+
├── llm_batch_helper/ # Main package
|
209
|
+
│ ├── __init__.py # Package exports
|
210
|
+
│ ├── cache.py # Response caching
|
211
|
+
│ ├── config.py # Configuration classes
|
212
|
+
│ ├── providers.py # LLM provider implementations
|
213
|
+
│ ├── input_handlers.py # Input processing utilities
|
214
|
+
│ └── exceptions.py # Custom exceptions
|
215
|
+
├── examples/ # Usage examples
|
216
|
+
│ ├── example.py # Basic usage example
|
217
|
+
│ ├── prompts/ # Sample prompt files
|
218
|
+
│ └── llm_cache/ # Example cache directory
|
219
|
+
└── tutorials/ # Interactive tutorials
|
220
|
+
└── llm_batch_helper_tutorial.ipynb # Comprehensive Jupyter notebook tutorial
|
221
|
+
```
|
222
|
+
|
223
|
+
## Supported Models
|
224
|
+
|
225
|
+
### OpenAI
|
226
|
+
- gpt-4o-mini
|
227
|
+
- gpt-4o
|
228
|
+
- gpt-4
|
229
|
+
- gpt-3.5-turbo
|
230
|
+
|
231
|
+
## Contributing
|
232
|
+
|
233
|
+
1. Fork the repository
|
234
|
+
2. Create a feature branch
|
235
|
+
3. Make your changes
|
236
|
+
4. Add tests if applicable
|
237
|
+
5. Run the test suite
|
238
|
+
6. Submit a pull request
|
239
|
+
|
240
|
+
## License
|
241
|
+
|
242
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
243
|
+
|
244
|
+
## Changelog
|
245
|
+
|
246
|
+
### v0.1.0
|
247
|
+
- Initial release
|
248
|
+
- Support for OpenAI API
|
249
|
+
- Async batch processing
|
250
|
+
- Response caching
|
251
|
+
- File and list-based input support
|
252
|
+
- Custom verification callbacks
|
253
|
+
- Poetry package management
|
@@ -0,0 +1,15 @@
|
|
1
|
+
from .cache import LLMCache
|
2
|
+
from .config import LLMConfig
|
3
|
+
from .input_handlers import get_prompts, read_prompt_files, read_prompt_list
|
4
|
+
from .providers import process_prompts_batch
|
5
|
+
|
6
|
+
__version__ = "0.1.1"
|
7
|
+
|
8
|
+
__all__ = [
|
9
|
+
"LLMCache",
|
10
|
+
"LLMConfig",
|
11
|
+
"get_prompts",
|
12
|
+
"process_prompts_batch",
|
13
|
+
"read_prompt_files",
|
14
|
+
"read_prompt_list",
|
15
|
+
]
|
@@ -0,0 +1,34 @@
|
|
1
|
+
import json
|
2
|
+
from pathlib import Path
|
3
|
+
from typing import Any, Dict, Optional
|
4
|
+
|
5
|
+
|
6
|
+
class LLMCache:
|
7
|
+
def __init__(self, cache_dir: str = "llm_cache"):
|
8
|
+
self.cache_dir = Path(cache_dir)
|
9
|
+
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
10
|
+
|
11
|
+
def _get_cache_path(self, prompt_id: str) -> Path:
|
12
|
+
"""Generate cache file path based on prompt_id."""
|
13
|
+
return self.cache_dir / f"{prompt_id}.json"
|
14
|
+
|
15
|
+
def get_cached_response(self, prompt_id: str) -> Optional[Dict[str, Any]]:
|
16
|
+
"""Retrieve cached response if it exists."""
|
17
|
+
cache_path = self._get_cache_path(prompt_id)
|
18
|
+
if cache_path.exists():
|
19
|
+
with open(cache_path, "r") as f:
|
20
|
+
return json.load(f)
|
21
|
+
return None
|
22
|
+
|
23
|
+
def save_response(self, prompt_id: str, prompt: str, response: Dict[str, Any]) -> None:
|
24
|
+
"""Save response to cache."""
|
25
|
+
cache_path = self._get_cache_path(prompt_id)
|
26
|
+
cache_data = {"prompt_input": prompt, "llm_response": response}
|
27
|
+
with open(cache_path, "w") as f:
|
28
|
+
json.dump(cache_data, f, indent=2)
|
29
|
+
|
30
|
+
def clear_cache(self) -> None:
|
31
|
+
"""Clear all cached responses."""
|
32
|
+
if self.cache_dir.exists():
|
33
|
+
for file in self.cache_dir.glob("*.json"):
|
34
|
+
file.unlink()
|
@@ -0,0 +1,32 @@
|
|
1
|
+
from typing import Callable, Dict, Optional
|
2
|
+
|
3
|
+
# System instruction for Gemini
|
4
|
+
SYSTEM_INSTRUCTION = """You are a helpful AI assistant. """
|
5
|
+
|
6
|
+
|
7
|
+
class LLMConfig:
|
8
|
+
def __init__(
|
9
|
+
self,
|
10
|
+
model_name: str,
|
11
|
+
temperature: float = 0.7,
|
12
|
+
max_tokens: Optional[int] = None,
|
13
|
+
system_instruction: Optional[str] = None,
|
14
|
+
max_retries: int = 10, # Max retries for the combined LLM call + Verification
|
15
|
+
max_concurrent_requests: int = 5,
|
16
|
+
verification_callback: Optional[Callable[..., bool]] = None,
|
17
|
+
verification_callback_args: Optional[Dict] = None,
|
18
|
+
max_completion_tokens: Optional[int] = None,
|
19
|
+
):
|
20
|
+
self.model_name = model_name
|
21
|
+
self.temperature = temperature
|
22
|
+
self.max_tokens = max_tokens
|
23
|
+
self.max_completion_tokens = max_completion_tokens
|
24
|
+
if self.max_tokens and not self.max_completion_tokens:
|
25
|
+
self.max_completion_tokens = self.max_tokens
|
26
|
+
self.system_instruction = system_instruction or SYSTEM_INSTRUCTION
|
27
|
+
self.max_retries = max_retries
|
28
|
+
self.max_concurrent_requests = max_concurrent_requests
|
29
|
+
self.verification_callback = verification_callback
|
30
|
+
self.verification_callback_args = (
|
31
|
+
verification_callback_args if verification_callback_args is not None else {}
|
32
|
+
)
|
@@ -0,0 +1,7 @@
|
|
1
|
+
class VerificationFailedError(Exception):
|
2
|
+
"""Custom exception for when verification callback fails."""
|
3
|
+
|
4
|
+
def __init__(self, message, prompt_id, llm_response_data=None):
|
5
|
+
super().__init__(message)
|
6
|
+
self.prompt_id = prompt_id
|
7
|
+
self.llm_response_data = llm_response_data
|
@@ -0,0 +1,84 @@
|
|
1
|
+
import hashlib
|
2
|
+
from pathlib import Path
|
3
|
+
from typing import Any, Dict, List, Tuple, Union
|
4
|
+
|
5
|
+
|
6
|
+
def read_prompt_files(input_dir: str) -> List[Tuple[str, str]]:
|
7
|
+
"""Read all text files from input directory and return as (filename, content) pairs.
|
8
|
+
|
9
|
+
Args:
|
10
|
+
input_dir: Path to directory containing prompt files
|
11
|
+
|
12
|
+
Returns:
|
13
|
+
List of (prompt_id, prompt_text) tuples where prompt_id is the filename without extension
|
14
|
+
"""
|
15
|
+
input_path = Path(input_dir)
|
16
|
+
if not input_path.exists():
|
17
|
+
raise ValueError(f"Input directory {input_dir} does not exist")
|
18
|
+
|
19
|
+
prompts = []
|
20
|
+
for file_path in input_path.glob("*.txt"):
|
21
|
+
with open(file_path, "r") as f:
|
22
|
+
content = f.read().strip()
|
23
|
+
# Use filename without extension as prompt_id
|
24
|
+
prompt_id = file_path.stem
|
25
|
+
prompts.append((prompt_id, content))
|
26
|
+
|
27
|
+
if not prompts:
|
28
|
+
raise ValueError(f"No .txt files found in {input_dir}")
|
29
|
+
|
30
|
+
return prompts
|
31
|
+
|
32
|
+
|
33
|
+
def read_prompt_list(
|
34
|
+
input_source: List[Union[str, Tuple[str, str], Dict[str, Any]]],
|
35
|
+
) -> List[Tuple[str, str]]:
|
36
|
+
"""Read prompts from a list of various formats.
|
37
|
+
|
38
|
+
Args:
|
39
|
+
input_source: List of prompts in any of these formats:
|
40
|
+
- str: The prompt text (will use hash as ID)
|
41
|
+
- tuple: (prompt_id, prompt_text)
|
42
|
+
- dict: {"id": prompt_id, "text": prompt_text}
|
43
|
+
|
44
|
+
Returns:
|
45
|
+
List of (prompt_id, prompt_text) tuples
|
46
|
+
"""
|
47
|
+
prompts = []
|
48
|
+
for item in input_source:
|
49
|
+
if isinstance(item, str):
|
50
|
+
# String format: use hash as ID
|
51
|
+
prompt_id = hashlib.sha256(item.encode()).hexdigest()[:32]
|
52
|
+
prompt_text = item
|
53
|
+
elif isinstance(item, tuple) and len(item) == 2:
|
54
|
+
# Tuple format: (prompt_id, prompt_text)
|
55
|
+
prompt_id, prompt_text = item
|
56
|
+
elif isinstance(item, dict) and "id" in item and "text" in item:
|
57
|
+
# Dict format: {"id": prompt_id, "text": prompt_text}
|
58
|
+
prompt_id = item["id"]
|
59
|
+
prompt_text = item["text"]
|
60
|
+
else:
|
61
|
+
raise ValueError(f"Invalid prompt format: {item}")
|
62
|
+
prompts.append((prompt_id, prompt_text))
|
63
|
+
return prompts
|
64
|
+
|
65
|
+
|
66
|
+
def get_prompts(
|
67
|
+
input_source: Union[str, List[Union[str, Tuple[str, str], Dict[str, Any]]]],
|
68
|
+
) -> List[Tuple[str, str]]:
|
69
|
+
"""Get prompts from either a directory or a list.
|
70
|
+
|
71
|
+
Args:
|
72
|
+
input_source: Either:
|
73
|
+
- str: Path to directory containing prompt files
|
74
|
+
- List: List of prompts in various formats (string, tuple, or dict)
|
75
|
+
|
76
|
+
Returns:
|
77
|
+
List of (prompt_id, prompt_text) tuples
|
78
|
+
"""
|
79
|
+
if isinstance(input_source, str):
|
80
|
+
return read_prompt_files(input_source)
|
81
|
+
elif isinstance(input_source, list):
|
82
|
+
return read_prompt_list(input_source)
|
83
|
+
else:
|
84
|
+
raise ValueError(f"Invalid input source type: {type(input_source)}")
|
@@ -0,0 +1,232 @@
|
|
1
|
+
import asyncio
|
2
|
+
import os
|
3
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
4
|
+
|
5
|
+
import httpx
|
6
|
+
import openai
|
7
|
+
from dotenv import load_dotenv
|
8
|
+
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
|
9
|
+
from tqdm.asyncio import tqdm_asyncio
|
10
|
+
|
11
|
+
from .cache import LLMCache
|
12
|
+
from .config import LLMConfig
|
13
|
+
from .input_handlers import get_prompts
|
14
|
+
|
15
|
+
load_dotenv()
|
16
|
+
|
17
|
+
|
18
|
+
@retry(
|
19
|
+
stop=stop_after_attempt(5),
|
20
|
+
wait=wait_exponential(multiplier=1, min=4, max=60),
|
21
|
+
retry=retry_if_exception_type(
|
22
|
+
(
|
23
|
+
ConnectionError,
|
24
|
+
TimeoutError,
|
25
|
+
openai.APITimeoutError,
|
26
|
+
openai.APIConnectionError,
|
27
|
+
openai.RateLimitError,
|
28
|
+
openai.APIError,
|
29
|
+
)
|
30
|
+
),
|
31
|
+
reraise=True,
|
32
|
+
)
|
33
|
+
async def _get_openai_response_direct(
|
34
|
+
prompt: str, config: LLMConfig
|
35
|
+
) -> Dict[str, Union[str, Dict]]:
|
36
|
+
api_key = os.environ.get("OPENAI_API_KEY")
|
37
|
+
if not api_key:
|
38
|
+
raise ValueError("OPENAI_API_KEY environment variable not set")
|
39
|
+
|
40
|
+
async with httpx.AsyncClient(timeout=1000.0) as client:
|
41
|
+
aclient = openai.AsyncOpenAI(api_key=api_key, http_client=client)
|
42
|
+
messages = [
|
43
|
+
{"role": "system", "content": config.system_instruction},
|
44
|
+
{"role": "user", "content": prompt},
|
45
|
+
]
|
46
|
+
|
47
|
+
response = await aclient.chat.completions.create(
|
48
|
+
model=config.model_name,
|
49
|
+
messages=messages,
|
50
|
+
temperature=config.temperature,
|
51
|
+
max_completion_tokens=config.max_completion_tokens,
|
52
|
+
)
|
53
|
+
usage_details = {
|
54
|
+
"prompt_token_count": response.usage.prompt_tokens,
|
55
|
+
"completion_token_count": response.usage.completion_tokens,
|
56
|
+
"total_token_count": response.usage.total_tokens,
|
57
|
+
}
|
58
|
+
return {
|
59
|
+
"response_text": response.choices[0].message.content,
|
60
|
+
"usage_details": usage_details,
|
61
|
+
}
|
62
|
+
|
63
|
+
async def get_llm_response_with_internal_retry(
|
64
|
+
prompt_id: str,
|
65
|
+
prompt: str,
|
66
|
+
config: LLMConfig,
|
67
|
+
provider: str,
|
68
|
+
cache: Optional[LLMCache] = None,
|
69
|
+
force: bool = False,
|
70
|
+
) -> Dict[str, Union[str, Dict]]:
|
71
|
+
# Check cache first if available and not forcing regeneration
|
72
|
+
if cache and not force:
|
73
|
+
cached_response = cache.get_cached_response(prompt_id)
|
74
|
+
if cached_response:
|
75
|
+
return cached_response["llm_response"]
|
76
|
+
|
77
|
+
try:
|
78
|
+
if provider.lower() == "openai":
|
79
|
+
response = await _get_openai_response_direct(prompt, config)
|
80
|
+
else:
|
81
|
+
raise ValueError(f"Unsupported provider: {provider}")
|
82
|
+
|
83
|
+
# Cache the response if cache is available
|
84
|
+
if cache and "error" not in response:
|
85
|
+
cache.save_response(prompt_id, prompt, response)
|
86
|
+
|
87
|
+
return response
|
88
|
+
except Exception as e:
|
89
|
+
return {
|
90
|
+
"error": f"LLM API call failed after internal retries: {e!s}",
|
91
|
+
"provider": provider,
|
92
|
+
}
|
93
|
+
|
94
|
+
|
95
|
+
async def process_prompts_batch(
|
96
|
+
prompts: Optional[List[Union[str, Tuple[str, str], Dict[str, Any]]]] = None,
|
97
|
+
input_dir: Optional[str] = None,
|
98
|
+
config: LLMConfig = None,
|
99
|
+
provider: str = "openai",
|
100
|
+
desc: str = "Processing prompts",
|
101
|
+
cache_dir: Optional[str] = None,
|
102
|
+
force: bool = False,
|
103
|
+
) -> Dict[str, Dict[str, Union[str, Dict]]]:
|
104
|
+
"""Process a batch of prompts through the LLM.
|
105
|
+
|
106
|
+
Args:
|
107
|
+
prompts: Optional list of prompts in any supported format (string, tuple, or dict)
|
108
|
+
input_dir: Optional path to directory containing prompt files
|
109
|
+
config: LLM configuration
|
110
|
+
provider: LLM provider to use ("openai" or "gemini")
|
111
|
+
desc: Description for progress bar
|
112
|
+
cache_dir: Optional directory for caching responses
|
113
|
+
force: If True, force regeneration even if cached response exists
|
114
|
+
|
115
|
+
Returns:
|
116
|
+
Dict mapping prompt IDs to their responses
|
117
|
+
|
118
|
+
Note:
|
119
|
+
Either prompts or input_dir must be provided, but not both.
|
120
|
+
"""
|
121
|
+
if prompts is None and input_dir is None:
|
122
|
+
raise ValueError("Either prompts or input_dir must be provided")
|
123
|
+
if prompts is not None and input_dir is not None:
|
124
|
+
raise ValueError("Cannot specify both prompts and input_dir")
|
125
|
+
|
126
|
+
# Get prompts from either source
|
127
|
+
if input_dir is not None:
|
128
|
+
prompts = get_prompts(input_dir)
|
129
|
+
else:
|
130
|
+
prompts = get_prompts(prompts)
|
131
|
+
|
132
|
+
# Create semaphore for concurrent requests
|
133
|
+
semaphore = asyncio.Semaphore(config.max_concurrent_requests)
|
134
|
+
|
135
|
+
# Process prompts
|
136
|
+
results = {}
|
137
|
+
tasks = [
|
138
|
+
_process_single_prompt_attempt_with_verification(
|
139
|
+
prompt_id, prompt_text, config, provider, semaphore, cache_dir, force
|
140
|
+
)
|
141
|
+
for prompt_id, prompt_text in prompts
|
142
|
+
]
|
143
|
+
|
144
|
+
for future in tqdm_asyncio(asyncio.as_completed(tasks), total=len(tasks), desc=desc):
|
145
|
+
prompt_id, response_data = await future
|
146
|
+
results[prompt_id] = response_data
|
147
|
+
|
148
|
+
return results
|
149
|
+
|
150
|
+
|
151
|
+
async def _process_single_prompt_attempt_with_verification(
|
152
|
+
prompt_id: str,
|
153
|
+
prompt_text: str,
|
154
|
+
config: LLMConfig,
|
155
|
+
provider: str,
|
156
|
+
semaphore: asyncio.Semaphore,
|
157
|
+
cache_dir: Optional[str] = None,
|
158
|
+
force: bool = False,
|
159
|
+
):
|
160
|
+
"""Process a single prompt with verification and caching."""
|
161
|
+
async with semaphore:
|
162
|
+
# Check cache first if cache_dir is provided
|
163
|
+
if cache_dir and not force:
|
164
|
+
cache = LLMCache(cache_dir)
|
165
|
+
cached_response = cache.get_cached_response(prompt_id)
|
166
|
+
if cached_response is not None:
|
167
|
+
# Verify response if callback provided
|
168
|
+
cached_response_data = cached_response["llm_response"]
|
169
|
+
if config.verification_callback:
|
170
|
+
verified = await asyncio.to_thread(
|
171
|
+
config.verification_callback,
|
172
|
+
prompt_id,
|
173
|
+
cached_response_data,
|
174
|
+
prompt_text,
|
175
|
+
**config.verification_callback_args,
|
176
|
+
)
|
177
|
+
if verified:
|
178
|
+
return prompt_id, {**cached_response_data, "from_cache": True}
|
179
|
+
|
180
|
+
# Process the prompt
|
181
|
+
last_exception_details = None
|
182
|
+
for attempt in range(config.max_retries):
|
183
|
+
try:
|
184
|
+
# Get LLM response
|
185
|
+
llm_response_data = await get_llm_response_with_internal_retry(
|
186
|
+
prompt_id, prompt_text, config, provider
|
187
|
+
)
|
188
|
+
|
189
|
+
if "error" in llm_response_data:
|
190
|
+
last_exception_details = llm_response_data
|
191
|
+
continue
|
192
|
+
|
193
|
+
# Verify response if callback provided
|
194
|
+
if config.verification_callback:
|
195
|
+
verified = await asyncio.to_thread(
|
196
|
+
config.verification_callback,
|
197
|
+
prompt_id,
|
198
|
+
llm_response_data,
|
199
|
+
prompt_text,
|
200
|
+
**config.verification_callback_args,
|
201
|
+
)
|
202
|
+
if not verified:
|
203
|
+
last_exception_details = {
|
204
|
+
"error": f"Verification failed on attempt {attempt + 1}",
|
205
|
+
"prompt_id": prompt_id,
|
206
|
+
"llm_response_data": llm_response_data,
|
207
|
+
}
|
208
|
+
if attempt == config.max_retries - 1:
|
209
|
+
return prompt_id, last_exception_details
|
210
|
+
await asyncio.sleep(min(2 * 2**attempt, 30))
|
211
|
+
continue
|
212
|
+
|
213
|
+
# Save to cache if cache_dir provided
|
214
|
+
if cache_dir:
|
215
|
+
cache = LLMCache(cache_dir)
|
216
|
+
cache.save_response(prompt_id, prompt_text, llm_response_data)
|
217
|
+
|
218
|
+
return prompt_id, llm_response_data
|
219
|
+
|
220
|
+
except Exception as e:
|
221
|
+
last_exception_details = {
|
222
|
+
"error": f"Unexpected error: {e!s}",
|
223
|
+
"prompt_id": prompt_id,
|
224
|
+
}
|
225
|
+
if attempt == config.max_retries - 1:
|
226
|
+
return prompt_id, last_exception_details
|
227
|
+
await asyncio.sleep(min(2 * 2**attempt, 30))
|
228
|
+
continue
|
229
|
+
|
230
|
+
return prompt_id, last_exception_details or {
|
231
|
+
"error": f"Exhausted all {config.max_retries} retries for {prompt_id}"
|
232
|
+
}
|
@@ -0,0 +1,59 @@
|
|
1
|
+
[tool.poetry]
|
2
|
+
name = "llm_batch_helper"
|
3
|
+
version = "0.1.3"
|
4
|
+
description = "A Python package that enables batch submission of prompts to LLM APIs, with built-in async capabilities and response caching."
|
5
|
+
authors = ["Tianyi Peng <tianyipeng95@gmail.com>"]
|
6
|
+
readme = "README.md"
|
7
|
+
license = "MIT"
|
8
|
+
homepage = "https://github.com/TianyiPeng/LLM_batch_helper"
|
9
|
+
repository = "https://github.com/TianyiPeng/LLM_batch_helper"
|
10
|
+
keywords = ["llm", "openai", "batch", "async", "ai", "nlp", "api"]
|
11
|
+
classifiers = [
|
12
|
+
"Development Status :: 4 - Beta",
|
13
|
+
"Intended Audience :: Developers",
|
14
|
+
"License :: OSI Approved :: MIT License",
|
15
|
+
"Programming Language :: Python :: 3",
|
16
|
+
"Programming Language :: Python :: 3.10",
|
17
|
+
"Programming Language :: Python :: 3.11",
|
18
|
+
"Programming Language :: Python :: 3.12",
|
19
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
20
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
21
|
+
]
|
22
|
+
packages = [{include = "llm_batch_helper"}]
|
23
|
+
|
24
|
+
[tool.poetry.dependencies]
|
25
|
+
python = "^3.11"
|
26
|
+
httpx = "^0.24.0"
|
27
|
+
openai = "^1.0.0"
|
28
|
+
python-dotenv = "^1.0.0"
|
29
|
+
tenacity = "^8.0.0"
|
30
|
+
tqdm = "^4.65.0"
|
31
|
+
|
32
|
+
[tool.poetry.group.dev.dependencies]
|
33
|
+
pytest = "^7.0.0"
|
34
|
+
black = "^23.0.0"
|
35
|
+
isort = "^5.12.0"
|
36
|
+
flake8 = "^6.0.0"
|
37
|
+
mypy = "^1.0.0"
|
38
|
+
jupyter = "^1.0.0"
|
39
|
+
twine = "^6.1.0"
|
40
|
+
ipython = "^9.4.0"
|
41
|
+
ipykernel = "^6.29.5"
|
42
|
+
|
43
|
+
[build-system]
|
44
|
+
requires = ["poetry-core"]
|
45
|
+
build-backend = "poetry.core.masonry.api"
|
46
|
+
|
47
|
+
[tool.black]
|
48
|
+
line-length = 88
|
49
|
+
target-version = ['py38']
|
50
|
+
|
51
|
+
[tool.isort]
|
52
|
+
profile = "black"
|
53
|
+
line_length = 88
|
54
|
+
|
55
|
+
[tool.mypy]
|
56
|
+
python_version = "3.8"
|
57
|
+
warn_return_any = true
|
58
|
+
warn_unused_configs = true
|
59
|
+
disallow_untyped_defs = true
|