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[源代码]

基类: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.

参数:

value -- Integer or string representation of an ID.

返回:

Validated integer ID.

返回类型:

int

抛出:

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

示例

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

基类: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.

参数:

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

返回:

Validated integer value.

返回类型:

int

抛出:

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

示例

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

基类:object

Custom type for boolean fields with validation.

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

参数:

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

返回:

Validated boolean value.

返回类型:

bool

抛出:

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

示例

>>> 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[源代码]

基类: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)).

参数:

value -- String value to validate.

返回:

Validated string value.

返回类型:

str

抛出:

PydanticCustomError -- If string exceeds maximum length limit.

示例

>>> 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()[源代码]
返回类型:

int

class ahvn.ukf.types.UKFMediumTextType[源代码]

基类: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)).

参数:

value -- String value to validate.

返回:

Validated string value.

返回类型:

str

抛出:

PydanticCustomError -- If string exceeds maximum length limit.

示例

>>> 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()[源代码]
返回类型:

int

class ahvn.ukf.types.UKFLongTextType[源代码]

基类: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)).

参数:

value -- String value to validate.

返回:

Validated string value.

返回类型:

str

抛出:

PydanticCustomError -- If string exceeds maximum length limit.

示例

>>> 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()[源代码]
返回类型:

int

class ahvn.ukf.types.UKFTimestampType[源代码]

基类: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.

参数:

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

返回:

UTC datetime with microseconds stripped.

返回类型:

datetime.datetime

抛出:

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

示例

>>> 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[源代码]

基类:timedelta

Custom type for duration fields with validation.

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

参数:

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

返回:

Validated timedelta object.

返回类型:

datetime.timedelta

抛出:

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

示例

>>> 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[源代码]

基类: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.

参数:

value -- Dictionary object or JSON string to validate.

返回:

Validated dictionary object.

返回类型:

dict

抛出:

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

示例

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

基类: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.

参数:

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

返回:

Set of string tags.

返回类型:

set

抛出:

TypeError -- If value cannot be iterated over.

示例

>>> 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[源代码]

基类:UKFTagsType

name = 'auths'
class ahvn.ukf.types.UKFSynonymsType[源代码]

基类: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.

参数:

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

返回:

Set of string synonyms.

返回类型:

set

抛出:

TypeError -- If value cannot be iterated over.

示例

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

基类: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.

参数:

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

返回:

Set of 5-element relation tuples with normalized types.

返回类型:

set

抛出:

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

示例

>>> 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=(), /)[源代码]

基类: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.

参数:

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

返回:

List of floats representing the vector.

返回类型:

list

抛出:

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

示例

>>> 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'