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