ahvn.ukf.types module

Custom Pydantic field types for UKF schema compatibility.

This module provides custom Pydantic field types that handle validation, serialization, and database mapping for the Universal Knowledge Framework. These types enable BaseUKF to serve as a single source of truth for schema definitions across different storage backends.

class ahvn.ukf.types.UKFIdType[source]

Bases: int

Custom type for UKF ID fields with validation and formatting.

Validates and converts values to integer IDs, supporting both raw integers and formatted hash strings with underscores or dashes.

It is recommended to use integer IDs generated from md5hash in hash_utils.

Parameters:

value – Integer or string representation of an ID.

Returns:

Validated integer ID.

Return type:

int

Raises:

PydanticCustomError – If value cannot be converted to a valid integer ID.

Examples

>>> UKFIdType._validate(123)
123
>>> UKFIdType._validate("000123")
123
name = 'id'
class ahvn.ukf.types.UKFIntegerType[source]

Bases: int

Custom type for integer fields with validation.

Validates and converts values to integers, providing consistent handling of numeric inputs including integers, floats and string representations.

Parameters:

value – Integer, float, or string representation of an integer.

Returns:

Validated integer value.

Return type:

int

Raises:

PydanticCustomError – If value cannot be converted to a valid integer.

Examples

>>> UKFIntegerType._validate(123)
123
>>> UKFIntegerType._validate(123.0)
123
>>> UKFIntegerType._validate("123")
123
name = 'int'
class ahvn.ukf.types.UKFBooleanType[source]

Bases: object

Custom type for boolean fields with validation.

Validates and converts various representations to boolean values, supporting common string representations and numeric values.

Parameters:

value – Boolean, integer, string, or other value to convert.

Returns:

Validated boolean value.

Return type:

bool

Raises:

PydanticCustomError – If value cannot be converted to a valid boolean.

Examples

>>> UKFBooleanType._validate(True)
True
>>> UKFBooleanType._validate("true")
True
>>> UKFBooleanType._validate(1)
True
>>> UKFBooleanType._validate("false")
False
>>> UKFBooleanType._validate(0)
False
name = 'bool'
class ahvn.ukf.types.UKFShortTextType[source]

Bases: str

Custom type for short text fields with length validation.

Validates string length against configurable short text limit from config.yaml. Default limit is 255 characters (equivalent to SQL VARCHAR(255)).

Parameters:

value – String value to validate.

Returns:

Validated string value.

Return type:

str

Raises:

PydanticCustomError – If string exceeds maximum length limit.

Examples

>>> UKFShortTextType._validate("Hello world")
'Hello world'
>>> UKFShortTextType._validate("a" * 256)  # Assuming 255 char limit
PydanticCustomError: short_text_too_long
name = 'short_text'
classmethod max_length()[source]
Return type:

int

class ahvn.ukf.types.UKFMediumTextType[source]

Bases: str

Custom type for medium text fields with length validation.

Validates string length against configurable medium text limit from config.yaml. Default limit is 2047 characters (equivalent to SQL VARCHAR(2047)).

Parameters:

value – String value to validate.

Returns:

Validated string value.

Return type:

str

Raises:

PydanticCustomError – If string exceeds maximum length limit.

Examples

>>> UKFMediumTextType._validate("Medium length text")
'Medium length text'
>>> UKFMediumTextType._validate("a" * 2048)  # Assuming 2047 char limit
PydanticCustomError: medium_text_too_long
name = 'medium_text'
classmethod max_length()[source]
Return type:

int

class ahvn.ukf.types.UKFLongTextType[source]

Bases: str

Custom type for long text fields with length validation.

Validates string length against configurable long text limit from config.yaml. Default limit is 65535 characters (equivalent to SQL VARCHAR(65535)).

Parameters:

value – String value to validate.

Returns:

Validated string value.

Return type:

str

Raises:

PydanticCustomError – If string exceeds maximum length limit.

Examples

>>> UKFLongTextType._validate("Very long text content")
'Very long text content'
>>> UKFLongTextType._validate("a" * 65536)  # Assuming 65535 char limit
PydanticCustomError: long_text_too_long
name = 'long_text'
classmethod max_length()[source]
Return type:

int

class ahvn.ukf.types.UKFTimestampType[source]

Bases: datetime

Custom type for datetime fields with UTC conversion and validation.

Validates and normalizes datetime values to UTC timezone with microseconds stripped for consistency. Supports various input formats including ISO strings, timestamps, and datetime objects.

Parameters:

value – Datetime, ISO string, timestamp (int/float), or datetime object.

Returns:

UTC datetime with microseconds stripped.

Return type:

datetime.datetime

Raises:

PydanticCustomError – If value cannot be converted to a valid datetime.

Examples

>>> UKFTimestampType._validate("2023-01-01T12:00:00Z")
datetime.datetime(2023, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)
>>> UKFTimestampType._validate(1672574400)  # Unix timestamp
datetime.datetime(2023, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)
name = 'timestamp'
class ahvn.ukf.types.UKFDurationType[source]

