structai 0.1.0__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.
- structai/__init__.py +30 -0
- structai/io.py +227 -0
- structai/llm_api.py +682 -0
- structai/mp.py +96 -0
- structai/openai_server.py +79 -0
- structai/utils.py +209 -0
- structai-0.1.0.dist-info/METADATA +365 -0
- structai-0.1.0.dist-info/RECORD +11 -0
- structai-0.1.0.dist-info/WHEEL +5 -0
- structai-0.1.0.dist-info/licenses/LICENSE +21 -0
- structai-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: structai
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A utility package for AI development
|
|
5
|
+
Author-email: Wanghan Xu <xu_wanghan@sjtu.edu.cn>
|
|
6
|
+
Project-URL: Homepage, https://github.com/black-yt/structai
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.6
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: openai
|
|
14
|
+
Requires-Dist: python-Levenshtein
|
|
15
|
+
Requires-Dist: json_repair
|
|
16
|
+
Requires-Dist: pillow
|
|
17
|
+
Requires-Dist: httpx[socks]
|
|
18
|
+
Requires-Dist: pandas
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Requires-Dist: tqdm
|
|
21
|
+
Requires-Dist: fastapi
|
|
22
|
+
Requires-Dist: uvicorn
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# StructAI
|
|
26
|
+
|
|
27
|
+
StructAI is a comprehensive utility package for AI development, offering a robust set of tools for file operations, LLM interactions, parallel processing, and general programming tasks.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
git clone https://github.com/black-yt/structai.git
|
|
33
|
+
cd structai
|
|
34
|
+
pip install -e .
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## API Reference & Usage
|
|
38
|
+
|
|
39
|
+
### `load_file(path)`
|
|
40
|
+
|
|
41
|
+
Automatically reads a file based on its extension.
|
|
42
|
+
|
|
43
|
+
**Supported formats:** `.json`, `.jsonl`, `.csv`, `.txt`, `.md`, `.pkl`, `.parquet`, `.xlsx`, `.py`, `.npy`, `.pt`, `.png`, `.jpg`, `.jpeg`.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from structai import load_file
|
|
47
|
+
|
|
48
|
+
# Load a JSON file
|
|
49
|
+
data = load_file("config.json")
|
|
50
|
+
|
|
51
|
+
# Load a CSV file as a pandas DataFrame
|
|
52
|
+
df = load_file("data.csv")
|
|
53
|
+
|
|
54
|
+
# Load an image
|
|
55
|
+
image = load_file("photo.jpg")
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### `save_file(data, path)`
|
|
59
|
+
|
|
60
|
+
Automatically saves data to a file based on the extension.
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from structai import save_file
|
|
64
|
+
|
|
65
|
+
data = {"key": "value"}
|
|
66
|
+
|
|
67
|
+
# Save as JSON
|
|
68
|
+
save_file(data, "output.json")
|
|
69
|
+
|
|
70
|
+
# Save as Pickle
|
|
71
|
+
save_file(data, "backup.pkl")
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### `print_once(msg)`
|
|
75
|
+
|
|
76
|
+
Prints a message to stdout only the first time it is called. Useful for logging inside loops.
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from structai import print_once
|
|
80
|
+
|
|
81
|
+
for i in range(10):
|
|
82
|
+
print_once("Starting processing...") # Prints only once
|
|
83
|
+
# process(i)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### `make_print_once()`
|
|
87
|
+
|
|
88
|
+
Returns a new function that prints a message only once. This allows for creating local "print once" scopes.
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from structai import make_print_once
|
|
92
|
+
|
|
93
|
+
logger1 = make_print_once()
|
|
94
|
+
logger2 = make_print_once()
|
|
95
|
+
|
|
96
|
+
logger1("Hello") # Prints "Hello"
|
|
97
|
+
logger1("Hello") # Does nothing
|
|
98
|
+
|
|
99
|
+
logger2("World") # Prints "World"
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### `LLMAgent`
|
|
103
|
+
|
|
104
|
+
A powerful wrapper class for interacting with OpenAI-compatible LLM APIs. It handles retries, timeouts, and structured output validation.
|
|
105
|
+
|
|
106
|
+
**Initialization:**
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from structai import LLMAgent
|
|
110
|
+
|
|
111
|
+
agent = LLMAgent(
|
|
112
|
+
api_key="sk-...", # Optional if LLM_API_KEY env var is set
|
|
113
|
+
api_base="https://...", # Optional if LLM_BASE_URL env var is set
|
|
114
|
+
model_version='gpt-4.1-mini', # Default model
|
|
115
|
+
system_prompt='You are a helpful assistant.',
|
|
116
|
+
temperature=0,
|
|
117
|
+
time_limit=300, # Timeout in seconds
|
|
118
|
+
max_try=1 # Number of retries
|
|
119
|
+
)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
**Basic Usage (`__call__` or `safe_api`):**
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
response = agent("What is the capital of France?")
|
|
126
|
+
print(response)
|
|
127
|
+
# Output: "Paris"
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
**Structured Output Validation:**
|
|
131
|
+
|
|
132
|
+
You can enforce the output format (List, Dict, or specific types) using `return_example`.
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
# Enforce a list of integers
|
|
136
|
+
numbers = agent(
|
|
137
|
+
"Generate 3 random numbers",
|
|
138
|
+
return_example=[1],
|
|
139
|
+
list_len=3
|
|
140
|
+
)
|
|
141
|
+
# Output: [10, 42, 7]
|
|
142
|
+
|
|
143
|
+
# Enforce a dictionary with specific keys
|
|
144
|
+
profile = agent(
|
|
145
|
+
"Create a user profile for Alice",
|
|
146
|
+
return_example={"name": "str", "age": 1, "city": "str"}
|
|
147
|
+
)
|
|
148
|
+
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
**Multimodal Input:**
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
# Pass image paths for vision models
|
|
155
|
+
description = agent(
|
|
156
|
+
"Describe this image",
|
|
157
|
+
image_paths=["image.jpg"]
|
|
158
|
+
)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### `sanitize_text(text)`
|
|
162
|
+
|
|
163
|
+
Sanitizes text by keeping only ASCII English characters, digits, and common punctuation. Removes control characters and ANSI codes.
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
from structai import sanitize_text
|
|
167
|
+
|
|
168
|
+
clean = sanitize_text("Hello \x1b[31mWorld\x1b[0m!")
|
|
169
|
+
print(clean) # "Hello World!"
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### `str2dict(s)`
|
|
173
|
+
|
|
174
|
+
Robustly converts a string representation of a dictionary to a Python `dict`. It handles common formatting errors and uses `json_repair` as a fallback.
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
from structai import str2dict
|
|
178
|
+
|
|
179
|
+
d = str2dict("{'a': 1, 'b': 2}")
|
|
180
|
+
print(d['a']) # 1
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### `str2list(s)`
|
|
184
|
+
|
|
185
|
+
Robustly converts a string representation of a list to a Python `list`.
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
from structai import str2list
|
|
189
|
+
|
|
190
|
+
l = str2list("[1, 2, 3]")
|
|
191
|
+
print(len(l)) # 3
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### `add_no_proxy_if_private(url)`
|
|
195
|
+
|
|
196
|
+
Checks if the hostname in the URL is a private IP address. If so, it adds it to the `no_proxy` environment variable to bypass proxies.
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
from structai import add_no_proxy_if_private
|
|
200
|
+
|
|
201
|
+
add_no_proxy_if_private("http://192.168.1.100:8080/v1")
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### `read_image(image_path)`
|
|
205
|
+
|
|
206
|
+
Reads an image from a path and returns a PIL Image object.
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
from structai import read_image
|
|
210
|
+
|
|
211
|
+
img = read_image("photo.jpg")
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### `encode_image(image_obj)`
|
|
215
|
+
|
|
216
|
+
Encodes a PIL Image object into a base64 string.
|
|
217
|
+
|
|
218
|
+
```python
|
|
219
|
+
from structai import encode_image
|
|
220
|
+
|
|
221
|
+
b64_str = encode_image(img)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### `messages_to_responses_input(messages)`
|
|
225
|
+
|
|
226
|
+
Converts standard Chat Completions `messages` format (list of dicts) to the input format required by the Responses API.
|
|
227
|
+
|
|
228
|
+
```python
|
|
229
|
+
from structai import messages_to_responses_input
|
|
230
|
+
|
|
231
|
+
messages = [{"role": "user", "content": "Hello"}]
|
|
232
|
+
system_prompt, input_blocks = messages_to_responses_input(messages)
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### `extract_text_outputs(result)`
|
|
236
|
+
|
|
237
|
+
Extracts the text content from an LLM API response object (supports both Chat Completions and Responses API formats).
|
|
238
|
+
|
|
239
|
+
```python
|
|
240
|
+
from structai import extract_text_outputs
|
|
241
|
+
|
|
242
|
+
# Assuming 'response' is the object returned by the OpenAI client
|
|
243
|
+
texts = extract_text_outputs(response)
|
|
244
|
+
print(texts[0])
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### `multi_thread(inp_list, function, max_workers=40, use_tqdm=True)`
|
|
248
|
+
|
|
249
|
+
Executes a function concurrently for each item in `inp_list` using a thread pool.
|
|
250
|
+
|
|
251
|
+
```python
|
|
252
|
+
from structai import multi_thread
|
|
253
|
+
import time
|
|
254
|
+
|
|
255
|
+
def square(x):
|
|
256
|
+
return x * x
|
|
257
|
+
|
|
258
|
+
inputs = [{"x": i} for i in range(10)]
|
|
259
|
+
results = multi_thread(inputs, square, max_workers=4)
|
|
260
|
+
print(results) # [0, 1, 4, 9, ...]
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
### `multi_process(inp_list, function, max_workers=40, use_tqdm=True)`
|
|
264
|
+
|
|
265
|
+
Executes a function concurrently for each item in `inp_list` using a process pool. Ideal for CPU-bound tasks.
|
|
266
|
+
|
|
267
|
+
```python
|
|
268
|
+
from structai import multi_process
|
|
269
|
+
|
|
270
|
+
def heavy_computation(n):
|
|
271
|
+
return sum(range(n))
|
|
272
|
+
|
|
273
|
+
inputs = [{"n": 1000000} for _ in range(5)]
|
|
274
|
+
results = multi_process(inputs, heavy_computation)
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
### `run_server(host="0.0.0.0", port=8001)`
|
|
278
|
+
|
|
279
|
+
Starts a FastAPI server that acts as a proxy to an OpenAI-compatible LLM provider.
|
|
280
|
+
|
|
281
|
+
```python
|
|
282
|
+
from structai import run_server
|
|
283
|
+
|
|
284
|
+
if __name__ == "__main__":
|
|
285
|
+
run_server()
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
### `timeout_limit(timeout=None)`
|
|
289
|
+
|
|
290
|
+
A decorator that enforces a maximum execution time on a function. Raises `TimeoutError` if the limit is exceeded.
|
|
291
|
+
|
|
292
|
+
```python
|
|
293
|
+
from structai import timeout_limit
|
|
294
|
+
import time
|
|
295
|
+
|
|
296
|
+
@timeout_limit(timeout=2.0)
|
|
297
|
+
def task():
|
|
298
|
+
time.sleep(5)
|
|
299
|
+
|
|
300
|
+
# This will raise TimeoutError
|
|
301
|
+
task()
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
### `run_with_timeout(func, args=(), kwargs=None, timeout=None)`
|
|
305
|
+
|
|
306
|
+
Runs a function with a specified timeout without using a decorator.
|
|
307
|
+
|
|
308
|
+
```python
|
|
309
|
+
from structai import run_with_timeout
|
|
310
|
+
|
|
311
|
+
def task(x):
|
|
312
|
+
return x * 2
|
|
313
|
+
|
|
314
|
+
result = run_with_timeout(task, args=(10,), timeout=1.0)
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
### `parse_think_answer(text)`
|
|
318
|
+
|
|
319
|
+
Parses a string containing Chain-of-Thought tags (`<think>...</think>` and `<answer>...</answer>`) and returns the content of both.
|
|
320
|
+
|
|
321
|
+
```python
|
|
322
|
+
from structai import parse_think_answer
|
|
323
|
+
|
|
324
|
+
raw_text = "<think>Step 1...</think><answer>42</answer>"
|
|
325
|
+
think, answer = parse_think_answer(raw_text)
|
|
326
|
+
print(f"Reasoning: {think}")
|
|
327
|
+
print(f"Result: {answer}")
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
### `extract_within_tags(content, start_tag='<answer>', end_tag='</answer>', default_return=None)`
|
|
331
|
+
|
|
332
|
+
Extracts the substring found between two specific tags.
|
|
333
|
+
|
|
334
|
+
```python
|
|
335
|
+
from structai import extract_within_tags
|
|
336
|
+
|
|
337
|
+
text = "Result: <json>{...}</json>"
|
|
338
|
+
json_str = extract_within_tags(text, "<json>", "</json>")
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
### `get_all_file_paths(directory, suffix='')`
|
|
342
|
+
|
|
343
|
+
Recursively retrieves all file paths in a directory that match a given suffix.
|
|
344
|
+
|
|
345
|
+
```python
|
|
346
|
+
from structai import get_all_file_paths
|
|
347
|
+
|
|
348
|
+
# Get all Python files in the current directory
|
|
349
|
+
py_files = get_all_file_paths(".", suffix=".py")
|
|
350
|
+
print(py_files)
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
### `remove_tag(s, tags=["<think>", "</think>", "<answer>", "</answer>"], r="\n")`
|
|
354
|
+
|
|
355
|
+
Removes specified tags from a string, replacing them with a separator (default newline).
|
|
356
|
+
|
|
357
|
+
```python
|
|
358
|
+
from structai import remove_tag
|
|
359
|
+
|
|
360
|
+
clean_text = remove_tag("<think>...</think> Answer")
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
## License
|
|
364
|
+
|
|
365
|
+
MIT License
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
structai/__init__.py,sha256=yBDB992YquQR9Q2GYgXu_RSd0VvdVSVnylul6xmou9g,931
|
|
2
|
+
structai/io.py,sha256=RRNa636ogLc9eBongp5x57bUvD6I-u_gCo8MhptG0dk,6287
|
|
3
|
+
structai/llm_api.py,sha256=vWm6sEt4NF_TM210bXzEi6bQklVl615LjccDukvmcLk,26829
|
|
4
|
+
structai/mp.py,sha256=MDlue6HkbH-36Vj46rBNMZmzJxnqsDOdItZ486kxZyA,3830
|
|
5
|
+
structai/openai_server.py,sha256=Y2Lh0ZoQ9bGbRj_8u7Jq8T9MPcQKPmLANlqzCTJZ9VY,2198
|
|
6
|
+
structai/utils.py,sha256=Ew6kpDWBx2vKVM3BmHMrerX1x5rkOX1ypVum23x9oHw,6849
|
|
7
|
+
structai-0.1.0.dist-info/licenses/LICENSE,sha256=_0ZnMMmgcegAB7zHqUl8SK5s6Hi2VHMPpCSBu9o7HjQ,1067
|
|
8
|
+
structai-0.1.0.dist-info/METADATA,sha256=BqbdrNDOGro1SMSV43voDwbKHAmdC3uLt7sF3fH-3UA,8659
|
|
9
|
+
structai-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
10
|
+
structai-0.1.0.dist-info/top_level.txt,sha256=wb5Z23kqdKQx7yyzv9RePWxlKrUF28PFJdEGMC2AIjQ,9
|
|
11
|
+
structai-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Wanghan Xu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
structai
|