Skip to content

bast-ai-base

Version: 0.6.4 Module: bast_ai.base, bast_ai.crypt, bast_ai.utils Path: src/python/base

Overview

The foundation library for all Bast AI services. Provides core utilities, type validation, file operations, text processing, cryptography, and common patterns used throughout the platform.

Features

Core Classes

Class Description
BastObject Base class for all Bast objects with logging
BastAbstractObject Abstract base class with enforced interface
ObjectEnforcer Type validation utilities
Stopwatch Performance timing measurements
IdealWrapper Wrapper utilities for result handling

File Operations (FileIO)

from bast_ai.base import FileIO

# JSON operations
data = FileIO.read_json("path/to/file.json")
FileIO.write_json("path/to/output.json", data)

# YAML operations
config = FileIO.read_yaml("path/to/config.yaml")

# CSV operations
df = FileIO.read_csv("path/to/data.csv")

# Text file operations
lines = FileIO.read_lines("path/to/file.txt")
FileIO.write_lines("path/to/output.txt", lines)

Text Utilities (TextUtils)

from bast_ai.base import TextUtils

# Text manipulation
cleaned = TextUtils.clean_text(raw_text)
normalized = TextUtils.normalize(text)

# NLP operations
tokens = TextUtils.tokenize(text)
sentences = TextUtils.split_sentences(text)

Type Validation (ObjectEnforcer)

from bast_ai.base import ObjectEnforcer

# Type checking
ObjectEnforcer.is_str(value, "value must be string")
ObjectEnforcer.is_list(value, "value must be list")
ObjectEnforcer.is_dict(value, "value must be dict")
ObjectEnforcer.is_not_none(value, "value cannot be None")

Environment Variables (EnvIO)

from bast_ai.utils import EnvIO

# Type-safe environment access
api_key = EnvIO.str_or_exception("API_KEY")   # raises if absent
port = EnvIO.int_or_default("PORT", 8080)
debug = EnvIO.is_true("DEBUG")                # False when unset

⚠️ int_or_default and float_or_default return None, not the default, when the variable is set to something unparseable — exists() is true, and as_int() swallows the ValueError. They also pass 0 and negatives straight through. Validate the result yourself where a bad value must not propagate.

### Cryptography (Crypto)

```python
from bast_ai.crypt import Crypto

# Encryption/decryption
encrypted = Crypto.encrypt(data)
decrypted = Crypto.decrypt(encrypted)

# Hashing
hashed = Crypto.hash_password(password)
is_valid = Crypto.verify_password(password, hashed)

Timing (Stopwatch)

from bast_ai.base import Stopwatch

sw = Stopwatch()
sw.start()
# ... operation ...
sw.stop()
print(f"Duration: {sw.duration:.2f}s")

Common Utilities

from bast_ai.base import odds_of, flatten_list, prov_stack

# Random probability
if odds_of(50):  # 50% chance
    do_something()

# Flatten nested lists
flat = flatten_list([[1, 2], [3, [4, 5]]])  # [1, 2, 3, 4, 5]

# Provenance tracking
stack = prov_stack()

Dependencies

External Dependencies

Package Version Purpose
pydantic >=2.11 Data validation
pandas >=2.3 Data analysis
spacy 3.8.7 NLP processing
nltk 3.9.1 Natural language toolkit
cryptography >=45 Encryption
PyYAML 6.0.2 YAML parsing
requests ^2.32 HTTP client
langchain >=0.1.0 LLM framework
langchain-openai >=0.1.0 OpenAI integration
rdflib ^7.1.4 RDF/OWL support
scipy ^1.15 Scientific computing
bcrypt ^4.3.0 Password hashing
python-dotenv ^1.1 Environment variables
aiofiles ^24.1 Async file operations
ddgs ^9.6 Web search
google-api-python-client ^2.0 Google APIs
biopython ^1.85 Bioinformatics

Testing

Unit Tests (15 files)

Located in src/python/base/tests/: - Core class tests - FileIO tests - TextUtils tests - Crypto tests - Utility function tests

Running Tests

# Run all tests with coverage
pants test --output=all --use-coverage \
  --coverage-py-filter="['bast_ai.base']" \
  src/python/base:: -- -s --no-header

# Run specific test
pants test src/python/base/tests/test_file_io.py

Issues & Improvements

Current Issues

  1. Large dependency footprint: The base library has 30+ dependencies which increases bundle size
  2. Mixed responsibilities: Some utilities could be split into separate packages

Suggested Improvements

  1. Modular sub-packages: Split into bast-ai-base-core, bast-ai-base-nlp, bast-ai-base-crypto
  2. Optional dependencies: Make NLP dependencies (spacy, nltk) optional
  3. Async support: Add async versions of FileIO operations
  4. Type hints: Increase type hint coverage to 100%

Changelog

v0.6.4 (Current)

  • Updated pydantic to >=2.11
  • Added ddgs for web search
  • Updated spacy to 3.8.7

v0.6.3

  • Added langchain integration
  • Updated pandas to >=2.3

Usage Example

from bast_ai.base import (
    BastObject,
    FileIO,
    TextUtils,
    ObjectEnforcer,
    Stopwatch,
    EnvIO
)

class MyService(BastObject):
    def __init__(self, config_path: str):
        BastObject.__init__(self, __name__)
        ObjectEnforcer.is_str(config_path)

        self.config = FileIO.read_yaml(config_path)
        self.api_key = EnvIO.str_or_exception("API_KEY")

    def process(self, text: str) -> dict:
        sw = Stopwatch()
        sw.start()

        cleaned = TextUtils.clean_text(text)
        tokens = TextUtils.tokenize(cleaned)

        sw.stop()
        self.logger.info(f"Processed in {sw.duration:.2f}s")

        return {"tokens": tokens, "duration": sw.duration}