structai 0.1.6__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 +586 -0
- structai/io.py +227 -0
- structai/llm_api.py +713 -0
- structai/mp.py +96 -0
- structai/openai_server.py +79 -0
- structai/utils.py +209 -0
- structai-0.1.6.dist-info/METADATA +601 -0
- structai-0.1.6.dist-info/RECORD +11 -0
- structai-0.1.6.dist-info/WHEEL +5 -0
- structai-0.1.6.dist-info/licenses/LICENSE +21 -0
- structai-0.1.6.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: structai
|
|
3
|
+
Version: 0.1.6
|
|
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
|
+
> **Recommended for most users.** Installs the latest stable release from PyPI.
|
|
32
|
+
```bash
|
|
33
|
+
pip install structai
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
> **For development.** Installs StructAI in editable mode from source, enabling live code changes.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
git clone https://github.com/black-yt/structai.git
|
|
40
|
+
cd structai
|
|
41
|
+
pip install -e .
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
> **Note:** Before using LLM-related features, please ensure you have set the necessary environment variables:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
export LLM_API_KEY="your-api-key"
|
|
48
|
+
export LLM_BASE_URL="your-api-base-url"
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## StructAI Library Documentation
|
|
54
|
+
|
|
55
|
+
### `structai_skill`
|
|
56
|
+
|
|
57
|
+
Returns a comprehensive documentation string for the StructAI library in Markdown format. This is useful for providing context to LLMs about the available tools in this library.
|
|
58
|
+
|
|
59
|
+
* **Args**:
|
|
60
|
+
* None
|
|
61
|
+
* **Returns**:
|
|
62
|
+
* (str): The documentation string.
|
|
63
|
+
|
|
64
|
+
* **Example**:
|
|
65
|
+
```python
|
|
66
|
+
from structai import structai_skill
|
|
67
|
+
|
|
68
|
+
docs = structai_skill()
|
|
69
|
+
print(docs)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
### `load_file`
|
|
74
|
+
Automatically reads a file based on its extension.
|
|
75
|
+
|
|
76
|
+
* **Args**:
|
|
77
|
+
* `path` (str): The path to the file to be read.
|
|
78
|
+
* **Returns**:
|
|
79
|
+
* (Any): The content of the file, parsed into an appropriate Python object.
|
|
80
|
+
* `.json` -> `dict` or `list`
|
|
81
|
+
* `.jsonl` -> `list` of dicts
|
|
82
|
+
* `.csv`, `.parquet`, `.xlsx` -> `pandas.DataFrame`
|
|
83
|
+
* `.txt`, `.md`, `.py` -> `str`
|
|
84
|
+
* `.pkl` -> unpickled object
|
|
85
|
+
* `.npy` -> `numpy.ndarray`
|
|
86
|
+
* `.pt` -> `torch` object
|
|
87
|
+
* `.png`, `.jpg`, `.jpeg` -> `PIL.Image.Image`
|
|
88
|
+
|
|
89
|
+
* **Example**:
|
|
90
|
+
```python
|
|
91
|
+
from structai import load_file
|
|
92
|
+
|
|
93
|
+
# Load a JSON file
|
|
94
|
+
data = load_file("config.json")
|
|
95
|
+
|
|
96
|
+
# Load a CSV file as a pandas DataFrame
|
|
97
|
+
df = load_file("data.csv")
|
|
98
|
+
|
|
99
|
+
# Load an image
|
|
100
|
+
image = load_file("photo.jpg")
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### `save_file`
|
|
104
|
+
Automatically saves data to a file based on the extension. Creates necessary directories if they don't exist.
|
|
105
|
+
|
|
106
|
+
* **Args**:
|
|
107
|
+
* `data` (Any): The data object to save.
|
|
108
|
+
* `path` (str): The destination file path.
|
|
109
|
+
* **Returns**:
|
|
110
|
+
* None
|
|
111
|
+
|
|
112
|
+
* **Example**:
|
|
113
|
+
```python
|
|
114
|
+
from structai import save_file
|
|
115
|
+
|
|
116
|
+
data = {"key": "value"}
|
|
117
|
+
|
|
118
|
+
# Save as JSON
|
|
119
|
+
save_file(data, "output.json")
|
|
120
|
+
|
|
121
|
+
# Save as Pickle
|
|
122
|
+
save_file(data, "backup.pkl")
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### `print_once`
|
|
126
|
+
Prints a message to stdout only once during the entire program execution. Useful for logging warnings or info inside loops.
|
|
127
|
+
|
|
128
|
+
* **Args**:
|
|
129
|
+
* `msg` (str): The message to print.
|
|
130
|
+
* **Returns**:
|
|
131
|
+
* None
|
|
132
|
+
|
|
133
|
+
* **Example**:
|
|
134
|
+
```python
|
|
135
|
+
from structai import print_once
|
|
136
|
+
|
|
137
|
+
for i in range(10):
|
|
138
|
+
print_once("Starting processing...") # print only once
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### `make_print_once`
|
|
142
|
+
Creates and returns a local function that prints a message only once. This is useful if you need a "print once" behavior scoped to a specific function or instance rather than globally.
|
|
143
|
+
|
|
144
|
+
* **Args**:
|
|
145
|
+
* None
|
|
146
|
+
* **Returns**:
|
|
147
|
+
* (callable): A function `inner(msg)` that behaves like `print_once`.
|
|
148
|
+
|
|
149
|
+
* **Example**:
|
|
150
|
+
```python
|
|
151
|
+
from structai import make_print_once
|
|
152
|
+
|
|
153
|
+
logger1 = make_print_once()
|
|
154
|
+
logger2 = make_print_once()
|
|
155
|
+
|
|
156
|
+
logger1("Hello") # Prints "Hello"
|
|
157
|
+
logger1("Hello") # Does nothing
|
|
158
|
+
|
|
159
|
+
logger2("World") # Prints "World"
|
|
160
|
+
logger2("World") # Does nothing
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### `LLMAgent` Class
|
|
164
|
+
|
|
165
|
+
A powerful wrapper class for interacting with OpenAI-compatible LLM APIs. It handles retries, timeouts, and structured output validation.
|
|
166
|
+
|
|
167
|
+
#### `initialization`
|
|
168
|
+
|
|
169
|
+
* **Args**:
|
|
170
|
+
* `api_key` (str, optional): API Key. Defaults to `os.environ["LLM_API_KEY"]`.
|
|
171
|
+
* `api_base` (str, optional): Base URL. Defaults to `os.environ["LLM_BASE_URL"]`.
|
|
172
|
+
* `model_version` (str, optional): Model identifier. Default `'gpt-4.1-mini'`.
|
|
173
|
+
* `system_prompt` (str, optional): Default system prompt. Default `'You are a helpful assistant.'`.
|
|
174
|
+
* `max_tokens` (int, optional): Maximum tokens for generation. Default `None`.
|
|
175
|
+
* `temperature` (float, optional): Sampling temperature. Default `0`.
|
|
176
|
+
* `http_client` (httpx.Client, optional): Optional custom httpx client.
|
|
177
|
+
* `headers` (dict, optional): Optional custom headers.
|
|
178
|
+
* `time_limit` (int, optional): Timeout in seconds. Default `300` (5 minutes).
|
|
179
|
+
* `max_try` (int, optional): Default number of retries. Default `1`.
|
|
180
|
+
* `use_responses_api` (bool, optional): Whether to use the Responses API format. Default `False`.
|
|
181
|
+
|
|
182
|
+
* **Returns**:
|
|
183
|
+
* (LLMAgent): LLMAgent instance.
|
|
184
|
+
|
|
185
|
+
* **Example**:
|
|
186
|
+
```python
|
|
187
|
+
from structai import LLMAgent
|
|
188
|
+
|
|
189
|
+
agent = LLMAgent()
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
#### `__call__`
|
|
193
|
+
Sends a query to the LLM with built-in validation, parsing, and retry logic.
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
* **Args**:
|
|
197
|
+
* `query` (str): The main input text or prompt to be sent to the LLM.
|
|
198
|
+
* `system_prompt` (str, optional): The system instruction. Overrides the default if provided.
|
|
199
|
+
* `return_example` (str | list | dict, optional): A template defining the expected structure and type of the response.
|
|
200
|
+
* `None` or `str` (default): Returns raw response string.
|
|
201
|
+
* `list`: Expects a JSON list string. Validates element types if example elements are provided.
|
|
202
|
+
* `dict`: Expects a JSON object string. Validates keys (supports fuzzy matching).
|
|
203
|
+
* `max_try` (int, optional): Max attempts. Defaults to instance's `max_try`.
|
|
204
|
+
* `wait_time` (float, optional): Time in seconds to wait between retries. Default `0.0`.
|
|
205
|
+
* `n` (int, optional): Number of completion choices. Default `1`.
|
|
206
|
+
* `max_tokens` (int, optional): Overrides instance's `max_tokens`.
|
|
207
|
+
* `temperature` (float, optional): Overrides instance's `temperature`.
|
|
208
|
+
* `image_paths` (list[str], optional): List of local image paths for multimodal models.
|
|
209
|
+
* `history` (list[dict], optional): Conversation history `[{"role": "user", "content": "..."}, ...]`.
|
|
210
|
+
* `use_responses_api` (bool, optional): Overrides instance setting.
|
|
211
|
+
* `list_len` (int, optional): *Validation* - Enforces exact list length.
|
|
212
|
+
* `list_min` (int | float, optional): *Validation* - Enforces minimum value for list elements.
|
|
213
|
+
* `list_max` (int | float, optional): *Validation* - Enforces maximum value for list elements.
|
|
214
|
+
* `check_keys` (bool, optional): *Validation* - Whether to validate dict keys. Default `True`.
|
|
215
|
+
|
|
216
|
+
* **Returns**:
|
|
217
|
+
* (str | list | dict): The parsed response from the LLM.
|
|
218
|
+
* If `n > 1`, returns a list of results.
|
|
219
|
+
* Returns `None` if all retries fail.
|
|
220
|
+
|
|
221
|
+
* **Example**:
|
|
222
|
+
```python
|
|
223
|
+
# Basic usage
|
|
224
|
+
response = agent("Generate a random number.", n=3, temperature=1)
|
|
225
|
+
# Output: ["Sure! Here's a random number for you: 738", "Sure! Here's a random number: 7382", "Sure! Here's a random number: 487."]
|
|
226
|
+
|
|
227
|
+
# Enforce the output format (List, Dict, or specific types) using `return_example`. Note that the output format needs to be explicitly specified in the prompt.
|
|
228
|
+
numbers = agent(
|
|
229
|
+
"Generate 3 random numbers, for example, [1, 2, 3].",
|
|
230
|
+
return_example=[1],
|
|
231
|
+
list_len=3
|
|
232
|
+
)
|
|
233
|
+
# Output: [10, 42, 7]
|
|
234
|
+
|
|
235
|
+
profile = agent(
|
|
236
|
+
"Create a user profile for Alice, for example, {'name': Alice, 'age': 1, 'city': 'shanghai'}.",
|
|
237
|
+
return_example={"name": "str", "age": 1, "city": "str"}
|
|
238
|
+
)
|
|
239
|
+
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
|
|
240
|
+
|
|
241
|
+
# Multimodal input for vision models
|
|
242
|
+
description = agent(
|
|
243
|
+
"Describe these images",
|
|
244
|
+
image_paths=["path/to/image_1.jpg", "path/to/image_2.jpg"]
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
# Memory context
|
|
248
|
+
history = [
|
|
249
|
+
{"role": "user", "content": "My name is Bob."},
|
|
250
|
+
{"role": "assistant", "content": "Hello Bob."}
|
|
251
|
+
]
|
|
252
|
+
answer = agent(
|
|
253
|
+
"What is my name?",
|
|
254
|
+
history=history,
|
|
255
|
+
)
|
|
256
|
+
# Output: 'Your name is Bob.'
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
### `sanitize_text`
|
|
260
|
+
|
|
261
|
+
Sanitizes text by keeping only ASCII English characters, digits, and common punctuation. Removes control characters and ANSI codes.
|
|
262
|
+
|
|
263
|
+
* **Args**:
|
|
264
|
+
* `text` (str): The text to sanitize.
|
|
265
|
+
* **Returns**:
|
|
266
|
+
* (str): The sanitized text.
|
|
267
|
+
|
|
268
|
+
* **Example**:
|
|
269
|
+
```python
|
|
270
|
+
from structai import sanitize_text
|
|
271
|
+
|
|
272
|
+
clean = sanitize_text("Hello \x1b[31mWorld\x1b[0m!")
|
|
273
|
+
print(clean) # 'Hello [31mWorld[0m!'
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
### `filter_excessive_repeats`
|
|
277
|
+
|
|
278
|
+
Identifies sequences where a single character or a two-character substring repeats at least the specified threshold times and removes them entirely from the string.
|
|
279
|
+
|
|
280
|
+
* **Args**:
|
|
281
|
+
* `text` (str): The input string.
|
|
282
|
+
* `threshold` (int, optional): The maximum allowed consecutive repetitions. Default `5`.
|
|
283
|
+
* **Returns**:
|
|
284
|
+
* (str): The processed string with excessive repetitions removed.
|
|
285
|
+
|
|
286
|
+
* **Example**:
|
|
287
|
+
```python
|
|
288
|
+
from structai import filter_excessive_repeats
|
|
289
|
+
|
|
290
|
+
clean = filter_excessive_repeats("Helloooooo World", threshold=5)
|
|
291
|
+
print(clean) # "Hell World"
|
|
292
|
+
|
|
293
|
+
clean = filter_excessive_repeats("Hello\\b\\b World", threshold=2)
|
|
294
|
+
print(clean) # "Heo World"
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
### `str2dict`
|
|
298
|
+
|
|
299
|
+
Robustly converts a string representation of a dictionary to a Python `dict`. It handles common formatting errors and uses `json_repair` as a fallback.
|
|
300
|
+
|
|
301
|
+
* **Args**:
|
|
302
|
+
* `s` (str): The string representation of a dictionary.
|
|
303
|
+
* **Returns**:
|
|
304
|
+
* (dict): The parsed dictionary.
|
|
305
|
+
|
|
306
|
+
* **Example**:
|
|
307
|
+
```python
|
|
308
|
+
from structai import str2dict
|
|
309
|
+
|
|
310
|
+
d = str2dict("{'a': 1, 'b': 2}")
|
|
311
|
+
print(d['a']) # 1
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
### `str2list`
|
|
315
|
+
|
|
316
|
+
Robustly converts a string representation of a list to a Python `list`.
|
|
317
|
+
|
|
318
|
+
* **Args**:
|
|
319
|
+
* `s` (str): The string representation of a list.
|
|
320
|
+
* **Returns**:
|
|
321
|
+
* (list): The parsed list.
|
|
322
|
+
|
|
323
|
+
* **Example**:
|
|
324
|
+
```python
|
|
325
|
+
from structai import str2list
|
|
326
|
+
|
|
327
|
+
l = str2list("[1, 2, 3]")
|
|
328
|
+
print(len(l)) # 3
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
### `add_no_proxy_if_private`
|
|
332
|
+
|
|
333
|
+
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.
|
|
334
|
+
|
|
335
|
+
* **Args**:
|
|
336
|
+
* `url` (str): The URL to check.
|
|
337
|
+
* **Returns**:
|
|
338
|
+
* None
|
|
339
|
+
|
|
340
|
+
* **Example**:
|
|
341
|
+
```python
|
|
342
|
+
from structai import add_no_proxy_if_private
|
|
343
|
+
|
|
344
|
+
add_no_proxy_if_private("http://192.168.1.100:8080/v1")
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
### `read_image`
|
|
348
|
+
|
|
349
|
+
Reads an image from a path and returns a PIL Image object.
|
|
350
|
+
|
|
351
|
+
* **Args**:
|
|
352
|
+
* `image_path` (str): The path to the image file.
|
|
353
|
+
* **Returns**:
|
|
354
|
+
* (PIL.Image.Image): The loaded image object.
|
|
355
|
+
|
|
356
|
+
* **Example**:
|
|
357
|
+
```python
|
|
358
|
+
from structai import read_image
|
|
359
|
+
|
|
360
|
+
img = read_image("photo.jpg")
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
### `encode_image`
|
|
364
|
+
|
|
365
|
+
Encodes a PIL Image object into a base64 string.
|
|
366
|
+
|
|
367
|
+
* **Args**:
|
|
368
|
+
* `image_obj` (PIL.Image.Image): The image object to encode.
|
|
369
|
+
* **Returns**:
|
|
370
|
+
* (str): The base64 encoded string.
|
|
371
|
+
|
|
372
|
+
* **Example**:
|
|
373
|
+
```python
|
|
374
|
+
from structai import encode_image
|
|
375
|
+
|
|
376
|
+
b64_str = encode_image(img)
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
### `messages_to_responses_input`
|
|
380
|
+
|
|
381
|
+
Converts standard Chat Completions `messages` format (list of dicts) to the input format required by the Responses API.
|
|
382
|
+
|
|
383
|
+
* **Args**:
|
|
384
|
+
* `messages` (list[dict]): List of message dictionaries with 'role' and 'content'.
|
|
385
|
+
* **Returns**:
|
|
386
|
+
* (tuple): A tuple containing `(system_prompt_content, input_blocks)`.
|
|
387
|
+
|
|
388
|
+
* **Example**:
|
|
389
|
+
```python
|
|
390
|
+
from structai import messages_to_responses_input
|
|
391
|
+
|
|
392
|
+
messages = [{"role": "user", "content": "Hello"}]
|
|
393
|
+
system_prompt, input_blocks = messages_to_responses_input(messages)
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
### `extract_text_outputs`
|
|
397
|
+
|
|
398
|
+
Extracts the text content from an LLM API response object (supports both Chat Completions and Responses API formats).
|
|
399
|
+
|
|
400
|
+
* **Args**:
|
|
401
|
+
* `result` (object): The response object from the LLM API.
|
|
402
|
+
* **Returns**:
|
|
403
|
+
* (list[str]): A list of extracted text outputs.
|
|
404
|
+
|
|
405
|
+
* **Example**:
|
|
406
|
+
```python
|
|
407
|
+
from structai import extract_text_outputs
|
|
408
|
+
|
|
409
|
+
# Assuming 'response' is the object returned by the OpenAI client
|
|
410
|
+
texts = extract_text_outputs(response)
|
|
411
|
+
print(texts[0])
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
### `multi_thread`
|
|
415
|
+
|
|
416
|
+
Executes a function concurrently for each item in `inp_list` using a thread pool.
|
|
417
|
+
|
|
418
|
+
* **Args**:
|
|
419
|
+
* `inp_list` (list[dict]): A list of dictionaries, where each dictionary contains keyword arguments for `function`.
|
|
420
|
+
* `function` (callable): The function to execute.
|
|
421
|
+
* `max_workers` (int, optional): The maximum number of threads. Default `40`.
|
|
422
|
+
* `use_tqdm` (bool, optional): Whether to show a progress bar. Default `True`.
|
|
423
|
+
* **Returns**:
|
|
424
|
+
* (list): A list of results corresponding to the input list order.
|
|
425
|
+
|
|
426
|
+
* **Example**:
|
|
427
|
+
```python
|
|
428
|
+
from structai import multi_thread
|
|
429
|
+
import time
|
|
430
|
+
|
|
431
|
+
def square(x):
|
|
432
|
+
return x * x
|
|
433
|
+
|
|
434
|
+
inputs = [{"x": i} for i in range(10)]
|
|
435
|
+
results = multi_thread(inputs, square, max_workers=4)
|
|
436
|
+
print(results) # [0, 1, 4, 9, ...]
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
### `multi_process`
|
|
440
|
+
|
|
441
|
+
Executes a function concurrently for each item in `inp_list` using a process pool. Ideal for CPU-bound tasks.
|
|
442
|
+
|
|
443
|
+
* **Args**:
|
|
444
|
+
* `inp_list` (list[dict]): A list of dictionaries, where each dictionary contains keyword arguments for `function`.
|
|
445
|
+
* `function` (callable): The function to execute.
|
|
446
|
+
* `max_workers` (int, optional): The maximum number of processes. Default `40`.
|
|
447
|
+
* `use_tqdm` (bool, optional): Whether to show a progress bar. Default `True`.
|
|
448
|
+
* **Returns**:
|
|
449
|
+
* (list): A list of results corresponding to the input list order.
|
|
450
|
+
|
|
451
|
+
* **Example**:
|
|
452
|
+
```python
|
|
453
|
+
from structai import multi_process
|
|
454
|
+
|
|
455
|
+
# 'heavy_computation' must be defined at the top level for multiprocessing pickling.
|
|
456
|
+
def heavy_computation(n):
|
|
457
|
+
return sum(range(n))
|
|
458
|
+
|
|
459
|
+
inputs = [{"n": 1000} for _ in range(5)]
|
|
460
|
+
results = multi_process(inputs, heavy_computation)
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
### `run_server`
|
|
464
|
+
|
|
465
|
+
Starts a FastAPI server that acts as a proxy to an OpenAI-compatible LLM provider using LLM_BASE_URL and LLM_API_KEY in environment variables.
|
|
466
|
+
|
|
467
|
+
* **Args**:
|
|
468
|
+
* `host` (str, optional): The host to bind to. Default `"0.0.0.0"`.
|
|
469
|
+
* `port` (int, optional): The port to bind to. Default `8001`.
|
|
470
|
+
* **Returns**:
|
|
471
|
+
* None (Runs indefinitely until stopped).
|
|
472
|
+
|
|
473
|
+
* **Example**:
|
|
474
|
+
```python
|
|
475
|
+
from structai import run_server
|
|
476
|
+
|
|
477
|
+
if __name__ == "__main__":
|
|
478
|
+
run_server()
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
### `timeout_limit`
|
|
482
|
+
|
|
483
|
+
A decorator that enforces a maximum execution time on a function. Raises `TimeoutError` if the limit is exceeded.
|
|
484
|
+
|
|
485
|
+
* **Args**:
|
|
486
|
+
* `timeout` (float | None): Maximum allowed execution time in seconds.
|
|
487
|
+
* **Returns**:
|
|
488
|
+
* (decorator): A decorator function that wraps the target function.
|
|
489
|
+
|
|
490
|
+
* **Example**:
|
|
491
|
+
```python
|
|
492
|
+
from structai import timeout_limit
|
|
493
|
+
import time
|
|
494
|
+
|
|
495
|
+
@timeout_limit(timeout=2.0)
|
|
496
|
+
def task():
|
|
497
|
+
time.sleep(5)
|
|
498
|
+
|
|
499
|
+
# This will raise TimeoutError
|
|
500
|
+
task()
|
|
501
|
+
```
|
|
502
|
+
|
|
503
|
+
### `run_with_timeout`
|
|
504
|
+
|
|
505
|
+
Runs a function with a specified timeout without using a decorator.
|
|
506
|
+
|
|
507
|
+
* **Args**:
|
|
508
|
+
* `func` (callable): The function to run.
|
|
509
|
+
* `args` (tuple, optional): Positional arguments for the function. Default `()`.
|
|
510
|
+
* `kwargs` (dict, optional): Keyword arguments for the function. Default `None`.
|
|
511
|
+
* `timeout` (float | None): Maximum allowed execution time in seconds.
|
|
512
|
+
* **Returns**:
|
|
513
|
+
* (Any): The return value of the function.
|
|
514
|
+
|
|
515
|
+
* **Example**:
|
|
516
|
+
```python
|
|
517
|
+
from structai import run_with_timeout
|
|
518
|
+
|
|
519
|
+
def task(x):
|
|
520
|
+
return x * 2
|
|
521
|
+
|
|
522
|
+
result = run_with_timeout(task, args=(10,), timeout=1.0)
|
|
523
|
+
```
|
|
524
|
+
|
|
525
|
+
### `remove_tag`
|
|
526
|
+
|
|
527
|
+
Removes specified tags from a string, replacing them with a separator (default newline).
|
|
528
|
+
|
|
529
|
+
* **Args**:
|
|
530
|
+
* `s` (str): The input string.
|
|
531
|
+
* `tags` (list[str], optional): A list of tags to remove. Default `["<think>", "</think>", "<answer>", "</answer>"]`.
|
|
532
|
+
* `r` (str, optional): The replacement string. Default `"\n"`.
|
|
533
|
+
* **Returns**:
|
|
534
|
+
* (str): The cleaned string.
|
|
535
|
+
|
|
536
|
+
* **Example**:
|
|
537
|
+
```python
|
|
538
|
+
from structai import remove_tag
|
|
539
|
+
|
|
540
|
+
clean_text = remove_tag("<think>...</think> Answer")
|
|
541
|
+
# Output: "...\n Answer"
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
### `parse_think_answer`
|
|
545
|
+
|
|
546
|
+
Parses a string containing Chain-of-Thought tags (`<think>...</think>` and `<answer>...</answer>`) and returns the content of both.
|
|
547
|
+
|
|
548
|
+
* **Args**:
|
|
549
|
+
* `text` (str): The input text containing the tags.
|
|
550
|
+
* **Returns**:
|
|
551
|
+
* (tuple): A tuple `(think_content, answer_content)`.
|
|
552
|
+
|
|
553
|
+
* **Example**:
|
|
554
|
+
```python
|
|
555
|
+
from structai import parse_think_answer
|
|
556
|
+
|
|
557
|
+
raw_text = "<think>Step 1...</think><answer>42</answer>"
|
|
558
|
+
think, answer = parse_think_answer(raw_text)
|
|
559
|
+
print(f"Reasoning: {think}") # Reasoning: Step 1...
|
|
560
|
+
print(f"Result: {answer}") # Result: 42
|
|
561
|
+
```
|
|
562
|
+
|
|
563
|
+
### `extract_within_tags`
|
|
564
|
+
|
|
565
|
+
Extracts the substring found between two specific tags.
|
|
566
|
+
|
|
567
|
+
* **Args**:
|
|
568
|
+
* `content` (str): The text to search within.
|
|
569
|
+
* `start_tag` (str, optional): The opening tag. Default `'<answer>'`.
|
|
570
|
+
* `end_tag` (str, optional): The closing tag. Default `'</answer>'`.
|
|
571
|
+
* `default_return` (Any, optional): The value to return if tags are not found. Default `None`.
|
|
572
|
+
* **Returns**:
|
|
573
|
+
* (str | Any): The extracted content string, or `default_return` if not found.
|
|
574
|
+
|
|
575
|
+
* **Example**:
|
|
576
|
+
```python
|
|
577
|
+
from structai import extract_within_tags
|
|
578
|
+
|
|
579
|
+
text = "Result: <json>{...}</json>"
|
|
580
|
+
json_str = extract_within_tags(text, "<json>", "</json>")
|
|
581
|
+
# Output: "{...}"
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
### `get_all_file_paths`
|
|
585
|
+
|
|
586
|
+
Recursively retrieves all file paths in a directory that match a given suffix.
|
|
587
|
+
|
|
588
|
+
* **Args**:
|
|
589
|
+
* `directory` (str): The root directory to search.
|
|
590
|
+
* `suffix` (str, optional): The file suffix to filter by (e.g., '.py'). Default `''` (matches all files).
|
|
591
|
+
* **Returns**:
|
|
592
|
+
* (list[str]): A list of matching file paths.
|
|
593
|
+
|
|
594
|
+
* **Example**:
|
|
595
|
+
```python
|
|
596
|
+
from structai import get_all_file_paths
|
|
597
|
+
|
|
598
|
+
# Get all Python files in the current directory
|
|
599
|
+
py_files = get_all_file_paths(".", suffix=".py")
|
|
600
|
+
print(py_files)
|
|
601
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
structai/__init__.py,sha256=Rj8O-vIsf2htP46Se5-4ml25QhZqRZOMmgir8pzQQtc,17826
|
|
2
|
+
structai/io.py,sha256=RRNa636ogLc9eBongp5x57bUvD6I-u_gCo8MhptG0dk,6287
|
|
3
|
+
structai/llm_api.py,sha256=PBpWkqq9jrbPsqgmFvuAxXfd3FmO9SBqs4zfe_WtmSE,27776
|
|
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.6.dist-info/licenses/LICENSE,sha256=_0ZnMMmgcegAB7zHqUl8SK5s6Hi2VHMPpCSBu9o7HjQ,1067
|
|
8
|
+
structai-0.1.6.dist-info/METADATA,sha256=EFZjiPBCyrU4IcSmdFeqURVIGE6x9ZkBg3o1Wyyuy4E,18018
|
|
9
|
+
structai-0.1.6.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
10
|
+
structai-0.1.6.dist-info/top_level.txt,sha256=wb5Z23kqdKQx7yyzv9RePWxlKrUF28PFJdEGMC2AIjQ,9
|
|
11
|
+
structai-0.1.6.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
|