Bases: timedelta

Custom type for duration fields with validation.

Validates and converts various representations to timedelta objects, supporting ISO 8601 duration strings and numeric seconds.

Parameters:

value – Timedelta, ISO 8601 duration string, or numeric seconds.

Returns:

Validated timedelta object.

Return type:

datetime.timedelta

Raises:

PydanticCustomError – If value cannot be converted to a valid timedelta.

Examples

>>> UKFDurationType._validate("P1DT2H")  # 1 day, 2 hours
datetime.timedelta(days=1, hours=2)
>>> UKFDurationType._validate(3600)  # 1 hour in seconds
datetime.timedelta(seconds=3600)
name = 'duration'
class ahvn.ukf.types.UKFJsonType[source]

Bases: dict

Custom type for JSON fields with validation and parsing.

Validates and converts JSON data, supporting both dictionary objects and JSON string representations. Uses custom JSON parser for consistency.

Parameters:

value – Dictionary object or JSON string to validate.

Returns:

Validated dictionary object.

Return type:

dict

Raises:

PydanticCustomError – If JSON string cannot be parsed or value is invalid.

Examples

>>> UKFJsonType._validate({"key": "value"})
{'key': 'value'}
>>> UKFJsonType._validate('{"key": "value"}')
{'key': 'value'}
>>> UKFJsonType._validate(None)
{}
name = 'json'
class ahvn.ukf.types.UKFTagsType[source]

Bases: set

Custom type for tags set with validation and serialization.

Validates and converts various iterable types to a set of string tags. Handles None values gracefully by returning empty set. Also supports auth tuples which are converted to “[user:authority]” tag format.

Parameters:

value – Set, list, tuple, or other iterable of tag values. Can also include auth tuples (user, authority) which are converted to tags.

Returns:

Set of string tags.

Return type:

set

Raises:

TypeError – If value cannot be iterated over.

Examples

>>> UKFTagsType._validate(["tag1", "tag2"])
{'tag1', 'tag2'}
>>> UKFTagsType._validate({"tag1", "tag2"})
{'tag1', 'tag2'}
>>> UKFTagsType._validate([("user1", "read")])  # Auth tuple as tag
{'[user1:read]'}
>>> UKFTagsType._validate(None)
set()
name = 'tags'
class ahvn.ukf.types.UKFAuthsType[source]

Bases: UKFTagsType

name = 'auths'
class ahvn.ukf.types.UKFSynonymsType[source]

Bases: set

Custom type for synonyms set with validation.

Validates and converts various iterable types to a set of string synonyms. Similar to UKFTagsType but specifically for synonym collections.

Parameters:

value – Set, list, tuple, or other iterable of synonym values.

Returns:

Set of string synonyms.

Return type:

set

Raises:

TypeError – If value cannot be iterated over.

Examples

>>> UKFSynonymsType._validate(["synonym1", "synonym2"])
{'synonym1', 'synonym2'}
>>> UKFSynonymsType._validate(None)
set()
name = 'synonyms'
class ahvn.ukf.types.UKFRelatedType[source]

Bases: set

Custom type for related tuples set with complex validation.

Validates and converts relation tuples with 3-5 elements representing subject-relation-object triples with optional relation_id and relation_resources. Uses UKFIdType validation for all ID fields, supporting both raw integers and formatted hash strings.

Parameters:

value – Set, list, or tuple of relation tuples with format: (subject_id, relation, object_id, [relation_id], [relation_resources])

Returns:

Set of 5-element relation tuples with normalized types.

Return type:

set

Raises:

PydanticCustomError – If any tuple has fewer than 3 elements or invalid ID format.

Examples

>>> UKFRelatedType._validate([(1, "knows", 2)])
{(1, 'knows', 2, None, None)}
>>> UKFRelatedType._validate([(1.0, "works_at", 3.0, 4, '{"since": "2020"}')])
{(1, 'works_at', 3, 4, '{"since": "2020"}')}
>>> UKFRelatedType._validate([("123-456", "relates_to", "789_012")])
{(123456, 'relates_to', 789012, None, None)}
name = 'related'
class ahvn.ukf.types.UKFVectorType(iterable=(), /)[source]

Bases: list

Custom type for vector fields with validation and serialization.

Validates and converts various iterable types to a list of floats. Handles None values gracefully by returning empty list.

Parameters:

value – List, tuple, or other iterable of numeric values.

Returns:

List of floats representing the vector.

Return type:

list

Raises:

TypeError – If value cannot be iterated over or contains non-numeric values.

Examples

>>> UKFVectorType._validate([1, 2, 3])
[1.0, 2.0, 3.0]
>>> UKFVectorType._validate((4.5, 5.5))
[4.5, 5.5]
>>> UKFVectorType._validate(None)
[]
name = 'vector'