Skip to main content

A utility package for AI development

Project description

StructAI

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.

Installation

Recommended for most users. Installs the latest stable release from PyPI.

pip install structai

For development. Installs StructAI in editable mode from source, enabling live code changes.

git clone https://github.com/black-yt/structai.git
cd structai
pip install -e .

API Reference & Usage

load_file(path)

Automatically reads a file based on its extension.

Supported formats: .json, .jsonl, .csv, .txt, .md, .pkl, .parquet, .xlsx, .py, .npy, .pt, .png, .jpg, .jpeg.

from structai import load_file

# Load a JSON file
data = load_file("config.json")

# Load a CSV file as a pandas DataFrame
df = load_file("data.csv")

# Load an image
image = load_file("photo.jpg")

save_file(data, path)

Automatically saves data to a file based on the extension.

from structai import save_file

data = {"key": "value"}

# Save as JSON
save_file(data, "output.json")

# Save as Pickle
save_file(data, "backup.pkl")

print_once(msg)

Prints a message to stdout only the first time it is called. Useful for logging inside loops.

from structai import print_once

for i in range(10):
    print_once("Starting processing...") # Prints only once
    # process(i)

make_print_once()

Returns a new function that prints a message only once. This allows for creating local "print once" scopes.

from structai import make_print_once

logger1 = make_print_once()
logger2 = make_print_once()

logger1("Hello") # Prints "Hello"
logger1("Hello") # Does nothing

logger2("World") # Prints "World"

LLMAgent

A powerful wrapper class for interacting with OpenAI-compatible LLM APIs. It handles retries, timeouts, and structured output validation.

Initialization:

from structai import LLMAgent

agent = LLMAgent(
    api_key="sk-...",              # Optional if LLM_API_KEY env var is set
    api_base="https://...",        # Optional if LLM_BASE_URL env var is set
    model_version='gpt-4.1-mini',  # Default model
    system_prompt='You are a helpful assistant.',
    temperature=0,
    time_limit=300,                # Timeout in seconds
    max_try=1                      # Number of retries
)

Basic Usage (__call__ or safe_api):

response = agent("What is the capital of France?")
print(response)
# Output: "Paris"

Structured Output Validation:

You can enforce the output format (List, Dict, or specific types) using return_example.

# Enforce a list of integers
numbers = agent(
    "Generate 3 random numbers", 
    return_example=[1], 
    list_len=3
)
# Output: [10, 42, 7]

# Enforce a dictionary with specific keys
profile = agent(
    "Create a user profile for Alice", 
    return_example={"name": "str", "age": 1, "city": "str"}
)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Multimodal Input:

# Pass image paths for vision models
description = agent(
    "Describe this image", 
    image_paths=["image.jpg"]
)

sanitize_text(text)

Sanitizes text by keeping only ASCII English characters, digits, and common punctuation. Removes control characters and ANSI codes.

from structai import sanitize_text

clean = sanitize_text("Hello \x1b[31mWorld\x1b[0m!")
print(clean) # "Hello World!"

str2dict(s)

Robustly converts a string representation of a dictionary to a Python dict. It handles common formatting errors and uses json_repair as a fallback.

from structai import str2dict

d = str2dict("{'a': 1, 'b': 2}")
print(d['a']) # 1

str2list(s)

Robustly converts a string representation of a list to a Python list.

from structai import str2list

l = str2list("[1, 2, 3]")
print(len(l)) # 3

add_no_proxy_if_private(url)

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.

from structai import add_no_proxy_if_private

add_no_proxy_if_private("http://192.168.1.100:8080/v1")

read_image(image_path)

Reads an image from a path and returns a PIL Image object.

from structai import read_image

img = read_image("photo.jpg")

encode_image(image_obj)

Encodes a PIL Image object into a base64 string.

from structai import encode_image

b64_str = encode_image(img)

messages_to_responses_input(messages)

Converts standard Chat Completions messages format (list of dicts) to the input format required by the Responses API.

from structai import messages_to_responses_input

messages = [{"role": "user", "content": "Hello"}]
system_prompt, input_blocks = messages_to_responses_input(messages)

