Core SDK Reference
ContextUnit
The ContextUnit is the atomic unit of data exchange across the entire ContextUnity mesh. Instead of passing fragmented strings or dicts between services, every request and response is wrapped in a ContextUnit.
This ensures that metadata (like provenance tracing) travels alongside the payload, enabling full observability.
from contextunity.core import ContextUnit
unit = ContextUnit( payload={"key": "value"}, provenance=["service:action"],)
# Serialize to protobufproto = unit.to_protobuf(pb2_module)
# Deserialize from protobufunit = ContextUnit.from_protobuf(proto)
# JSON serializationjson_data = unit.model_dump()ContextToken & TokenBuilder
The ContextToken provides stateless authentication. Rather than hitting a database to check if a request is authorized, the TokenBuilder cryptographically signs the token.
- Minting: Creates a root token for a tenant with specific permissions.
- Validation: Ensures the token is mathematically valid, not expired, and has the required permission (used extensively by the
SecurityGuard). - Attenuation: Allows a service to create a “lesser” token (delegation) for a background worker, restricting its permissions to only what is strictly necessary.
from contextunity.core.tokens import ContextToken, TokenBuilder
# Create a builderbuilder = TokenBuilder(enabled=True)
# Mint a root tokentoken = builder.mint_root( user_ctx={}, permissions=["brain:read", "brain:write"], ttl_s=3600, allowed_tenants=["my_project"], user_id="user_123",)
# Validatetoken.has_permission("brain:read") # Truetoken.can_access_tenant("my_project") # Truetoken.is_expired() # False
# Attenuate (delegate with fewer permissions)child = builder.attenuate( token, permissions=["brain:read"], # Subset only agent_id="sub-agent",)
# Verify (raises PermissionError if invalid)builder.verify(token, required_permission="brain:read")SharedConfig
To prevent “hidden” environmental variables spread across the codebase, contextunity.core enforces centralized configuration via Pydantic. By using SharedConfig, all loaded environment variables are strictly typed and validated at startup.
If a required variable is missing or malformed, the application fails fast during boot rather than crashing later in production.
from contextunity.core.config import SharedConfig, load_shared_config_from_env
# Load from environment variablesconfig = load_shared_config_from_env()
# Access validated settingsprint(config.log_level) # LogLevel.INFOprint(config.redis_url) # None or "redis://..."print(config.otel_enabled) # Falseprint(config.security.enabled) # FalseLogging
All ContextUnity services must use structured, unified logging. The get_contextunit_logger ensures logs are formatted correctly for DataDog or ELK stacks.
More importantly, it forces the use of safe_log_value() to prevent accidental leakage of API Keys, LLM Provider tokens, or PII into the observability stack.
from contextunity.core.logging import get_contextunit_logger, safe_log_value
logger = get_contextunit_logger(__name__)
# Safe logging of sensitive valueslogger.info("API Key: %s", safe_log_value(api_key))The safe_log_value() helper automatically masks API keys, tokens, and passwords in log output.
gRPC Utilities
from contextunity.core.grpc_utils import create_channel_sync
# Create a gRPC channel with standard configurationchannel = create_channel_sync("localhost:50051")
# Use with service stubsfrom contextunity.core import brain_pb2_grpcstub = brain_pb2_grpc.BrainServiceStub(channel)Exception Types
from contextunity.core.exceptions import ( ContextUnityError, # Base exception for all ContextUnity errors ConfigurationError, # Invalid configuration SecurityError, # Security/auth failures RetrievalError, # Knowledge retrieval failures ProviderError, # LLM/storage provider failures ConnectorError, # Data source connector failures ModelError, # LLM model errors TransformerError, # Data transformer failures IngestionError, # Data ingestion failures StorageError, # Storage backend failures DatabaseConnectionError, # Database connection failures GraphBuilderError, # Graph construction failures IntentDetectionError, # Intent classification failures)