extract_text_outputs(result)

Extracts the text content from an LLM API response object (supports both Chat Completions and Responses API formats).

from structai import extract_text_outputs

# Assuming 'response' is the object returned by the OpenAI client
texts = extract_text_outputs(response)
print(texts[0])

multi_thread(inp_list, function, max_workers=40, use_tqdm=True)

Executes a function concurrently for each item in inp_list using a thread pool.

from structai import multi_thread
import time

def square(x):
    return x * x

inputs = [{"x": i} for i in range(10)]
results = multi_thread(inputs, square, max_workers=4)
print(results) # [0, 1, 4, 9, ...]

multi_process(inp_list, function, max_workers=40, use_tqdm=True)

Executes a function concurrently for each item in inp_list using a process pool. Ideal for CPU-bound tasks.

from structai import multi_process

def heavy_computation(n):
    return sum(range(n))

inputs = [{"n": 1000000} for _ in range(5)]
results = multi_process(inputs, heavy_computation)

run_server(host="0.0.0.0", port=8001)

Starts a FastAPI server that acts as a proxy to an OpenAI-compatible LLM provider.

from structai import run_server

if __name__ == "__main__":
    run_server()

timeout_limit(timeout=None)

A decorator that enforces a maximum execution time on a function. Raises TimeoutError if the limit is exceeded.

from structai import timeout_limit
import time

@timeout_limit(timeout=2.0)
def task():
    time.sleep(5)

# This will raise TimeoutError
task()

run_with_timeout(func, args=(), kwargs=None, timeout=None)

Runs a function with a specified timeout without using a decorator.

from structai import run_with_timeout

def task(x):
    return x * 2

result = run_with_timeout(task, args=(10,), timeout=1.0)

parse_think_answer(text)

Parses a string containing Chain-of-Thought tags (<think>...</think> and <answer>...</answer>) and returns the content of both.

from structai import parse_think_answer

raw_text = "<think>Step 1...</think><answer>42</answer>"
think, answer = parse_think_answer(raw_text)
print(f"Reasoning: {think}")
print(f"Result: {answer}")

extract_within_tags(content, start_tag='<answer>', end_tag='</answer>', default_return=None)

Extracts the substring found between two specific tags.

from structai import extract_within_tags

text = "Result: <json>{...}</json>"
json_str = extract_within_tags(text, "<json>", "</json>")

get_all_file_paths(directory, suffix='')

Recursively retrieves all file paths in a directory that match a given suffix.

from structai import get_all_file_paths

# Get all Python files in the current directory
py_files = get_all_file_paths(".", suffix=".py")
print(py_files)

remove_tag(s, tags=["<think>", "</think>", "<answer>", "</answer>"], r="\n")

Removes specified tags from a string, replacing them with a separator (default newline).

from structai import remove_tag

clean_text = remove_tag("<think>...</think> Answer")

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

structai-0.1.2.tar.gz (19.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

structai-0.1.2-py3-none-any.whl (18.1 kB view details)

Uploaded Python 3

File details

Details for the file structai-0.1.2.tar.gz.

File metadata

  • Download URL: structai-0.1.2.tar.gz
  • Upload date:
  • Size: 19.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.19

File hashes

Hashes for structai-0.1.2.tar.gz
Algorithm Hash digest
SHA256 719d3c42b6d69753302b342ad35f0eab7a995c7290c966659e933246c36465f2
MD5 6365f591598287bb1f70eb595c4ba047
BLAKE2b-256 264e926d9186a66d4f4ec892f84064f306b41e0f61071665f843fd99f4420ad0

See more details on using hashes here.

File details

Details for the file structai-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: structai-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 18.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.19

File hashes

Hashes for structai-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 8dd4ec98360bc8c976c587e8c5e8fb0d013ca85819b4c2f389ebf1bea0fe0c7c
MD5 83e0b552c856d56d7f45b93df94d74e6
BLAKE2b-256 8dc254af8b03824cc4bda6c762c41dc8d15a6f2477d3e55e260ff0a97796ca6f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page